Skip to content
Memory corruption Disclosed report Advanced CVE-2017-5461

Write beyond bounds caused by bugs in Base64 de/encoding in nssb64d.c and nssb64e.c

The Base64 length-calculation functions in NSS can overflow integers, causing callers to allocate buffers that are too small for the decoded or encoded output. An attacker could then trigger a heap buffer overrun with attacker-controlled data.

q1 Follow

Originally disclosed on Mozilla

Critical View original
  • Fixed in 19 days
  • Paid in 17 days
  • Disclosed after 19 days
Text
PL_Base64MaxDecodedLength() (security\nss\lib\util\nssb64d.c) can cause an integer overflow. If it does, its caller(s) will allocate a buffer too small for the result of a Base64 decoding operation, then possibly overrun it.

For example, PL_Base64DecodeBuffer() (security\nss\lib\util\nssb64d.c) uses the result of PL_Base64MaxDecodedLength() to check whether a caller-provided buffer is long enough, or to allocate a buffer if the caller does not provide one. In either case, the calculated length is inadequate if the length of the encoded string is >= 0x55555556. Once it has calculated the (potentially incorrect) length, it passes it and the corresponding buffer to pl_base64_decode_buffer() (same module) to do the decoding. That function incrementally checks against the provided length (data->output_buflen) but (another bug!) *only in debug builds (i.e. via a PR_ASSERT())*.

The upshot is that PL_Base64DecodeBuffer() might be vulnerable to the same kind of buffer overrun bug as in https://bugzilla.mozilla.org/show_bug.cgi?id=1344081 : an attack that overruns a heap buffer, by an attacker-determined amount, with 3-byte granularity.

There is a similar issue in PL_Base64MaxEncodedLength() and its associated functions for Base64 encoding.

I will try to manifest these bugs and post a POC if and when I do.

The bugs are in lines 373 and 254 (nssb64d.c):

370: static PRUint32
371: PL_Base64MaxDecodedLength (PRUint32 size)
372: {
373:     return ((size * 3) / 4);
374: }

