Memory and timing flaws, and what the runtime prevents

8 min 5 sections 5 practice questions 10 sources citedISC2 objective 8.2

A running program keeps its working data in reserved spaces in memory, and it often does two things at once. Two families of flaw follow. A program that writes past the end of a space, or uses a space after handing it back, can be taken over. A program that checks something and then acts on it a moment later can be fooled in between. The environment a program runs in can block much of this. No programming background is assumed.

By the end of this unit you will be able to:

  • Explain how a buffer overflow and an integer overflow let an attacker change what a program does
  • Tell apart a memory leak and a use after free by their effect
  • Explain a race condition and time of check to time of use with an everyday case
  • Match each runtime defence to the flaw it blocks, and say what it does not fix

Seat F12, sold twice

An illustrative example

A small cinema sells tickets online. On a Saturday night one seat is left: F12. Two customers in different towns press Book within the same second.

The booking program checks for each of them that F12 is free. It is, both times. It takes both payments, then marks the seat as sold, twice. At seven o'clock two people arrive holding tickets for F12. The manager looks at the program's records and finds nothing wrong: every sale checked the seat before taking the money.

Each sale checked that the seat was free before selling it. How did both checks pass?

What a program uses while it runs: memory and the runtime

A program at work needs somewhere to keep the things it is handling: a name typed into a form, a running total, a list of seats. It asks for space in memory, the computer's short-term working store, and is given a block of fixed size. A block reserved to hold data is called a buffer.

Next to a buffer the program keeps its own notes. One of them says where to carry on when the current task finishes, much as a bookmark marks the page to return to. If the program writes past the end of a buffer, it writes over whatever comes next, including those notes.

The program's runtime is everything around it while it runs. That means the operating system's services and, for many languages, a virtual machine that carries out the code and checks it as it goes. Some flaws are the programmer's to prevent. Others can be caught or blunted by the runtime, whoever wrote the code.

Buffer overflow and integer overflow

A buffer overflow happens when a program copies more data into a buffer than it holds. It never compared the size of the input with the size of the space. The surplus spills over the neighbouring memory.

An overflow overwrites the bookmark that says where to carry on

An overflow overwrites the bookmark that says where to carry onTwo copies of the same memory: a 16-character buffer with the program's bookmark beside it. Left, a 9-character name fits and the bookmark is unchanged. Right, 40 characters pass no length check, fill the buffer and overwrite the bookmark, which points back into the input.Input that fits9 characters into 16Name9 charactersBuffer16 characters,9 usedBookmarkunchangedInput that overflows40 characters into 16Input40 characterswith codeBuffer16 characters,all filledBookmarkoverwritten:points backNo lengthcheckAn overflow overwrites the bookmark that says where to carry onTwo copies of the same memory: a 16-character buffer with the program's bookmark beside it. Left, a 9-character name fits and the bookmark is unchanged. Right, 40 characters pass no length check, fill the buffer and overwrite the bookmark, which points back into the input.Input that fits9 characters into 16Name9 charactersBuffer16 characters,9 usedBookmarkunchangedInput that overflows40 characters into 16Input40 characterswith codeBuffer16 characters,all filledBookmarkoverwritten:points backNo lengthcheck
Read this figure as text

A buffer is a block of memory of fixed size reserved to hold data. Next to it the program keeps its own notes, and one of them, like a bookmark, says where to carry on when the current task finishes.

  1. Left: a 9-character name is copied into a buffer with room for 16 characters. It fits, and the bookmark beside the buffer is unchanged.
  2. Right: an attacker sends 40 characters of exactly the right length and content. The program never compares the size of the input with the size of the space.
  3. The copy fills the buffer and the surplus spills over the neighbouring memory, replacing the bookmark with an address of the attacker's choosing.
  4. That address often points back into the attacker's own input. When the task ends the program carries on from there and runs the attacker's instructions with the program's own rights.
  5. The lasting fix is in the code: check the length of every input against the space before copying, or use a memory-safe language that makes the check for the programmer.

