From 0760d132da046063f6ac3c28bd2ee1d8505e6fcd Mon Sep 17 00:00:00 2001 From: Paul Dreik Date: Fri, 29 Nov 2019 19:23:35 +0100 Subject: [PATCH] Avoid invoking memcpy if size is zero or the supplied buffer is NULL This allows for passing a NULL pointer with zero max_len. Invoking memcpy on NULL is undefined behaviour, even if the size is zero. https://en.cppreference.com/w/c/string/byte/memcpy The function can now be queried for the necessary buffer length. Reviewed-by: Paul Dale Reviewed-by: Tomas Mraz (Merged from https://github.com/openssl/openssl/pull/10541) --- crypto/asn1/evp_asn1.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crypto/asn1/evp_asn1.c b/crypto/asn1/evp_asn1.c index 3122c4724f6..13d8ed3893a 100644 --- a/crypto/asn1/evp_asn1.c +++ b/crypto/asn1/evp_asn1.c @@ -27,7 +27,10 @@ int ASN1_TYPE_set_octetstring(ASN1_TYPE *a, unsigned char *data, int len) return 1; } -/* int max_len: for returned value */ +/* int max_len: for returned value + * if passing NULL in data, nothing is copied but the necessary length + * for it is returned. + */ int ASN1_TYPE_get_octetstring(const ASN1_TYPE *a, unsigned char *data, int max_len) { int ret, num; @@ -43,7 +46,8 @@ int ASN1_TYPE_get_octetstring(const ASN1_TYPE *a, unsigned char *data, int max_l num = ret; else num = max_len; - memcpy(data, p, num); + if (num > 0 && data != NULL) + memcpy(data, p, num); return ret; } -- 2.47.2