CVE-2021-3711: SM2 decrypt buffer overflow
A bug in OpenSSL's SM2 decryption causes the buffer size calculated on the first call to EVP_PKEY_decrypt() to be smaller than the actual plaintext size, leading to a heap buffer overflow on the second call. An attacker who can supply SM2 ciphertext for decryption could overflow the buffer by up to 62 bytes, potentially altering adjacent data or crashing the application.
- Fixed in 5 hours
- Paid in 5 hours
- Disclosed after 5 hours
Summary by the program
OpenSSL Advisory: https://www.openssl.org/news/secadv/20210824.txt
The report
CVE-2021-3711 In order to decrypt SM2 encrypted data an application is expected to call the API function EVP_PKEY_decrypt(). Typically an application will call this function twice. The first time, on entry, the "out" parameter can be NULL and, on exit, the "outlen" parameter is populated with the buffer size required to hold the decrypted plaintext. The application can then allocate a sufficiently sized buffer and call EVP_PKEY_decrypt() again, but this time passing a non-NULL value for the "out" parameter. A bug in the implementation of the SM2 decryption code means that the calculation of the buffer size required to hold the plaintext returned by the first call to EVP_PKEY_decrypt() can be smaller than the actual size required by the second call. This can lead to a buffer overflow when EVP_PKEY_decrypt() is called by the application a second time with a buffer that is too small.
Reproduce step:
Examples of data that triggered the vulnerability
- SM2 ciphertext data
Examples of ciphertext data are as follows:
3072022070DAD60CDA7C30D64CF4F278A849003581223F5324BFEC9BB329229BFFAD21A6021F18AFAB2B35459D2643243B242BE4EA80C6FA5071D2D847340CC57EB9309E5D04200B772E4DB664B2601E3B85E39E4DB664B2601E3B85E39C4AA308BE13588C301308E3588C01308E3588E3308E4
- Parse SM2 ciphertext
The length of this ciphertext is 116 bytes. Parse this group of ciphertexts according to the ASN.1 format:
3072 //30 indicates the SEQUENCE type, 72 indicates that the total length of the subsequent data is 114 bytes
0220 //02 means INTEGER type, 20 means the length of the integer is 32 bytes
70DAD60CDA7C30D64CF4F278A849003581223F5324BFEC9BB329229BFFAD21A6 //32-byte XCoordinate
021F //02 means INTEGER type, 1F means the length of the integer is 31 bytes
18AFAB2B35459D2643243B242BE4EA80C6FA5071D2D847340CC57EB9309E5D //31-byte YCoordinate
0420 //04 means OCTETSTRING type, 20 means the length of the string is 32 bytes
0B772E4DB664B2601E3B85E39C4AA8C2C1910308BE13B331E009C5A9258C29FD //32-byte HASH
040B //04 means OCTETSTRING type, 0B means the length of the string is 11 bytes
6D588BE9260A94DA18E0E6 //11-byte ciphertext
After verification, the above-mentioned XCoordinate and YCoordinate satisfy the SM2 elliptic curve equation.
- Trigger heap overflow
When pkey_sm2_decrypt is called for the first time, the pointer out is NULL and msg_len is equal to 116. The sm2_plaintext_size function returns 10 (msg_len-overhead = 116-106).
10 bytes of memory are allocated through OPENSSL_malloc, and out points to this memory.
The second call to pkey_sm2_decrypt, since the ciphertext has 11 bytes, the decryption result is also 11 bytes.
The memory pointed to by out is 10 bytes, and the decrypted result is 11 bytes, resulting in 1 byte being written out of bounds.
Impact
A malicious attacker who is able present SM2 content for decryption to an application could cause attacker chosen data to overflow the buffer by up to a maximum of 62 bytes altering the contents of other data held after the buffer, possibly changing application behaviour or causing the application to crash. The location of the buffer is application dependent but is typically heap allocated.
OpenSSL versions 1.1.1k and below are affected by this issue. Users of these versions should upgrade to OpenSSL 1.1.1l.
OpenSSL 1.0.2 is not impacted by this issue.
OpenSSL 3.0 alpha/beta releases are also affected but this issue will be addressed before the final release.
Context
This report concerns OpenSSL, the library behind TLS and a great deal of other cryptographic work, and specifically its SM2 decryption path. SM2 is a Chinese national public key algorithm, and OpenSSL exposes SM2 decryption through the EVP API, in particular EVP_PKEY_decrypt().
The normal contract for EVP_PKEY_decrypt() is a two-call pattern. On the first call the application passes a NULL out pointer, and on return the outlen parameter holds the buffer size needed for the decrypted plaintext. The application then allocates a buffer of that size and calls EVP_PKEY_decrypt() again with a non-NULL out pointer to receive the plaintext.
The bug is that the size returned by the first call can be smaller than the size the second call actually needs. The report is filed as CVE-2021-3711, a classic buffer overflow, rated high severity, against the OpenSSL repository. The program summary points to the OpenSSL advisory at https://www.openssl.org/news/secadv/20210824.txt.
Setup
The report does not describe any account, role or tooling setup. What it does establish is the affected surface: OpenSSL versions 1.1.1k and below are affected, and users of those versions should upgrade to OpenSSL 1.1.1l. OpenSSL 1.0.2 is not impacted. OpenSSL 3.0 alpha/beta releases are also affected, but the issue was to be addressed before the final release.
The precondition for triggering the bug is an application that decrypts attacker-supplied SM2 ciphertext through EVP_PKEY_decrypt() using the standard two-call pattern.
Finding it
The SM2 decryption implementation computes the plaintext size in sm2_plaintext_size. The relevant internal function is sm2_plaintext_size, which derives the required buffer length from the ciphertext length by subtracting a fixed overhead. The second call to pkey_sm2_decrypt performs the actual decryption, and the report shows that the two calculations can disagree.
The disagreement is what makes the first call under-report the buffer size, so the application allocates too little memory and the second call writes past the end of it.
Exploitation
Step 1: Obtain SM2 ciphertext that triggers the mismatch
The report gives an example of ciphertext data that triggered the vulnerability:
[redacted]
This ciphertext is 116 bytes long.
Step 2: Parse the ciphertext as ASN.1
The researcher parses the blob according to the ASN.1 format, field by field:
3072 //30 indicates the SEQUENCE type, 72 indicates that the total length of the subsequent data is 114 bytes
0220 //02 means INTEGER type, 20 means the length of the integer is 32 bytes
[redacted] //32-byte XCoordinate
021F //02 means INTEGER type, 1F means the length of the integer is 31 bytes
[redacted] //31-byte YCoordinate
0420 //04 means OCTETSTRING type, 20 means the length of the string is 32 bytes
[redacted] //32-byte HASH
040B //04 means OCTETSTRING type, 0B means the length of the string is 11 bytes
6D588BE9260A94DA18E0E6 //11-byte ciphertext
The structure is a SEQUENCE of 114 bytes containing the X coordinate (32 bytes), the Y coordinate (31 bytes), a 32-byte hash and an 11-byte ciphertext. The researcher notes that, after verification, the X and Y coordinates satisfy the SM2 elliptic curve equation.
The important detail is the last field: the actual ciphertext is 11 bytes, while the total blob is 116 bytes.
Step 3: Trigger the heap overflow
The first call to pkey_sm2_decrypt passes a NULL out pointer and msg_len equal to 116. sm2_plaintext_size returns 10, computed as msg_len - overhead, that is 116 - 106. The application allocates 10 bytes with OPENSSL_malloc and points out at that memory.
The second call to pkey_sm2_decrypt decrypts the 11-byte ciphertext, so the decryption result is also 11 bytes. The buffer behind out is only 10 bytes, so 1 byte is written out of bounds.
Root cause
In the example, sm2_plaintext_size returns 10, computed as 116 - 106. The actual plaintext length is determined by the length of the ciphertext field inside the ASN.1 structure, which here is 11 bytes. Because the two values are derived differently, the first call can report a buffer smaller than what the second call writes.
The first call can report a buffer smaller than what the second call writes.
Impact
An attacker who can present SM2 content for decryption to an application could cause attacker-chosen data to overflow the buffer by up to a maximum of 62 bytes, altering the contents of other data held after the buffer. That could change application behaviour or cause the application to crash. The location of the buffer is application dependent but is typically heap allocated.
The impact is conditional on the application decrypting attacker-supplied SM2 ciphertext through the affected API on an affected version.
Fix
The report states that users of OpenSSL 1.1.1k and below should upgrade to OpenSSL 1.1.1l. OpenSSL 1.0.2 is not impacted. The report does not describe the code change itself.
Variants to test
- Two-call size APIs in other cryptographic libraries: any function that returns a required length on a first call and fills a buffer on a second call is a candidate. A positive result is a first-call length smaller than the number of bytes the second call writes.
- ASN.1-parsed ciphertexts with variable-length inner fields: craft structures where the outer length and the inner ciphertext length diverge, as in this report. A positive result is a size prediction based on the outer length that does not match the inner field.
- Fixed-overhead assumptions: look for code that subtracts a constant from a message length to derive a plaintext size. A positive result is any input where the constant does not match the real overhead.
- Other algorithm-specific decrypt paths in the same EVP layer: check whether the same two-call pattern is implemented consistently across algorithms. A positive result is one algorithm whose first and second calls disagree on length.
Hunting notes
This kind of bug hides in size-calculation code that runs before the real parsing or decryption, especially where a constant overhead is assumed. During recon, the signal is an API with a documented two-call pattern, where the first call exists only to report a length. If the length is computed from anything other than the exact data that will be written, the mismatch is worth testing.
The report walks through the exact byte counts: 116-byte input, a 10-byte allocation, an 11-byte result, and 1 byte written out of bounds, with a stated maximum overflow of 62 bytes. The report ties the arithmetic to a valid curve point and an example ciphertext.
What happened, in plain words
OpenSSL is a piece of software that many other programs use to do cryptography: the maths that keeps your web browsing private, checks that a website is who it claims to be, and so on. It is a library, meaning it is not a program you open yourself; it is code that other programs load and call when they need to encrypt or decrypt something.
One of the things OpenSSL can do is decrypt data protected with SM2, a public key algorithm that is a Chinese national standard. This report, filed as CVE-2021-3711, describes a bug in that SM2 decryption code. The bug is a classic buffer overflow, rated high severity. In plain words: a program asks OpenSSL how much memory it will need to hold some decrypted data, OpenSSL answers with a number that is too small, the program reserves that too-small space, and then OpenSSL writes slightly more data into it than fits. The extra bytes land in memory just past the reserved area, where other data lives.
The program summary links to the official OpenSSL advisory at https://www.openssl.org/news/secadv/20210824.txt.
A few ideas before we go further:
- API: a set of functions that one program offers to other programs. Think of a restaurant menu: you do not walk into the kitchen, you order from the menu and the kitchen does the work. Here the menu item is a function called
EVP_PKEY_decrypt(). - Buffer: a reserved block of memory, like a row of numbered lockers. If you reserve ten lockers and then try to put something in locker eleven, you are writing into space that belongs to someone else.
- Heap: the general-purpose pool of memory a program uses for things it creates while running, as opposed to fixed space set aside in advance. Buffers for decrypted data are typically taken from the heap.
- Ciphertext: data that has been encrypted, so it looks like random noise. Plaintext is what you get after decrypting it.
- ASN.1: a standard way of packing several pieces of data into one blob, where each piece is preceded by a small label saying what type it is and how long it is. Think of a parcel with a customs label listing its contents and their sizes.
Context
This report concerns OpenSSL, the library behind TLS and a great deal of other cryptographic work, and specifically its SM2 decryption path. SM2 is a Chinese national public key algorithm, and OpenSSL exposes SM2 decryption through the EVP API, in particular EVP_PKEY_decrypt().
The normal contract for EVP_PKEY_decrypt() is a two-call pattern. On the first call the application passes a NULL out pointer, and on return the outlen parameter holds the buffer size needed for the decrypted plaintext. The application then allocates a buffer of that size and calls EVP_PKEY_decrypt() again with a non-NULL out pointer to receive the plaintext.
That two-call pattern deserves a slower explanation, because everything else depends on it. Imagine you want to post a parcel but you do not know how big the box needs to be. You ring the courier and ask: how big a box do I need for this item? The courier weighs it and tells you a size. You buy a box of that size, put the item in, and hand it over. That is the first call: you pass no box (a NULL out pointer, meaning "no destination yet") and you get back a number (the outlen parameter, the required size). The second call is the actual handover: now you do have a box (a non-NULL out pointer) and the courier fills it.
The whole arrangement only works if the size quoted on the first call is at least as large as what the second call actually needs. The bug is that the size returned by the first call can be smaller than the size the second call actually needs. The report is filed as CVE-2021-3711, a classic buffer overflow, rated high severity, against the OpenSSL repository. The program summary points to the OpenSSL advisory at https://www.openssl.org/news/secadv/20210824.txt.
Setup
The report does not describe any account, role or tooling setup. What it does establish is the affected surface: OpenSSL versions 1.1.1k and below are affected, and users of those versions should upgrade to OpenSSL 1.1.1l. OpenSSL 1.0.2 is not impacted. OpenSSL 3.0 alpha/beta releases are also affected, but the issue was to be addressed before the final release.
A version number here is simply which release of the software you have, like the edition of a book. "1.1.1k and below" means every release up to and including that one carries the flaw; "1.1.1l" is the release where it is fixed. "Alpha/beta" means early test releases that are not yet finished.
The precondition for triggering the bug is an application that decrypts attacker-supplied SM2 ciphertext through EVP_PKEY_decrypt() using the standard two-call pattern. In other words, the application must be willing to decrypt data that an outsider controls, and it must use the ask-for-size-then-fill pattern described above. If it never decrypts untrusted SM2 data, or does not use that pattern, this particular bug does not come into play.
Finding it
The SM2 decryption implementation computes the plaintext size in sm2_plaintext_size. The relevant internal function is sm2_plaintext_size, which derives the required buffer length from the ciphertext length by subtracting a fixed overhead. The second call to pkey_sm2_decrypt performs the actual decryption, and the report shows that the two calculations can disagree.
"Fixed overhead" means a constant number that the code always subtracts, on the assumption that every SM2 ciphertext carries the same amount of extra packaging around the real payload. Going back to the parcel comparison: the code assumes every parcel has exactly the same weight of cardboard and labels, so it subtracts that weight to guess the contents. If a parcel happens to have less packaging than assumed, the guess is wrong.
The disagreement is what makes the first call under-report the buffer size, so the application allocates too little memory and the second call writes past the end of it.
Exploitation
Step 1: Obtain SM2 ciphertext that triggers the mismatch
The report gives an example of ciphertext data that triggered the vulnerability:
[redacted]
This ciphertext is 116 bytes long.
A byte is the basic unit of digital data: one character in a text file is usually one byte. So this blob is 116 characters' worth of data, written out as hexadecimal, which is a way of writing bytes using the digits 0 to 9 and the letters A to F. Each pair of hex characters is one byte. The reason this exact blob matters is that it is shaped in a way that makes the size guess go wrong, as the next step shows.
Step 2: Parse the ciphertext as ASN.1
The researcher parses the blob according to the ASN.1 format, field by field:
3072 //30 indicates the SEQUENCE type, 72 indicates that the total length of the subsequent data is 114 bytes
0220 //02 means INTEGER type, 20 means the length of the integer is 32 bytes
[redacted] //32-byte XCoordinate
021F //02 means INTEGER type, 1F means the length of the integer is 31 bytes
[redacted] //31-byte YCoordinate
0420 //04 means OCTETSTRING type, 20 means the length of the string is 32 bytes
[redacted] //32-byte HASH
040B //04 means OCTETSTRING type, 0B means the length of the string is 11 bytes
6D588BE9260A94DA18E0E6 //11-byte ciphertext
This block is the same 116 bytes, but broken into labelled pieces so a human can see the structure. Each line has a comment after // explaining what the bytes mean. Reading it line by line:
3072:30is the ASN.1 tag for a SEQUENCE, meaning "a bundle of items follows".72is the length of that bundle, written in hex, which is 114 bytes. So the whole bundle is 114 bytes, and with these two header bytes the total is 116.0220:02is the tag for INTEGER, a whole number.20is the length in hex, which is 32 bytes. So a 32-byte number follows.[redacted]: the 32-byte X coordinate, one half of a point on the SM2 curve.021F: again an INTEGER, this time 31 bytes long (1Fin hex is 31).[redacted]: the 31-byte Y coordinate, the other half of the point.0420:04is the tag for OCTET STRING, a raw run of bytes.20is 32 bytes. So a 32-byte blob follows.[redacted]: that 32-byte blob, labelled HASH in the report.040B: another OCTET STRING, this time 11 bytes long (0Bin hex is 11).6D588BE9260A94DA18E0E6: the 11-byte ciphertext, the actual encrypted payload.
The structure is a SEQUENCE of 114 bytes containing the X coordinate (32 bytes), the Y coordinate (31 bytes), a 32-byte hash and an 11-byte ciphertext. The researcher notes that, after verification, the X and Y coordinates satisfy the SM2 elliptic curve equation.
That last sentence is worth unpacking. SM2 is built on an elliptic curve, which is a particular kind of mathematical curve. A point on the curve is described by two numbers, X and Y, and not every pair of numbers is a valid point: the pair has to satisfy the curve's equation.
The important detail is the last field: the actual ciphertext is 11 bytes, while the total blob is 116 bytes. Keep those two numbers in mind, because the bug lives in the gap between them.
Step 3: Trigger the heap overflow
The first call to pkey_sm2_decrypt passes a NULL out pointer and msg_len equal to 116. sm2_plaintext_size returns 10, computed as msg_len - overhead, that is 116 - 106. The application allocates 10 bytes with OPENSSL_malloc and points out at that memory.
In plain words: the application asks "how much room do I need?" and hands over the total blob length, 116. The size function subtracts its fixed overhead of 106 and answers 10. OPENSSL_malloc is OpenSSL's memory allocation function, the equivalent of booking a row of lockers; here it books 10 bytes, and out is set to point at the start of that row.
The second call to pkey_sm2_decrypt decrypts the 11-byte ciphertext, so the decryption result is also 11 bytes. The buffer behind out is only 10 bytes, so 1 byte is written out of bounds.
This is the heart of the report. The real payload inside the blob is 11 bytes, so decrypting it produces 11 bytes of plaintext. But only 10 bytes were booked. The eleventh byte is written into the memory immediately after the buffer, which belongs to something else. That is what "out of bounds" means: writing outside the area you reserved. The arithmetic is small, one byte, but the principle is the dangerous part: the program wrote data it was not supposed to touch.
Root cause
In the example, sm2_plaintext_size returns 10, computed as 116 - 106. The actual plaintext length is determined by the length of the ciphertext field inside the ASN.1 structure, which here is 11 bytes. Because the two values are derived differently, the first call can report a buffer smaller than what the second call writes.
Put another way, there are two ways to work out how big the answer will be. One looks at the outside of the parcel and subtracts an assumed packaging weight. The other looks at the label inside and reads the true size of the contents. When the packaging is lighter than assumed, the first method underestimates. The first call can report a buffer smaller than what the second call writes. The application has no way of knowing that the number it was given is wrong; it follows the documented pattern correctly and still ends up with too little memory.
Impact
An attacker who can present SM2 content for decryption to an application could cause attacker-chosen data to overflow the buffer by up to a maximum of 62 bytes, altering the contents of other data held after the buffer. That could change application behaviour or cause the application to crash. The location of the buffer is application dependent but is typically heap allocated.
Why does writing past a buffer matter? Because the memory after the buffer holds other things the program cares about: other variables, bookkeeping data, sometimes addresses the program will later jump to. Overwriting those bytes can make the program behave in ways its author never intended, or simply fall over. The report caps the overflow at 62 bytes, which tells you how much room an attacker has to work with. The impact is conditional on the application decrypting attacker-supplied SM2 ciphertext through the affected API on an affected version.
Fix
The report states that users of OpenSSL 1.1.1k and below should upgrade to OpenSSL 1.1.1l. OpenSSL 1.0.2 is not impacted. The report does not describe the code change itself.
For anyone running affected software, the action is the same as with any patched library: move to the fixed release. You do not need to understand the internals to be safe; you need the version where the internals were corrected.
Variants to test
- Two-call size APIs in other cryptographic libraries: any function that returns a required length on a first call and fills a buffer on a second call is a candidate. A positive result is a first-call length smaller than the number of bytes the second call writes.
- ASN.1-parsed ciphertexts with variable-length inner fields: craft structures where the outer length and the inner ciphertext length diverge, as in this report. A positive result is a size prediction based on the outer length that does not match the inner field.
- Fixed-overhead assumptions: look for code that subtracts a constant from a message length to derive a plaintext size. A positive result is any input where the constant does not match the real overhead.
- Other algorithm-specific decrypt paths in the same EVP layer: check whether the same two-call pattern is implemented consistently across algorithms. A positive result is one algorithm whose first and second calls disagree on length.
Hunting notes
This kind of bug hides in size-calculation code that runs before the real parsing or decryption, especially where a constant overhead is assumed. During recon, the signal is an API with a documented two-call pattern, where the first call exists only to report a length. If the length is computed from anything other than the exact data that will be written, the mismatch is worth testing.
"Recon" here means the early looking-around phase, before any testing: reading documentation and code to spot the shapes of function that are worth probing. The shape to look for is the ask-first, fill-second pattern, because that pattern creates a promise about size, and promises about size can be wrong.
The report walks through the exact byte counts: 116-byte input, a 10-byte allocation, an 11-byte result, and 1 byte written out of bounds, with a stated maximum overflow of 62 bytes. The report ties the arithmetic to a valid curve point and an example ciphertext.
Glossary
- API: a set of functions one piece of software offers to other software, so they can ask it to do work without knowing how it works inside.
- ASN.1: a standard format for packing several labelled pieces of data into one blob, where each piece carries a type tag and a length.
- Buffer: a reserved block of memory used to hold data; writing past its end is a buffer overflow.
- Buffer overflow: a bug where a program writes more data into a buffer than it can hold, so the extra bytes land in neighbouring memory.
- Byte: the basic unit of digital data, usually one character of text; written in hexadecimal as two characters.
- Ciphertext: data that has been encrypted and looks like random noise until decrypted.
- Classic buffer overflow: the traditional form of buffer overflow, where a fixed-size area is overrun by a write that is too large.
- CVE: a public identifier for a known security vulnerability, here CVE-2021-3711.
- Elliptic curve: a particular kind of mathematical curve used in modern cryptography; valid points on it must satisfy its equation.
- EVP API: OpenSSL's general-purpose interface for cryptographic operations, including
EVP_PKEY_decrypt(). - Fixed overhead: a constant amount of packaging the code assumes is present in every message and subtracts when estimating the payload size.
- Heap: the pool of memory a program uses for data it creates while running; buffers for decrypted data are typically allocated there.
- Hexadecimal: a way of writing bytes using the digits 0 to 9 and letters A to F, where each pair of characters is one byte.
- Library: code that other programs load and call, rather than a program you run on its own.
- NULL pointer: a pointer that deliberately points at nothing, used in the first call to mean "I have no destination buffer yet".
- OpenSSL: a widely used library that implements TLS and many cryptographic algorithms, including SM2.
- Out of bounds: writing or reading outside the memory area that was reserved.
- Plaintext: the readable data you get after decrypting ciphertext.
- Pointer: a value that records where in memory something is stored.
- Public key algorithm: a cryptographic scheme that uses a pair of keys, one public and one private, for encryption and signatures.
- Recon: the early phase of looking around, reading documentation and code, to find promising places to test.
- SM2: a Chinese national public key algorithm, supported by OpenSSL for decryption through the EVP API.
- TLS: the protocol that secures web browsing and other network connections, implemented in large part by OpenSSL.
- Two-call pattern: an API convention where the first call reports how much memory is needed and the second call fills a buffer of that size.
- Version: a particular release of a piece of software, such as OpenSSL 1.1.1k.