An attacker sends input of exactly the right length and content. The overflow replaces the bookmark with an address of the attacker's choosing, often pointing back into the attacker's own input. When the task ends, the program carries on from there and runs the attacker's instructions with the program's own rights.

An integer overflow is a number growing too big for the space that holds it. A counter that can hold up to 255 goes from 255 to 0, like a car's mileage display turning over. If the program then uses that wrapped number to decide how much space to reserve, it reserves far too little, and the next copy overflows the buffer.

The lasting fixes are in the code. Check the length of every input against the space before copying, and check each calculated size for overflow before using it. A memory-safe language makes both checks for the programmer.

Memory handed back too late, or used after it is handed back

In C and C++ a program reserves memory, uses it, and must release it when finished. Two opposite mistakes follow.

Memory leak
The program never releases memory it no longer needs. Each request leaves a little more held, like a library whose borrowers never return books. Eventually nothing is left and the program slows or stops. An attacker who can trigger the leak on purpose has a way to take the service down.
Use after free
The program releases a block, the block is given to another part of the program, and the old code keeps reading or writing it. It is a hotel guest who keeps a key card after checking out and walks into the next guest's room. It can corrupt data, leak it, or let an attacker run code.

A leak harms . A use after free harms all three security properties.

Garbage collection, in which the runtime releases memory once nothing refers to it, removes use after free. To do the work, the collector stops the program briefly; each stop is called a pause. Garbage collection does not prevent leaks: a program that keeps references it no longer needs, such as a list that only grows, still leaks. In C and C++, careful rules and testing tools reduce both flaws.

Race conditions: something changes between the check and the act

Computers handle many requests at once. A race condition is a flaw whose result depends on which of two simultaneous activities gets to a shared resource first. The cinema's seat was the shared resource, and both sales got there before either finished.

The commonest form has its own name. Time of check to time of use (TOCTOU) is a race in which a program checks something and acts on the answer a moment later. The thing changes in the gap. The seat was free when each check ran. By the time each sale used that answer, it was no longer true.

A switched file

A program with administrator rights checks that a user may write to a file, then opens it. Between the check and the opening, the user swaps the file for a pointer to the password file. The program writes to a file the user could never have touched.

The fix is to make the check and the use one step that nothing can interrupt. The program locks the resource before checking it and releases the lock after using it, or uses an operation that checks and acts together. A database transaction that books the seat only if it is still free does exactly this. Shrinking the gap makes an attack harder but does not remove it.

Defences in the runtime, and what each blocks

Code should be correct, but code written in C or C++ will contain some memory flaws. The runtime adds layers that make them hard to exploit.

Runtime defences against memory and timing flaws
DefenceHow it worksWhat it blocks
Bounds checkingThe language or runtime checks every read and write against the size of the bufferBuffer overflow at its cause
Stack canaryA known value is placed before the bookmark and checked before it is used. A changed value stops the programOverwriting the bookmark unnoticed
Data execution prevention (DEP)Memory that holds data is marked as not runnableRunning instructions hidden in input
Address space layout randomisation (ASLR)Code is loaded at unpredictable addressesJumping to a known useful address
Garbage collectionThe runtime releases memory once nothing refers to itUse after free, but not memory leaks
Locks and single-step operationsOnly one activity at a time may check and change the resource and TOCTOU

A is a controlled place to run code, with access only to what it is allowed to touch: usually no files and no network. A browser runs each web page's scripts in one. Managed code, run by a virtual machine such as Java's or that of .NET, gets bounds checking and garbage collection on every operation.

A container packages a program with everything it needs and runs it apart from others on the same machine. Containers share one operating system core, so their separation is weaker than separate virtual machines.

Common misconception

“With data execution prevention and address randomisation switched on, buffer overflows no longer matter.”

Both make an overflow harder to exploit. Neither removes it, and attackers have ways round each. The overflow can still crash the program. The cure is bounds checking in the code or a memory-safe language.

A question, worked through

A medical device maker's firmware is written in C. A penetration test finds a buffer overflow in the code that reads patient records from a memory card. The firmware ships next month, and rewriting it in another language would take two years. Address randomisation and data execution prevention are already enabled on the device.

