From 9570f674cc729cafcba65f4cce03552d9a6108f4 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Sat, 23 Jan 2021 21:54:46 -0800 Subject: [PATCH] Avoid passing out-of-bound pointers to 0-size memcpy Doing so could be considered UB in a strict reading of the standard. Avoid it. --- contrib/lax_der_parsing.c | 4 ++-- contrib/lax_der_privatekey_parsing.c | 2 +- src/ecdsa_impl.h | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/contrib/lax_der_parsing.c b/contrib/lax_der_parsing.c index c1627e3..90aed34 100644 --- a/contrib/lax_der_parsing.c +++ b/contrib/lax_der_parsing.c @@ -121,7 +121,7 @@ int ecdsa_signature_parse_der_lax(const secp256k1_context* ctx, secp256k1_ecdsa_ /* Copy R value */ if (rlen > 32) { overflow = 1; - } else { + } else if (rlen) { memcpy(tmpsig + 32 - rlen, input + rpos, rlen); } @@ -133,7 +133,7 @@ int ecdsa_signature_parse_der_lax(const secp256k1_context* ctx, secp256k1_ecdsa_ /* Copy S value */ if (slen > 32) { overflow = 1; - } else { + } else if (slen) { memcpy(tmpsig + 64 - slen, input + spos, slen); } diff --git a/contrib/lax_der_privatekey_parsing.c b/contrib/lax_der_privatekey_parsing.c index 429760f..0653f8e 100644 --- a/contrib/lax_der_privatekey_parsing.c +++ b/contrib/lax_der_privatekey_parsing.c @@ -45,7 +45,7 @@ int ec_privkey_import_der(const secp256k1_context* ctx, unsigned char *out32, co if (end < privkey+2 || privkey[0] != 0x04 || privkey[1] > 0x20 || end < privkey+2+privkey[1]) { return 0; } - memcpy(out32 + 32 - privkey[1], privkey + 2, privkey[1]); + if (privkey[1]) memcpy(out32 + 32 - privkey[1], privkey + 2, privkey[1]); if (!secp256k1_ec_seckey_verify(ctx, out32)) { memset(out32, 0, 32); return 0; diff --git a/src/ecdsa_impl.h b/src/ecdsa_impl.h index 156a33d..c32141e 100644 --- a/src/ecdsa_impl.h +++ b/src/ecdsa_impl.h @@ -140,7 +140,7 @@ static int secp256k1_der_parse_integer(secp256k1_scalar *r, const unsigned char overflow = 1; } if (!overflow) { - memcpy(ra + 32 - rlen, *sig, rlen); + if (rlen) memcpy(ra + 32 - rlen, *sig, rlen); secp256k1_scalar_set_b32(r, ra, &overflow); } if (overflow) {