Table of Contents

How to use ROP to bypass security mechanisms

Olivia with cat. Used on a post about ROP.

Return-Oriented Programming (ROP) is an exploitation technique used to execute arbitrary code on a target system. It is often used in environments with defense mechanisms like Write XOR Execute (W^X), Address Space Layout Randomization (ASLR), and stack canaries. ROP lets me get around W^X by reusing existing code. Getting past ASLR and stack canaries usually takes an additional weakness, such as an information leak.

In this blog post, I will cover the basics of ROP, and how I use it. By the end, you’ll know what a gadget is, how a chain of them turns a stack overflow into code execution, and how ROP gets past W^X, and what else it takes to get past ASLR and stack canaries. Here’s what a ROP chain looks like on the stack (higher addresses at the bottom):

[ buffer ......... ]  ← overflow starts here
[ saved return     ]  → 0x08048430  pop eax; ret
[ value for eax    ]  → 0x00000005
[ next gadget      ]  → 0x08048432  add eax, ecx; ret
[ next gadget      ]  → ...

🌸👋🏻 Enjoying this post? Get the next issue of [ret]2read. Once a month, I’ll email you whatever’s on my mind, usually Apple security research, offensive security, open source software freedom, and operating system internals.

1. Gadgets

Gadgets are small snippets of code that end with a ret (return) instruction. These gadgets are in the existing code (e.g., in libraries or the executable itself). Each gadget typically performs a small, specific task, such as moving data between registers, adding numbers, or calling a function.

Example gadget 

Here is an example of what a gadget might look like. This gadget could be found in a binary or a library (the examples in this post use 32-bit x86):

pop eax
ret
  • pop eax: Pops the value from the top of the stack into the eax register.
  • ret: Pops the next value from the stack into the instruction pointer (EIP or RIP on 64-bit systems), transferring control to the address specified by that value.

2. Chaining gadgets

In a ROP attack, I chain together multiple gadgets to perform operations—calling functions, manipulating registers, and executing system calls—without injecting new code.  By controlling the stack (specifically the return addresses on the stack), I can make the program “return” to these gadgets in sequence. This sequence of gadgets is crafted to achieve a specific outcome, such as calling execve() to spawn a shell.

Example of chaining gadgets

Imagine I want to perform a simple operation like eax = 5 + ecx. I could achieve this using a chain of gadgets found in the binary:

1. Gadget 1: Pop a value into eax

pop eax
ret
view raw load.asm hosted with ❤ by GitHub

This gadget pops the next value on the stack into eax. Because I control the stack, I put the value I want there. In this example, that’s 5.

2. Gadget 2: Add ecx to eax

add eax, ecx
ret
view raw add.asm hosted with ❤ by GitHub

This gadget adds the value of ecx to eax.

3. Gadget 3: Return to the next gadget

ret
view raw rets.asm hosted with ❤ by GitHub

This gadget only returns, which moves execution to the next address on the stack.

Chained execution

When executed in sequence, these gadgets perform the following:

  1. Pop the next value on the stack (the 5 I placed there) into eax.
    • The state after this gadget: eax = 5
  2. Add the value of ecx to eax.
    • The state after this gadget: eax = eax + ecx (which is now eax = 5 + ecx)
  3. Return to the next instruction in the chain or complete the chain.
    • The ret instruction in each gadget returns control to the next gadget in the chain, allowing the sequence to continue or complete the operation.

3. Bypassing security mechanisms

The defenses in play here are W^X, ASLR, and stack canaries.

ROP chains existing code instead of injecting new code, which gets around W^X. ASLR and stack canaries still stand in the way, so I need to deal with them separately.

Write XOR Execute (W^X) 

TLDR: W^X ensures that a memory page cannot be both writable and executable at the same time. ROP bypasses this by reusing existing executable code rather than injecting new code.

A page, memory page, or virtual page is a fixed-length contiguous block of virtual memory, described by a single entry in a page table. It is the smallest unit of data for memory management in an operating system that uses virtual memory. Similarly, a page frame is the smallest fixed-length contiguous block of physical memory into which memory pages are mapped by the operating system.
Wikipedia

Purpose

W^X is a security mechanism that enforces a rule where a memory page can be either writable or executable, but not both simultaneously. This protection prevents attackers from injecting and then executing malicious code in writable memory.

Bypassing

ROP doesn’t turn W^X off. It sidesteps it, because the code I reuse is already marked executable.

🌸👋🏻 Enjoying this post? Get the next issue of [ret]2read. Once a month, I’ll email you whatever’s on my mind, usually Apple security research, offensive security, open source software freedom, and operating system internals.

Want your company or product in front of [ret]2read readers?
One sponsor per issue →

Address Space Layout Randomization (ASLR) 

TLDR: ASLR randomizes the memory locations of code sections, making it difficult to predict where code will be in memory. However, if I can leak an address or brute-force the address space, I might be able to locate ROP gadgets.