What should the security manager require FIRST?

  1. Correct the copy so that it checks input length against the buffer
  2. Rely on the address randomisation and execution prevention
  3. Plan to rewrite the firmware in a memory-safe language
  4. Run the card-reading code inside a separate sandbox
Decide on your answer, then open the reasoning
  1. A known buffer overflow exists in code that ships next month. The question asks what comes first.
  2. Rule out b. Randomisation and execution prevention make exploitation harder but leave the flaw in place. A crafted card could still crash the device or get round them.
  3. Rule out c. A memory-safe language is the best long-term choice, but it takes two years and the product ships next month.
  4. Between a and d: a sandbox limits what a successful attack could reach and is worth adding. It still leaves the known flaw in the code.
  5. Checking input length against the buffer removes the cause, and it can be done before release. Option a, with the sandbox and a later language change as further layers.

Answer: A. Correct the copy so that it checks input length against the buffer

Choosing between good answers

A question asks for the best defence against buffer overflow in code being written
choose bounds checking or input length validation in the code, or a memory-safe language. ASLR, DEP and canaries are layers that make exploitation harder.
A program checks a condition and then acts on it in a separate step, and an attacker changes things in between
it is time of check to time of use. The answer makes the check and the use a single uninterrupted step, usually with a lock.
The symptom is a service slowly running out of memory until it stops
it is a memory leak, an availability problem. Use after free is a corruption problem that can lead to running an attacker's code.
Untrusted code must run and cannot be fully checked first
choose a sandbox, which limits what the code can reach. A container gives less separation than a virtual machine, because containers share one operating system core.

Check your understanding

5 questions on this unit, easiest first. Confirm an answer to see the reasoning for it, then the right answer, the other options and the rule to reuse. Your answers are kept in this browser and feed readiness and review.

These questions are drafts that no named reviewer has approved yet.

Question 1 of 5

A security architect is briefing a development team on what each runtime defence does against memory and timing flaws.

Match each defence to what it blocks.

Choose the match for each entry. Every match has to be right.

What to remember

  • A buffer overflow writes past the end of a reserved space and can overwrite the note that says where to carry on, handing control to the attacker.
  • An integer overflow wraps a number round to a small value, and a size worked out from it can cause a buffer overflow.
  • A memory leak exhausts memory over time. A use after free reuses released memory and can corrupt data or run an attacker's code.
  • A race condition depends on which activity reaches a shared resource first. TOCTOU is a change between a check and the action that relies on it, fixed by making the two one step.
  • Runtime defences include bounds checking, stack canaries, DEP, ASLR, garbage collection, locks and sandboxes. Only bounds checking and memory-safe languages remove overflows at their cause.

Say it from memory

  1. Which protections can a program's runtime give against memory and timing flaws, and which flaw does each address?

    Bounds checking stops buffer overflows at the cause. Stack canaries detect an overwritten return note. DEP stops data being run as code. ASLR hides where code sits. Garbage collection prevents use after free, not leaks. Locks prevent race conditions and TOCTOU. A sandbox limits what code can reach. Containers share one operating system core, so they separate less than virtual machines.

    Read this part again

  2. How does a buffer overflow let an attacker run code, and how can an integer overflow lead to one?

    Input longer than the buffer spills over neighbouring memory and replaces the note saying where to carry on with an address the attacker chose. An integer overflow is a number too big for its space, which wraps round, such as 255 to 0. If that number sets how much space to reserve, too little is reserved and the next copy overflows.

    Read this part again

  3. How does a memory leak differ from a use after free, and which one does garbage collection remove?

    A memory leak is never releasing memory no longer needed, until the program slows or stops; it harms availability. A use after free is old code still reading or writing a released block now given to another part; it harms all three security properties. Garbage collection removes use after free but does not prevent leaks.

    Read this part again

  4. What is a time of check to time of use flaw, and what is the fix?

    A race condition in which a program checks something and acts on the answer a moment later, and the thing changes in the gap. The fix is to make the check and the use one step that nothing can interrupt, by locking the resource or using an operation that checks and acts together. Shrinking the gap does not remove it.

    Read this part again

Sources