From 5f52622aa9140f75927fb1c94547c08c5212899e Mon Sep 17 00:00:00 2001 From: Adam Vartanian Date: Mon, 10 Apr 2017 15:51:16 +0100 Subject: CVE 2016-2109 fix Read ASN.1 data in chunks to prevent invalid inputs from allocating excessive amounts of data. Bug: 35443725 Test: run cts -m CtsLibcoreTestCases Test: manually ran testcase from OpenSSL Change-Id: Ia9d6aa40726c0cba26e2060108112f33e00e8270 Merged-In: Ie00536d7ad815464b2b031f7bcd1b683e12c1623 Merged-In: If087a69ee075b3c5323abb8d7d740e92bd703bb1 Merged-In: If77e23607fc77f724f50ad0e0b94eef4beae57ea Merged-In: Ia8d0370ece1d5c1750a4331810c610ed5c813224 Merged-In: Ia945d5ce50335919b0783fe909892703213454ef (cherry picked from commit ea156ae109eac7b7cf7d4f6a76f3c4590734789b) --- src/crypto/asn1/a_d2i_fp.c | 47 ++++++++++++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/src/crypto/asn1/a_d2i_fp.c b/src/crypto/asn1/a_d2i_fp.c index 6022c74..5c5d775 100644 --- a/src/crypto/asn1/a_d2i_fp.c +++ b/src/crypto/asn1/a_d2i_fp.c @@ -62,7 +62,7 @@ #include #include - +#define ASN1_CHUNK_INITIAL_SIZE (16 * 1024) static int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb); #ifndef NO_OLD_ASN1 @@ -231,6 +231,7 @@ static int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb) want=c.slen; if (want > (len-off)) { + size_t chunk_max = ASN1_CHUNK_INITIAL_SIZE; want-=(len-off); if (want > INT_MAX /* BIO_read takes an int length */ || len+want < len) @@ -238,23 +239,37 @@ static int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb) OPENSSL_PUT_ERROR(ASN1, asn1_d2i_read_bio, ASN1_R_TOO_LONG); goto err; } - if (!BUF_MEM_grow_clean(b,len+want)) - { - OPENSSL_PUT_ERROR(ASN1, asn1_d2i_read_bio, ERR_R_MALLOC_FAILURE); - goto err; - } while (want > 0) { - i=BIO_read(in,&(b->data[len]),want); - if (i <= 0) - { - OPENSSL_PUT_ERROR(ASN1, asn1_d2i_read_bio, ASN1_R_NOT_ENOUGH_DATA); - goto err; - } - /* This can't overflow because - * |len+want| didn't overflow. */ - len+=i; - want-=i; + + /* + * Read content in chunks of increasing size + * so we can return an error for EOF without + * having to allocate the entire content length + * in one go. + */ + size_t chunk = want > chunk_max ? chunk_max : want; + + if (!BUF_MEM_grow_clean(b, len + chunk)) { + OPENSSL_PUT_ERROR(ASN1, asn1_d2i_read_bio, ERR_R_MALLOC_FAILURE); + goto err; + } + want -= chunk; + while (chunk > 0) { + i = BIO_read(in, &(b->data[len]), chunk); + if (i <= 0) { + OPENSSL_PUT_ERROR(ASN1, asn1_d2i_read_bio, ASN1_R_NOT_ENOUGH_DATA); + goto err; + } + /* + * This can't overflow because |len+want| didn't + * overflow. + */ + len += i; + chunk -= i; + } + if (chunk_max < INT_MAX/2) + chunk_max *= 2; } } if (off + c.slen < off) -- cgit v1.2.3