219: static PRStatus
220: pl_base64_decode_buffer (PLBase64Decoder *data, const unsigned char *in,
221: 			 PRUint32 length)
222: {
223:     unsigned char *out = data->output_buffer;
224:     unsigned char *token = data->token;
225:     int i, n = 0;
226: 
227:     i = data->token_size;
228:     data->token_size = 0;
229: 
230:     while (length > 0) {
231: 	while (i < 4 && length > 0) {
...
254: 	   PR_ASSERT((out - data->output_buffer + 3) <= data->output_buflen);

and 288 and potentially 300 (nssb64e.c):

280: static PRUint32
281: PL_Base64MaxEncodedLength (PRUint32 size, PRUint32 line_length)
282: {
283:     PRUint32 tokens, tokens_per_line, full_lines, line_break_chars, remainder;
284: 
285:     tokens = (size + 2) / 3;
286: 
287:     if (line_length == 0)
288: 	      return tokens * 4;
289: 
290:     if (line_length < 4)	/* too small! */
291: 	      line_length = 4;
292: 
293:     tokens_per_line = line_length / 4;
294:     full_lines = tokens / tokens_per_line;
295:     remainder = (tokens - (full_lines * tokens_per_line)) * 4;
296:     line_break_chars = full_lines * 2;
297:     if (remainder == 0)
298: 	   line_break_chars -= 2;
299: 
300:     return (full_lines * tokens_per_line * 4) + line_break_chars + remainder;
301: }

The original report as published on Mozilla's Bugzilla, by q1. Images and videos are our own copies; raw HTML is shown as text. View it on Mozilla's Bugzilla.

The original is short, so this covers everything it reports, then explains this kind of bug in general: how it works, how to test for it and how it is fixed. The general sections are about the bug class, not this target. Written with AI and checked against the original; the original is the record. 5 min read.

What the report shows

The target is Mozilla's Network Security Services (NSS) library, specifically the Base64 utility code in nssb64d.c (decoding) and nssb64e.c (encoding). The researcher, q1, reported that the length-calculation helpers that callers use to size buffers before a Base64 operation can overflow.

The core claim is that PL_Base64MaxDecodedLength() can overflow. When it does, its callers allocate a buffer that is too small for the decoded result and can then overrun it. The report walks through the decoding path:

  1. PL_Base64DecodeBuffer() calls PL_Base64MaxDecodedLength() to check whether a caller-supplied buffer is long enough, or to allocate one when the caller supplies none.
  2. If the encoded string length is >= 0x55555556, the calculated length is inadequate.
  3. The (possibly wrong) length and the buffer are passed to pl_base64_decode_buffer(), which does the decoding.
  4. That function checks incrementally against the provided length (data->output_buflen), but, as the researcher notes with emphasis, only in debug builds, via a PR_ASSERT().

The researcher states the upshot plainly: PL_Base64DecodeBuffer() might be vulnerable to the same kind of buffer overrun as the one in Mozilla bug 1344081, an attack that overruns a heap buffer by an attacker-determined amount with 3-byte granularity. A similar issue is said to exist in PL_Base64MaxEncodedLength() and its associated encoding functions. The report ends by saying a proof of concept will be posted if and when the bugs are manifested; no POC, bounty figure or fix is given in the text.

The report points at the following code. First, the decoding length calculation:

Text
370: static PRUint32
371: PL_Base64MaxDecodedLength (PRUint32 size)
372: {
373:     return ((size * 3) / 4);
374: }

Then the debug-only bounds check inside the decoder:

Text
219: static PRStatus
220: pl_base64_decode_buffer (PLBase64Decoder *data, const unsigned char *in,
221: 			 PRUint32 length)
222: {
223:     unsigned char *out = data->output_buffer;
224:     unsigned char *token = data->token;
225:     int i, n = 0;
226:
227:     i = data->token_size;
228:     data->token_size = 0;
229:
230:     while (length > 0) {
231: 	while (i < 4 && length > 0) {
...
254: 	   PR_ASSERT((out - data->output_buffer + 3) <= data->output_buflen);

And the encoding side:

Text
280: static PRUint32
281: PL_Base64MaxEncodedLength (PRUint32 size, PRUint32 line_length)
282: {
283:     PRUint32 tokens, tokens_per_line, full_lines, line_break_chars, remainder;
284:
285:     tokens = (size + 2) / 3;
286:
287:     if (line_length == 0)
288: 	      return tokens * 4;
289:
290:     if (line_length < 4)	/* too small! */
291: 	      line_length = 4;
292:
293:     tokens_per_line = line_length / 4;
294:     full_lines = tokens / tokens_per_line;
295:     remainder = (tokens - (full_lines * tokens_per_line)) * 4;
296:     line_break_chars = full_lines * 2;
297:     if (remainder == 0)
298: 	   line_break_chars -= 2;
299:
300:     return (full_lines * tokens_per_line * 4) + line_break_chars + remainder;
301: }

Root cause

The code computes the length with arithmetic on fixed-width unsigned integers. PL_Base64MaxDecodedLength() computes (size * 3) / 4 in PRUint32. For a large enough size, size * 3 wraps around, so the function returns a value smaller than the true decoded length. The caller uses that value for allocation and length validation, and the decoder can then write past the end of the buffer. The second contributing factor is that the only per-write bounds check in pl_base64_decode_buffer() is a PR_ASSERT(), which is compiled out of release builds, so nothing stops the overrun in production. The report says a similar issue exists in the encoding helper and its associated functions.

Impact

Keeping the report's hedges: the code might be vulnerable to a heap buffer overrun of attacker-determined size with 3-byte granularity, in the same class as bug 1344081. Wherever an application passes attacker-controlled data of sufficient length into these NSS Base64 helpers, the consequence could be memory corruption, which in a library used for TLS and cryptographic parsing is a serious prospect. The report does not demonstrate exploitation, so the practical impact is asserted rather than shown.

How this kind of bug works

Integer overflow in size calculations is a classic memory-safety bug. A length is computed in a fixed-width type (here 32-bit unsigned), and the multiplication or addition wraps modulo 2^32. The result is a small number that passes a sanity check, a buffer of that small size is allocated, and the subsequent copy or decode writes the real, larger amount of data. The write pattern often follows the encoding: Base64 produces output in 3-byte groups, which is where the 3-byte granularity comes from.

Two defences stop it. First, compute sizes in a wider type or with checked arithmetic, and reject inputs whose length exceeds the maximum the calculation can represent. Second, keep a real bounds check on every write in release builds, not only an assertion. Assertions document invariants for developers; they are not a security control.

How to test for it

Look for code that derives an allocation size from an input length using multiplication, division or addition, especially in parsers, decoders and protocol handlers. Grep for patterns like size * 3 / 4, (n + 2) / 3 * 4, and any helper named MaxLength, CalcSize or similar.

A concrete method:

  1. Identify the length helper and the maximum input length at which its arithmetic wraps (for a 32-bit multiply by 3, that is around 0x55555556).
  2. Find every caller that uses the helper's result to allocate or validate a buffer.
  3. Determine whether the input length is attacker-controlled and whether the code path is reachable in a release build.
  4. If you can build the component, compile in release mode and feed an input at or just past the wrap threshold; a positive result is a crash, a sanitizer report (ASan, Valgrind) showing a heap write past the allocation, or corrupted adjacent memory.
  5. If you cannot build it, trace the data flow and show that the length reaches the allocation unchecked.

Common false positives: the helper is only called with lengths that are bounded elsewhere; the caller uses a 64-bit type; the input is truncated or rejected before the calculation; or the only failing check is an assertion in a debug build that never ships. Confirm the release-build behaviour before reporting.

How it is fixed

A fix would be checked arithmetic: compute the size in a wider type, or explicitly test for overflow before multiplying, and return an error or clamp when the input is too large. Callers should validate the encoded length against a maximum before allocating. Separately, the incremental bounds check in the decoder could be a real runtime check that returns an error, not a PR_ASSERT().

Hunting notes

This bug class hides in utility and codec libraries: Base64, hex, URL and percent encoders, compression wrappers, ASN.1 and protocol length fields, and anywhere a MaxLength helper feeds an allocation. Recon signals include C code with fixed-width length types, size helpers that multiply, and assertions used as the only bounds check. A clear data-flow argument plus a crash beats a theoretical note.

The original is short, so this covers everything it reports, then explains this kind of bug in general: how it works, how to test for it and how it is fixed. The general sections are about the bug class, not this target. Written with AI and checked against the original; the original is the record. 7 min read.

What happened, in plain words

This report is about a bug in a piece of software called NSS, short for Network Security Services, which Mozilla maintains. NSS is a library: a collection of ready-made code that other programs use instead of writing everything themselves. Among other things it handles Base64, a way of turning any data into plain text characters so it can travel safely through systems that only expect text. When you send an email attachment or a web page carries an image inside the page itself, Base64 is often doing the work behind the scenes.

Before NSS decodes a Base64 string back into its original data, it needs to know how big the result will be, so it can reserve the right amount of memory. The researcher, q1, reported that the function doing that size calculation can produce a wrong, too-small answer for very long inputs. If the program then trusts that answer, it reserves too little memory and the decoding step can write past the end of it. That kind of mistake is called a buffer overrun, and it can corrupt memory.

The report points at the decoding side first. The size calculation is this function:

Text
370: static PRUint32
371: PL_Base64MaxDecodedLength (PRUint32 size)
372: {
373:     return ((size * 3) / 4);
374: }

Line by line: PRUint32 is a whole number that cannot be negative and has a fixed maximum size, roughly four billion. The function takes the length of the encoded text (size), multiplies it by 3 and divides by 4, because Base64 output is about a third larger than the original data. The problem is that the multiplication happens inside that fixed-size number. If size is large enough, size * 3 goes past the maximum and wraps around to a small value, like a car odometer rolling over. The function then returns a length far smaller than reality. The report states the threshold: the calculated length is inadequate once the encoded string is >= 0x55555556 characters long.

Next, the report shows how that wrong length is used. PL_Base64DecodeBuffer() calls the size function to check whether a buffer the caller supplied is long enough, or to reserve one if the caller supplied none. Either way, the buffer is too small when the overflow happens. The length and buffer are then handed to the actual decoding function, pl_base64_decode_buffer(), which contains this check:

Text
219: static PRStatus
220: pl_base64_decode_buffer (PLBase64Decoder *data, const unsigned char *in,
221: 			 PRUint32 length)
222: {
223:     unsigned char *out = data->output_buffer;
224:     unsigned char *token = data->token;
225:     int i, n = 0;
226:
227:     i = data->token_size;
228:     data->token_size = 0;
229:
230:     while (length > 0) {
231: 	while (i < 4 && length > 0) {
...
254: 	   PR_ASSERT((out - data->output_buffer + 3) <= data->output_buflen);

Line 254 is the important one. PR_ASSERT is an assertion: a note to the developer saying "this should always be true". Assertions are normally switched off in the builds that ship to users, so in a real product this check does nothing. The decoder therefore writes into the buffer without any working limit, and the researcher notes the overrun could be an attacker-chosen size, in steps of 3 bytes, because Base64 works in groups of 3 bytes.

The report says the same kind of flaw exists on the encoding side, in PL_Base64MaxEncodedLength() and the functions around it:

Text
280: static PRUint32
281: PL_Base64MaxEncodedLength (PRUint32 size, PRUint32 line_length)
282: {
283:     PRUint32 tokens, tokens_per_line, full_lines, line_break_chars, remainder;
284:
285:     tokens = (size + 2) / 3;
286:
287:     if (line_length == 0)
288: 	      return tokens * 4;
289:
290:     if (line_length < 4)	/* too small! */
291: 	      line_length = 4;
292:
293:     tokens_per_line = line_length / 4;
294:     full_lines = tokens / tokens_per_line;
295:     remainder = (tokens - (full_lines * tokens_per_line)) * 4;
296:     line_break_chars = full_lines * 2;
297:     if (remainder == 0)
298: 	   line_break_chars -= 2;
299:
300:     return (full_lines * tokens_per_line * 4) + line_break_chars + remainder;
301: }

Here the same fixed-size arithmetic is used to work out how much space the encoded text will need, including line breaks. The report says a similar issue exists here, so the answer can again be too small. The report does not show a working attack; it says a proof of concept will be posted if and when the bugs are demonstrated, and it gives no fix or bounty figure.

Why does this matter? NSS is used for secure connections and for parsing data that arrives from the network, so a memory corruption bug in it is a serious prospect wherever an application feeds it long, attacker-controlled input. The report is careful to say the code might be vulnerable, because exploitation was not shown.

In general, how this kind of bug works

This is a classic integer overflow in a size calculation. A length is computed in a fixed-width number, the arithmetic wraps around, and the result is a small number that passes a sanity check. A buffer of that small size is reserved, and the real, larger amount of data is then written into it. The write pattern often follows the data format: Base64 produces output in 3-byte groups, which is where the 3-byte granularity comes from.

Two defences stop it. First, compute sizes in a wider number type or with checked arithmetic, and reject inputs whose length is too large to represent. Second, keep a real bounds check on every write in shipping builds, not only an assertion. Assertions document what developers believe; they are not a security control.

To look for this class of bug, search for code that derives a buffer size from an input length using multiplication, division or addition, especially in parsers, decoders and protocol handlers. Patterns like size * 3 / 4, (n + 2) / 3 * 4, and helpers named MaxLength or CalcSize are worth a look. A practical method:

  1. Find the length helper and the input length at which its arithmetic wraps (for a 32-bit multiply by 3, around 0x55555556).
  2. Find every caller that uses the result to reserve or validate a buffer.
  3. Check whether the input length is attacker-controlled and whether the path is reachable in a shipping build.
  4. If you can build the component, compile it in release mode and feed an input at or just past the wrap threshold; a crash or a memory-checking tool report showing a write past the allocation confirms it.
  5. If you cannot build it, trace the data flow and show that the length reaches the allocation unchecked.

Common false positives: the helper is only called with lengths bounded elsewhere, the caller uses a 64-bit type, the input is rejected before the calculation, or the only failing check is an assertion in a debug build that never ships. Confirm the release-build behaviour before reporting.

A fix would be checked arithmetic: compute the size in a wider type, or test for overflow before multiplying, and return an error when the input is too large. Callers could validate the encoded length against a maximum before reserving memory, and the decoder's incremental check could be a real runtime check that returns an error rather than a PR_ASSERT().

This bug class hides in utility and codec libraries: Base64, hex, URL and percent encoders, compression wrappers, ASN.1 and protocol length fields, and anywhere a MaxLength helper feeds an allocation.

Glossary

  • NSS (Network Security Services): Mozilla's library of security and cryptography code used by other programs.
  • Library: a collection of reusable code that applications call instead of writing it themselves.
  • Base64: an encoding that turns arbitrary data into plain text characters so it can pass through text-only systems.
  • Encoding / decoding: converting data into another representation and back again.
  • Buffer: a reserved block of memory used to hold data temporarily.
  • Buffer overrun: writing data past the end of a buffer, corrupting neighbouring memory.
  • Integer overflow: arithmetic on a fixed-size number that wraps around past its maximum instead of growing.
  • PRUint32: a fixed-width whole number type that cannot be negative and has a maximum of about four billion.
  • Assertion (PR_ASSERT): a developer check that something should always be true, normally removed from shipping builds.
  • Debug build / release build: a version of software built for testing with extra checks, versus the version shipped to users.
  • Heap: the area of memory where programs reserve buffers at runtime.
  • Memory corruption: damage to memory contents caused by writing where the program should not.
  • Proof of concept (POC): a small demonstration that a bug can actually be triggered.
  • Sanitizer (ASan, Valgrind): tools that watch a running program and report memory errors such as out-of-bounds writes.
  • Checked arithmetic: arithmetic that detects overflow and reports it instead of silently wrapping.
  • Data flow: the path a piece of data takes through the code, from input to where it is used.

More by q1

View all

71 more disclosed reports, best first.

More from Mozilla

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.