From: GGAutomaton Date: Sat, 28 Mar 2026 07:41:33 +0000 (-0700) Subject: sm2: check buffer size before writing ciphertext X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=8d165eb843a99c7ed44944620a52cf4c4eba2e22;p=thirdparty%2Fopenssl.git sm2: check buffer size before writing ciphertext The SM2 encryption may write past the caller-provided output buffer when the required ciphertext size exceeds the supplied buffer length. Reject outputs that do not fit in the caller-provided buffer. Reviewed-by: Viktor Dukhovni Reviewed-by: Eugene Syromiatnikov Reviewed-by: Tomas Mraz MergeDate: Wed May 6 16:51:00 2026 (Merged from https://github.com/openssl/openssl/pull/30614) --- diff --git a/crypto/sm2/sm2_crypt.c b/crypto/sm2/sm2_crypt.c index 37993bc8c3f..e7ae6a8bd0b 100644 --- a/crypto/sm2/sm2_crypt.c +++ b/crypto/sm2/sm2_crypt.c @@ -253,12 +253,23 @@ again: goto done; } - ciphertext_leni = i2d_SM2_Ciphertext(&ctext_struct, &ciphertext_buf); + ciphertext_leni = i2d_SM2_Ciphertext(&ctext_struct, NULL); /* Ensure cast to size_t is safe */ if (ciphertext_leni < 0) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; } + + if (*ciphertext_len < (size_t)ciphertext_leni) { + ERR_raise(ERR_LIB_SM2, SM2_R_BUFFER_TOO_SMALL); + goto done; + } + + ciphertext_leni = i2d_SM2_Ciphertext(&ctext_struct, &ciphertext_buf); + if (ciphertext_leni < 0) { + ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); + goto done; + } *ciphertext_len = (size_t)ciphertext_leni; rc = 1;