From 59eecb0e9eae6a5168b145cb880b022b4b5991e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Fri, 16 Nov 2018 10:54:54 +0100 Subject: [PATCH] Guard against PSA generating invalid signature The goal is not to double-check everything PSA does, but to ensure that it anything goes wrong, we fail cleanly rather than by overwriting a buffer. --- library/pk_wrap.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/library/pk_wrap.c b/library/pk_wrap.c index 301d2266f..3af17d398 100644 --- a/library/pk_wrap.c +++ b/library/pk_wrap.c @@ -784,13 +784,18 @@ static int asn1_write_mpibuf( unsigned char **p, unsigned char *start, memmove( *p, start, len ); /* ASN.1 DER encoding requires minimal length, so skip leading 0s. - * Neither r nor s can be 0, so we can assume len > 0 at all times. */ - while( **p == 0x00 ) + * Neither r nor s should be 0, but as a failsafe measure, still detect + * that rather than overflowing the buffer in case of a PSA error. */ + while( len > 0 && **p == 0x00 ) { ++(*p); --len; } + /* this is only reached if the signature was invalid */ + if( len == 0 ) + return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED ); + /* if the msb is 1, ASN.1 requires that we prepend a 0. * Neither r nor s can be 0, so we can assume len > 0 at all times. */ if( **p & 0x80 )