Skip to content
Memory corruption Write-up Advanced

Don’t Follow The Masses: Bug Hunting in JavaScript Engines

An integer overflow in V8's string literal buffer capacity calculation could cause a heap buffer overflow when scanning a very large JavaScript string. An attacker could trigger memory corruption by supplying such a string, potentially leading to code execution.

Dimitri Fourny Follow

Published on labs.bluefrostsecurity.de

Bounty$7,500 View original

Analysis of CVE-2019-5790 and how the search for unexplored attack surface in V8 led to its discovery.

Blue Frost Security GmbH, on labs.bluefrostsecurity.de

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 4 min read.

Context

A garbage collector runs alongside all of this.

Most public research on JavaScript engine security concentrates on the JIT compilers, and for good reason: they are highly complex, they change constantly, and they have historically produced a large number of vulnerabilities. The authors' argument is that this focus leaves other parts of the code base comparatively unexplored. Their target was the very first stage of the pipeline, the scanner, and the result was CVE-2019-5790, a heap memory corruption bug that Google awarded with a $7,500 bug bounty.

Focussing on publicly known attack surface in high profile targets
(Source: https://www.flickr.com/photos/usoceangov/31969091783/) From the original on labs.bluefrostsecurity.de

The image illustrates the point about publicly known attack surface in high profile targets: the well-trodden areas attract attention, while quieter components can hide bugs with a longer lifetime.

Setup

The authors note the bug seemed quite obvious by reading the code. The parser implementation lives in src/parsing/ in the V8 source tree, and the relevant classes are Scanner, Token, UTF16CharacterStream, Parser and the scanner's LiteralBuffer.

The bug was found by Dimitri Fourny (@DimitriFourny) and reported to Google on 13 December 2018. It was fixed in Chrome 73.0.3683.75, and the tracking entry is Chromium issue 914736.

Finding it

The scanner turns the input text into tokens. Scanner::Scan calls Scanner::ScanSingleToken to find the next non-whitespace token. Some tokens are trivial: a brace, bracket or semicolon is returned immediately. Others cause more characters to be consumed from the stream.

A string literal is one of the latter. When the scanner encounters the quote character it returns a TOKEN::String token and calls Scanner::ScanString, which calls Scanner::AddLiteralChar in a loop until the closing quote is found. Scanner::AddLiteralChar calls Scanner::LiteralBuffer::AddChar, which ends up in Scanner::LiteralBuffer::AddTwoByteChar when the initial quote is followed by two-byte characters.

The scanned part of the string is held in the backing_store_ byte vector, which is resized on demand. When AddTwoByteChar decides the vector must grow, it calls Scanner::LiteralBuffer::ExpandBuffer, which allocates a larger buffer and copies the old bytes into it. The size of the new vector is computed by Scanner::LiteralBuffer::NewCapacity.

The flaw is in that capacity calculation. The number of characters following the opening quote controls backing_store_.length(), so a very large JavaScript string produces a very large capacity value. The expression capacity * kGrowthFactory can then overflow, and new_capacity is set to a value smaller than the previous capacity. The next MemCopy writes more bytes into the vector than were allocated, corrupting heap memory.

Reading the code made the bug look fairly obvious, but the authors note it would have been hard to find by fuzzing: triggering it needs around 20 GB of memory and considerable time on a typical desktop machine.

Exploitation

Step 1: supply a string large enough to overflow the capacity calculation

The proof of concept is a single huge JavaScript string literal. The report states that a simple proof-of-concept can trigger the bug.

As the scanner consumes the characters, AddTwoByteChar repeatedly asks for a larger buffer. Once the multiplication overflows, NewCapacity returns a value smaller than the current capacity, ExpandBuffer allocates that smaller buffer, and the subsequent MemCopy writes beyond its end.

Step 2: observe the corruption

The overflow turns into heap memory corruption. The report does not describe a full exploit chain, only that the out-of-bounds write occurs in the scanner's literal buffer.

Root cause

The capacity growth calculation in Scanner::LiteralBuffer::NewCapacity multiplies the capacity by kGrowthFactory, and this expression can overflow. Because a huge JavaScript string makes the capacity value huge, the product can wrap to a small value, and the buffer is then reallocated smaller than the data that is about to be copied into it. The next MemCopy writes more bytes into the vector than were allocated.

Impact

An attacker who can get a very large string scanned by V8 can corrupt heap memory. The practical constraint is severe: the trigger requires around 20 GB of memory, which limits exploitation on ordinary desktop machines. The report does not describe a working exploit beyond the corruption itself.

Fix

The bug was fixed in Chrome 73.0.3683.75.

Variants to test

  1. Other length or capacity computations in the scanner and parser: look for multiplications of an attacker-controlled length by a constant where the result feeds an allocation. A positive result is a path where a very long token makes the computed size smaller than the data copied into it.
  2. A positive result is the same shrink-then-copy pattern in any of these buffers.
  3. A positive result is an overflow in the capacity calculation reachable from source text alone.
  4. A positive result is a reallocation that returns a smaller buffer than requested.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 11 min read.

What happened, in plain words

A security researcher found a bug in V8, the part of Google Chrome that reads and runs JavaScript, the programming language that makes web pages interactive. The bug was in the very first step Chrome performs when it looks at JavaScript code: reading the text and chopping it into small pieces called tokens. If a web page contained an extremely long piece of text (a string), Chrome could miscalculate how much memory it needed to hold that text, reserve too little, and then write past the end of what it reserved. Writing past the end of a reserved block of memory is called heap memory corruption, and it is a memory corruption flaw.

Google paid the researcher $7,500 for the report. The bug is tracked as CVE-2019-5790, a public identifier given to a specific security flaw so people can refer to it unambiguously. It was fixed in Chrome version 73.0.3683.75.

The interesting part of the story is not the bug itself but where it was found. Most people hunting for bugs in JavaScript engines look at the just-in-time (JIT) compiler, the component that turns JavaScript into fast machine code. That area is complex, changes constantly and has produced many bugs, so it attracts attention. The authors deliberately looked somewhere quieter, the scanner, the component that reads the raw text. Their point is that well-known areas get picked over, while less fashionable parts of a large program can still hide bugs that nobody has found yet.

Focussing on publicly known attack surface in high profile targets
(Source: https://www.flickr.com/photos/usoceangov/31969091783/) From the original on labs.bluefrostsecurity.de

The image is used to illustrate that idea: high-profile targets have a large, publicly known attack surface, meaning the set of places an attacker can try to interact with, and the busy, well-studied parts of that surface draw most of the attention.

Background: how JavaScript gets from text to running code

Before looking at the bug, it helps to know the journey a piece of JavaScript takes inside Chrome. The authors describe it as a pipeline, a series of stages where the output of one stage becomes the input of the next. The same broad design appears in other browsers too, but the description here is about V8.

  1. Scanning. The engine reads the raw text, character by character, and groups characters into tokens. A token is a meaningful chunk such as a keyword, a number, a punctuation mark or a quoted piece of text. Think of it like reading a sentence and marking where each word begins and ends before you try to understand the grammar.
  2. Parsing. The tokens are arranged into a tree structure called an abstract syntax tree (AST). The AST records how the pieces fit together: which expression is inside which function, and so on. It is the engine's structured understanding of the program.
  3. Bytecode. The AST is translated into a simpler set of instructions called bytecode, which an interpreter named Ignition executes. An interpreter runs instructions one at a time, like a person following a recipe step by step.
  4. JIT compilation. When a function has run many times, the engine treats it as "hot" and compiles it into machine code with a compiler called TurboFan. Machine code is the raw instructions the processor executes directly, which is much faster than interpreting.
  5. Garbage collection. Running alongside all of this is the garbage collector, a component that automatically frees memory the program no longer needs, so the programmer does not have to do it by hand.

Each stage is a possible place for bugs. The authors note that the JIT compiler is the most complex and most studied stage, and that the garbage collector, despite removing a whole class of mistakes such as memory leaks, can itself introduce interesting flaws. But their target was stage one, the scanner.

Background: the scanner in detail

The scanner's job is to turn text into tokens. In the V8 source code, the relevant code lives in a folder called src/parsing/. Several named pieces of code do the work:

  • The Scanner class reads the input and produces Token objects.
  • The UTF16CharacterStream class presents the incoming text as a stream of UTF-16 characters. UTF-16 is a way of encoding text as numbers; JavaScript arriving over the network can be encoded in different ways, and this class hides that difference from the scanner.
  • The Parser class takes the tokens and builds the AST.
  • The scanner keeps a LiteralBuffer, a buffer (a reserved block of memory) that holds the characters of a piece of text as they are read.

A class, in programming, is a blueprint that bundles together some data and the operations that work on it. When you hear Scanner::ScanString, read it as "the ScanString operation belonging to the Scanner class".

The bug: CVE-2019-5790

The bug was found by Dimitri Fourny (@DimitriFourny) and reported to Google on 13 December 2018. It was fixed in Chrome 73.0.3683.75, and the tracking entry is Chromium issue 914736.

Here is the chain of calls, step by step, in plain words.

  1. Scanner::Scan calls Scanner::ScanSingleToken to find the next token that is not whitespace. Whitespace is spaces, tabs and line breaks, which the scanner skips.
  2. Some tokens are trivial. A brace, a bracket or a semicolon is a single character, so the scanner returns it immediately. Other tokens need the scanner to keep reading more characters from the stream.
  3. A quoted piece of text, a string, is one of the latter. When the scanner sees the opening quote character, it produces a TOKEN::String token and calls Scanner::ScanString.
  4. Scanner::ScanString calls Scanner::AddLiteralChar in a loop, adding one character at a time, until it reaches the closing quote.
  5. Scanner::AddLiteralChar calls Scanner::LiteralBuffer::AddChar, which ends up calling Scanner::LiteralBuffer::AddTwoByteChar when the characters after the opening quote are two-byte characters. Two-byte characters are characters that need two bytes of storage, for example many non-English letters; a byte is the basic unit of computer memory, and one byte can hold a small number such as a single plain English letter.
  6. The characters read so far are kept in a byte vector called backing_store_. A vector is a growable list of items; here the items are bytes. When it needs more room, it is resized.
  7. When AddTwoByteChar decides the vector must grow, it calls Scanner::LiteralBuffer::ExpandBuffer. That operation reserves a larger block of memory and copies the old bytes into it. Copying bytes from one place to another is done by a routine called MemCopy.
  8. The size of the new block is worked out by Scanner::LiteralBuffer::NewCapacity.

The flaw is in that last calculation. The number of characters after the opening quote controls the length of backing_store_, so a very long string produces a very large capacity value. The calculation multiplies that capacity by a growth factor, a constant that says how much bigger each new buffer should be than the old one. If the capacity is large enough, the multiplication overflows: the result is too big to fit in the fixed-size number the computer uses, so it wraps around and becomes a small value. new_capacity then ends up smaller than the previous capacity. The next MemCopy writes more bytes into the vector than were reserved for it, and memory beyond the end of the buffer is overwritten. That is heap memory corruption. The heap is the general pool of memory a program uses for data it creates while running.

Reading the code made the bug look fairly obvious to the authors. But they point out it would have been hard to find by fuzzing. Fuzzing means feeding a program huge numbers of automatically generated inputs and watching for crashes. Triggering this bug needs around 20 GB of memory and considerable time on a typical desktop machine, which makes random testing impractical.

The proof of concept

The proof of concept is a single huge JavaScript string literal. A string literal is a piece of text written directly in the code, between quotes. The report states that a simple proof of concept can trigger the bug.

Line by line, in plain words:

  • The opening " tells the scanner that a string is starting, so it switches into string-reading mode and begins filling its literal buffer.
  • Everything up to the closing " is read one character at a time. The more characters there are, the larger the buffer has to become, and the larger the capacity value grows.
  • The closing " ends the string. In the real trigger, the number of characters in between is what matters: it has to be large enough that multiplying the capacity by the growth factor overflows.

As the scanner consumes the characters, AddTwoByteChar repeatedly asks for a larger buffer. Once the multiplication overflows, NewCapacity returns a value smaller than the current capacity, ExpandBuffer reserves that smaller block, and the following MemCopy writes past its end.

What the corruption means

The overflow turns into heap memory corruption. The report does not describe a full exploit chain, only that the out-of-bounds write happens in the scanner's literal buffer. An out-of-bounds write means writing to memory outside the area that was reserved, which can overwrite other data the program is using.

In a browser, JavaScript from a web page runs inside a component called the renderer, the part of Chrome that turns a page into what you see. The practical constraint is severe: the trigger needs around 20 GB of memory, which limits exploitation on ordinary desktop machines. The report does not describe a working exploit beyond the corruption itself.

Root cause

The capacity growth calculation in Scanner::LiteralBuffer::NewCapacity multiplies the capacity by kGrowthFactory, and this expression can overflow. An integer is a whole number, and in a computer it is stored in a fixed amount of space, so there is a largest value it can hold. When a calculation produces a bigger result than that, the number wraps around to a small value instead of failing. Because a huge JavaScript string makes the capacity value huge, the product can wrap to a small value. The buffer is then reallocated smaller than the data that is about to be copied into it, and the next MemCopy writes more bytes into the vector than were allocated.

The fix

The bug was fixed in Chrome 73.0.3683.75.

Where else to look

The authors' broader lesson is about choosing where to hunt. The following are the kinds of places where a similar bug might hide, phrased as things to test.

  1. Other length or capacity calculations in the scanner and parser. Look for places where a length controlled by the input is multiplied by a constant and the result is used to reserve memory. A positive result is a path where a very long token makes the computed size smaller than the data copied into it.
  2. ** A positive result is the same shrink-then-copy pattern in any of these buffers.
  3. ** A positive result is an overflow in the capacity calculation reachable from source text alone.
  4. ** A positive result is a reallocation that returns a smaller buffer than requested.

Why this matters if you are new to security

The story is a reminder that the most talked-about part of a system is not always the most fruitful place to look. A large program such as a browser has a huge attack surface, meaning the total set of places where an attacker can try to interact with it. Popular areas get studied by many people, so the easy bugs there are found quickly. Quieter components can hold bugs that survive for months or years, which is exactly what a bug hunter wants. The authors also show the value of reading code carefully: the flaw was visible by reading, but hard to spot by fuzzing because of the memory it needs.

Glossary

  • Abstract syntax tree (AST): a tree-shaped representation of a program that records how its pieces fit together.
  • Attack surface: the total set of places where an attacker can try to interact with a system.
  • Buffer: a reserved block of memory used to hold data, often while it is being read or built up.
  • Byte: the basic unit of computer memory; one byte can hold a small number such as a single plain English letter.
  • Bytecode: a simple set of instructions that an interpreter executes, produced from the AST.
  • Capacity: the amount of room reserved in a buffer.
  • Class: a blueprint in code that bundles data and the operations that work on it.
  • CVE: a public identifier given to a specific security flaw so people can refer to it unambiguously.
  • Fuzzing: feeding a program huge numbers of automatically generated inputs and watching for crashes.
  • Garbage collector: a component that automatically frees memory the program no longer needs.
  • Growth factor: a constant that says how much bigger each new buffer should be than the old one.
  • Heap: the general pool of memory a program uses for data it creates while running.
  • Heap memory corruption: damage to memory in the heap caused by writing outside the area that was reserved.
  • Identifier: a name in code, such as a variable name.
  • Integer: a whole number; in a computer it is stored in a fixed amount of space, so there is a largest value it can hold.
  • Integer overflow: when a calculation produces a number too big for the fixed space, so it wraps around to a small value.
  • Interpreter: a component that runs instructions one at a time, like following a recipe step by step.
  • JIT (just-in-time) compiler: a component that turns frequently run code into fast machine code while the program is running.
  • Machine code: the raw instructions the processor executes directly.
  • MemCopy: a routine that copies bytes from one place in memory to another.
  • Out-of-bounds write: writing to memory outside the area that was reserved.
  • Parser: the component that arranges tokens into an AST.
  • Proof of concept (PoC): a small input or program that demonstrates a bug.
  • Regular expression literal: a pattern for matching text, written directly in code.
  • Renderer: the part of a browser that turns a page into what you see and runs its JavaScript.
  • Scanner: the component that reads raw text and groups characters into tokens.
  • String: a piece of text in a program.
  • String literal: a piece of text written directly in code, between quotes.
  • Template literal: a string written with backticks, which can include embedded expressions.
  • Token: a meaningful chunk of text, such as a keyword, a number, a punctuation mark or a quoted piece of text.
  • Two-byte character: a character that needs two bytes of storage, for example many non-English letters.
  • UTF-16: a way of encoding text as numbers, using two bytes for many characters.
  • Vector: a growable list of items; here, a list of bytes.
  • V8: the JavaScript engine inside Google Chrome.
  • Whitespace: spaces, tabs and line breaks, which the scanner skips.

More from Google

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.