Purpose

ASLR randomizes the memory addresses of a process, such as the stack, heap, and loaded modules (e.g., executables and shared libraries). This randomization makes it difficult for me to predict the location of gadgets, thus thwarting the construction of a reliable ROP chain. One catch: if a program isn’t built as a position-independent executable (PIE), its main code loads at the same address every run, even with ASLR on. Addresses like 0x08048430 in my examples are typical of a 32-bit, non-PIE Linux binary.

Bypassing

To successfully perform a ROP attack, I need to know the exact memory locations of the gadgets I intend to use. If I can leak an address within the randomized space (e.g., via an information leak vulnerability), I can infer the positions of other gadgets. 

Alternatively, brute-forcing ASLR can be attempted. On 32-bit systems, there are few enough random bits that brute forcing is often practical. On 64-bit systems, it is usually impractical because the randomized address space is far larger.

Stack canaries

TLDR: Stack canaries are values placed on the stack to detect buffer overflows. ROP doesn’t bypass them on its own; I need a leak or a different bug that skips the canary.

Purpose

Stack canaries are placed on the stack between local buffers and the saved return address. They are designed to detect stack buffer overflows by checking that the canary value is unchanged before the function returns. If a buffer overflow overwrites the canary, the program detects the change and aborts before the corrupted return address is used.

Bypassing

A plain linear overflow can’t reach the return address without overwriting the canary, and ROP doesn’t change that.

I need something else: a leak that lets me write the correct canary back, or a different bug, such as an arbitrary write, that changes the return address without touching the canary.

For example, a separate bug, such as a format string vulnerability, can leak the canary value. Here, I might use a format string vulnerability to read arbitrary memory, including the location where the stack canary is stored. By leaking the canary value through this method, I can bypass the stack protection mechanism during a buffer overflow attack, since I now know the correct canary value that needs to be preserved. 

Newer defenses

Some defenses target ROP more directly. Control-flow integrity (CFI) limits where a program’s control transfers can go. Shadow stacks, such as the one in Intel CET, keep a protected second copy of return addresses and fault if the two don’t match. Arm pointer authentication (PAC) can sign return addresses, so an overwritten one fails its check.

Search for gadgets

To find gadgets, I use a Python script that runs the ropgadget tool against a binary:

import subprocess
def find_gadgets(binary):
try:
output = subprocess.check_output(["ROPgadget", "--binary", binary])
gadgets = output.decode("utf-8").split("\n")
for gadget in gadgets:
print(gadget)
except Exception as e:
print(f"error occurred: {e}")
binary_path = "/path/to/binary"
find_gadgets(binary_path)
view raw ropgadget.py hosted with ❤ by GitHub

This script runs the ROPgadget tool against a specified binary and prints out potential gadgets, which can be used for ROP attacks.

Example use case

Let’s say I find the following gadgets in a binary:

  1. 0x08048430: pop eax; ret;
  2. 0x08048432: add eax, ecx; ret;
  3. 0x08048434: ret;

I could craft an exploit that places these addresses on the stack in the right order, manipulating the program to execute them sequentially, achieving the desired computation using existing code in the binary.

🌸👋🏻 Enjoying this post? Get the next issue of [ret]2read. Once a month, I’ll email you whatever’s on my mind, usually Apple security research, offensive security, open source software freedom, and operating system internals.

Why use ROP?

As I stated previously, many operating systems employ multiple layers of security, and traditional buffer overflow techniques become less effective. ROP provides a way to exploit vulnerabilities even in the presence of these defenses by:

  • Avoiding the need to inject new code (which W^X prevents).
  • Working around ASLR by using techniques like information leaks to find gadget locations.
  • Utilizing existing, legitimate code in a way that the original developers never intended.

Example scenario

Let’s look at our last example. 

Suppose, hypothetically, I find a buffer overflow vulnerability in a BSD-based application. (BSD systems differ, and OpenBSD in particular adds extra anti-ROP defenses.) Due to W^X, I cannot inject shellcode directly. Instead, I have to analyze the binary to identify gadgets, such as:

  • A gadget to move data into a register.
  • A gadget to set up a system call.
  • A gadget to call execve().

Then, I craft an exploit that overwrites the return address on the stack with the address of the first gadget. As the program executes, it “returns” to each gadget in my sequence, eventually leading to the execution of a system call that runs my shell.

After chaining these gadgets together to achieve arbitrary code execution, ROP has gotten around W^X by reusing existing code. If you enjoyed this post, consider reading How Does OS Affect Binary Exploitation. 

Portrait of Olivia Gallucci in garden, used in LNP article.

Written by Olivia Gallucci

Olivia is a senior security engineer, certified personal trainer, and freedom software advocate. She writes about offensive security, open source software, and professional development.

Discover more from [ret]2read

A Monthly OS Internals Publication by Olivia Gallucci. Subscribe now to keep reading and get access to the full archive.

Continue reading