[PATCH 4.14 28/57] crypto: ecdh - avoid buffer overflow in ecdh_set_secret()

Greg Kroah-Hartman
2021-01-11T13:08:25Z

From: Ard Biesheuvel <ardb@kernel.org>

commit 0aa171e9b267ce7c52d3a3df7bc9c1fc0203dec5 upstream.

Pavel reports that commit 17858b140bf4 ("crypto: ecdh - avoid unaligned
accesses in ecdh_set_secret()") fixes one problem but introduces another:
the unconditional memcpy() introduced by that commit may overflow the
target buffer if the source data is invalid, which could be the result of
intentional tampering.

So check params.key_size explicitly against the size of the target buffer
before validating the key further.

Fixes: 17858b140bf4 ("crypto: ecdh - avoid unaligned accesses in ecdh_set_secret()")
Reported-by: Pavel Machek <pavel@denx.de>
Cc: <stable@vger.kernel.org>
Signed-off-by: Ard Biesheuvel <ardb@kernel.org>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

---
crypto/ecdh.c | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)

--- a/crypto/ecdh.c
+++ b/crypto/ecdh.c
@@ -43,7 +43,8 @@ static int ecdh_set_secret(struct crypto
struct ecdh params;
unsigned int ndigits;

- if (crypto_ecdh_decode_key(buf, len, &params) < 0)
+ if (crypto_ecdh_decode_key(buf, len, &params) < 0 ||
+ params.key_size > sizeof(ctx->private_key))
return -EINVAL;

ndigits = ecdh_supported_curve(params.curve_id);