From 004f87b98dd9e5fb685d46b7212f6ca1c82648b3 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Fri, 6 Jul 2018 15:47:54 +0200 Subject: [PATCH] RSA encryption: accept input=NULL if ilen=0 In mbedtls_rsa_rsaes_oaep_encrypt and mbedtls_rsa_rsaes_pkcs1_v15_encrypt, if the input length is 0 (which is unusual and mostly useless, but permitted) then it is fine for the input pointer to be NULL. Don't return an error in this case. When `input` is NULL, `memcpy( p, input, ilen )` has undefined behavior even if `ilen` is zero. So skip the `memcpy` call in this case. Likewise, in `mbedtls_rsa_rsaes_oaep_decrypt`, skip the `memcpy` call if `*olen` is zero. --- library/rsa.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/library/rsa.c b/library/rsa.c index 389d7473e..c8244d302 100644 --- a/library/rsa.c +++ b/library/rsa.c @@ -1171,7 +1171,8 @@ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, p += hlen; p += olen - 2 * hlen - 2 - ilen; *p++ = 1; - memcpy( p, input, ilen ); + if( ilen != 0 ) + memcpy( p, input, ilen ); mbedtls_md_init( &md_ctx ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 ) @@ -1263,7 +1264,8 @@ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, } *p++ = 0; - memcpy( p, input, ilen ); + if( ilen != 0 ) + memcpy( p, input, ilen ); return( ( mode == MBEDTLS_RSA_PUBLIC ) ? mbedtls_rsa_public( ctx, output, output ) @@ -1441,7 +1443,8 @@ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, } *olen = ilen - (p - buf); - memcpy( output, p, *olen ); + if( *olen != 0 ) + memcpy( output, p, *olen ); ret = 0; cleanup: