From 08c11765d4fe790403229496a8a3ec625a3ca5af Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Wed, 10 Aug 2011 12:36:13 -0700 Subject: [PATCH] base64: fix off-by-one buffer size bug Problem and (trivial) fix reported by Gijs van Tulder in . * lib/base64.c (base64_decode_alloc_ctx): Allocate one more byte. * tests/test-base64.c (main): Catch the bug. --- ChangeLog | 8 ++++++++ lib/base64.c | 6 +++--- tests/test-base64.c | 5 ++--- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/ChangeLog b/ChangeLog index 538c121ab..2ed4429cb 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,11 @@ +2011-08-10 Paul Eggert + + base64: fix off-by-one buffer size bug + Problem and (trivial) fix reported by Gijs van Tulder in + . + * lib/base64.c (base64_decode_alloc_ctx): Allocate one more byte. + * tests/test-base64.c (main): Catch the bug. + 2011-08-10 Eric Blake closein: correct comments diff --git a/lib/base64.c b/lib/base64.c index 99fcc57c3..1f07c7c48 100644 --- a/lib/base64.c +++ b/lib/base64.c @@ -552,10 +552,10 @@ base64_decode_alloc_ctx (struct base64_decode_context *ctx, { /* This may allocate a few bytes too many, depending on input, but it's not worth the extra CPU time to compute the exact size. - The exact size is 3 * inlen / 4, minus 1 if the input ends - with "=" and minus another 1 if the input ends with "==". + The exact size is 3 * (inlen + (ctx ? ctx->i : 0)) / 4, minus 1 if the + input ends with "=" and minus another 1 if the input ends with "==". Dividing before multiplying avoids the possibility of overflow. */ - size_t needlen = 3 * (inlen / 4) + 2; + size_t needlen = 3 * (inlen / 4) + 3; *out = malloc (needlen); if (!*out) diff --git a/tests/test-base64.c b/tests/test-base64.c index c7cad2f7a..b1979b4e7 100644 --- a/tests/test-base64.c +++ b/tests/test-base64.c @@ -184,9 +184,8 @@ main (void) ok = base64_decode_alloc_ctx (&ctx, "hp", 2, &p, &len); ASSERT (ok); - ASSERT (len == 2); - /* Actually this looks buggy. Shouldn't output be 'ghi'? */ - ASSERT (memcmp (p, "gh", len) == 0); + ASSERT (len == 3); + ASSERT (memcmp (p, "ghi", len) == 0); ok = base64_decode_alloc_ctx (&ctx, "", 0, &p, &len); ASSERT (ok); } -- 2.11.0