/
Segmentation

Security Vulnerabilities: How Attackers Exploit Memory to Take Over Your Systems

Every running program makes an assumption: the data it writes into memory will stay where it’s supposed to.  

Most of the time, that holds. But when a programmer leaves out a boundary check or mishandles a pointer, a few extra bytes can spill into places they were never meant to go. That’s often all an attacker needs to take control of the program.

In an earlier post, I walked readers through how attackers go from finding a vulnerability to reaching their goals. Once they find a flaw, the next step is exploitation.

Exploitation usually means writing shellcode: low-level malicious code that hijacks the normal flow of a running program and sends it to the attacker’s own code, which is also running in memory.

This article follows one classic technique, the stack-based buffer overflow, from a single crash to a reverse shell that hands the attacker remote control. Defenders should know these mechanics because the exploit is only the opening move. Once attackers can run code on one system, they use it as a launch point to spread across the network. Seeing how that first foothold is won makes it clear why containing it matters as much as preventing it.

Virtual memory mapping

Let’s start with memory mapping, which I introduced in my previous article.

Computer programs start as source code that a programmer writes, plus supporting files and dependencies such as linked libraries. All of it gets compiled into a single executable file. In an earlier article on .NET assemblies, I went through this process in more detail.

Once compiled, the program needs memory to run. When it runs, it becomes a process. The process is loaded into memory and broken into sections, and each part of the program maps to one of them.

This layout is the virtual memory structure shown in the image below. It shows a basic C program laid out according to the Executable and Linkable Format (ELF).

A program’s virtual memory layout, with the heap growing upward and the stack growing downward toward it.

Let’s look at what each section does:

  • .text: Also known as the code section, this holds the instructions needed to run the program. It’s loaded from the object file (executable file) and is marked as read-only. It has a fixed size at runtime.
  • .data: This section stores initialized data: global or static variables set to values other than zero in the code, such as int x = 123. Its size is also fixed at runtime. It’s readable and writable.
  • .bss: This stores global or static variables that haven’t been initialized or were initialized to zero. BSS stands for “block started by symbol,” a term from assembly language for reserving memory for variables that don’t need starting values. The section records the size those variables need, such as an array, but it doesn’t actually take up space in the object file. Its size is fixed at runtime.
  • Heap: This stores variables that are created and managed at runtime, with memory allocated as needed. It grows from lower memory addresses to higher ones. In C, programs allocate and free this memory with the malloc() and free() functions. C++ uses the new and delete operators.
  • Stack: This tracks function calls, function parameters, and the return address. It grows downward, from higher memory addresses to lower ones.

Of these sections, the stack matters most for an exploit. Before we get there, though, it helps to understand the most common ways attackers abuse memory in the first place.

The stack

Several of these exploits, and stack-based buffer overflows in particular, depend on how the stack works.  

When the program is executed and becomes a running application or process, it is allocated memory and each function that executes from within the main program gets a stack memory allocation known as a stack frame.

When the program is executed and becomes a running application or process, it’s allocated memory and each function that executes from within the main program gets a stack memory allocation known as a stack frame.

This stack memory structure, also referred to as execution stack or, more commonly, a call stack, is a key section of virtual memory structure that tracks a programs method or function calls during execution. This includes functions currently executing, associated local variables of the function, parameters passed to the function, and finally the return address where the function should hand over control to after completing.  

The process works in four stages:

When a function is called, a new stack frame with its own return address is added on top of the stack.
  • Allocation: When a function is called, a new stack frame is created and placed on the stack. This is the new memory allocation for the running function. ‍
  • Stack frame: This contains local variables used by the function, parameters passed to the function’s arguments, temporary data, and crucially, the return address which is where the function should return control of program flow. ‍
  • Deallocation: After the function completes, the stack frame is removed from the stack, and the function returns program control flow to the return address. See the image below for how control passes back to the calling function once the frame is gone.
  • ‍Last-in-first-out: The process of allocation and deallocation is based on last-in-first-out (LIFO). This means the last stack frame (function call) that was placed on the stack is the first one to be removed from the stack. You can think of this process as stacking plates on a shelf. The last plate that was put on the stack of plates will also be the first one to be removed when someone picks a plate.
When the function finishes, its frame is removed and the return address sends control back to the caller.

Exploit technique: stack-based buffer overflow

In a typical computer system, there will be several programs running and each requiring memory allocation. This leads to delicate juggling of memory arrangement and operations.  

A key part of a buffer overflow for malicious purposes is for the attacker to carefully control the data that’s written into memory to overflow an adjacent program’s buffer, as in the image example below.  

This is made possible because of vulnerabilities in how a program’s code, specifically functions or methods, were designed to handle memory buffers or accepts inputs.  

In the first part of the example above, two programs have their allocated buffer filled as expected with just enough data to fit in the buffer.

In the second part of the image, the butter is overwritten with excessive data. This is from a flaw in the program that validates input. In such a scenario, the overflowing buffer can easily overwrite adjacent memory, which could be holding important program data or, more importantly, function return addresses.  

These limitations in the code or implementation of the program are what allow an attacker to control program flow and run arbitrary code. If an attacker can control the return address, they can redirect a code’s execution to their malicious code.

To walk through the fundamentals, we’ll use the example of a program that’s vulnerable to buffer overflow.  

Crafting an exploit for a buffer overflow attack includes these eight steps:

  1. Victim application
  2. Debugging tool
  3. Fuzzing tool
  4. Unique pattern generator
  5. Memory offset calculator
  6. Control flow redirection
  7. Exploit and shellcode
  8. Reverse shell

Let’s breakdown this process and the tools required to accomplish each step.

1. Vulnerable executable

First, choose the vulnerable executable file or binary application. In this case, it’s a small vulnerable application server that receives text input over the network. ‍

2. Debugging the vulnerable executable

Next, we use a debugger to analyze the binary. Contrasting it with a disassembler, such as Ghidra or IDA Pro, converts machine (computer) code into assembly language, which is a more readable static analysis.  

A debugger, such as WinDbg, or Ollydbg, allows a more interactive, dynamic analysis of a program state. The debugger allows us to run the program in a controlled way and analyze:

  • Assembly instructions, such as running functions and jumps
  • Memory, including inspecting contents of the stack
  • CPU registers and execution points  
  • Function path, including the function call stack
  • Program inputs, such as byte lengths and buffer behavior

In the debug view above, we can see the stack memory, CPU registers, local variables, and assembly instructions. The image below shows the various sections of the x64debug software we used to analyze the execution of a vulnerable server application.

Closer inspection of the CPU registers section shows the extended instruction point (EIP) value is 778D637D.

3. Fuzzing: finding the overflow

When an application receives input, it typically stores this in a buffer. A fuzzer is used to iterate through several input options and lengths. This helps test that buffer overflow is possible.

On the left side of the image above, we have several input options. We’ve added a memory buffer view on the right for educational purposes to visualize the overflow past the boundary.  

Below is an example of a simple fuzzer application based on a cyclic pattern known as the De Bruijn sequence. Rather than sending a simple repeating string such as AAAAAAA, a De Bruijn sequence is more useful because each string occurs only once. So, when the vulnerable application eventually crashes, the exact string pattern value that came from the crash reveals the exact position.

The fuzzer application takes a target IP address, TCP or UDP port, an initial byte length, and number of sequence runs as inputs. The application then runs sequentially against the target application. This increases the input string accordingly.  

Note that while the fuzzer application is running, the vulnerable binary would also be started in a debugger. This allows it to detect at which byte length the application crashes and get the resulting stack memory pointer to the EIP register.

After successfully confirming the input length at which the application crashes, and therefore validating that the application is susceptible to a buffer overflow, we can then proceed to create a unique input string pattern as part of building the exploit.

4. Unique pattern generation

We have already established that the input is larger than the allocated buffer. The excess input data can overwrite adjacent or nearby values stored on the stack.  

This can include the important values such as EIP Instruction Point for 32-bit systems and RIP Instruction Point for 64-bit systems.

This is where a cyclic pattern generation tool is useful. You can use it to send a unique, specially crafted input to determine the exact length at or beyond which the application crashes and therefore exceeds the buffer.  

Terminal window showing 'pattern-tool --help' command for creating unique cyclic patterns with length 32, charset A-Z, a-z, 0-9, and a non-repeating cyclic type. Unique pattern example 'Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9' is displayed with 32 characters. Adjacent table lists non-repeating 3-character markers from Aa0 to Aa9 with their start position indices from 0 to 27 in increments of 3.

For efficiency, a cyclic pattern is used as the input so that when the application crashes, part of the unique input shows up in the respective platform register, such as the EIP.

The example above shows the Metasploit framework’s msf-pattern_create -l <length> used to craft a unique pattern string for the length of 3,000 bytes to accurately overflow the vulnerable program.

5. Memory offset calculation

As I showed earlier, using a cyclic pattern, such as Aa0, Aa1, Aa3, etc., as input rather than a standard repeating character, such as AAAAA, helps the attacker determine the correct memory offset and thereby include the exact padding they need to reach and overwrite the offset.

  • Generate pattern: msf-pattern_create -l 3000 ‍
  • Input pattern: run the vulnerable program with the generated pattern ‍
  • Find overwritten value: check the debugger for the overwritten EIP value ‍
  • Calculate offset: msf-pattern_offset -l 3000 -q <overwritten_value>

By following these steps, you can accurately determine the offset needed to build effective exploits, ensuring that your payload is positioned correctly within the buffer.

The example above shows how attackers can use the Metasploit framework msf-pattern_offset tool to find the exact memory offset required for a unique string pattern length of 3,000 bytes and the EIP register value 778D637D from the debugger of the vulnerable application.  

The result will be the padding length required to successfully reach the EIP, such as 2105 bytes.

6. Flow control: jump instruction

On the stack, a program’s execution flow is the order in which stack frames are added and removed. When a function is called, a new stack frame is added to the stack. When the function finishes, its frame is removed, and the program jumps back to the return address so it can pick up where it left off.

In terms of the low-level assembly of the program flow a “jmp” instruction allows for unconditional branching. This allows the program to bypass the default sequential execution of instructions and jump to the specified function defined after the “jmp” instruction.  

Attackers can redirect program flow to their malicious code while also running in memory by jumping to that code after successfully exploiting the stack-based buffer overflow attack.

Both of these concepts are useful for controlling program execution flow and therefore necessary to fully leverage the buffer overflow exploit.

NOP sled  

Another important step during the jump instruction phase on the way to the attackers malicious code is the CPU “no operation” instructions known as the NOP sled. Many “no operation” instructions are placed in a considerable chunk of memory just before the attacker’s injected code address.

This technique is required because predicting the attacker’s exact memory address location may be difficult due to operating system controls like Address-Space Layout Randomisation (ASLR). The NOPs operate like a sled on ice which slides the program control flow through this series of instructions until it lands on the attackers malicious code to starts executing that code.

The image above shows the 0x90 NOP instructions for x86 CPU. It’s referred to as a NOP sled or NOP slide because program execution slides through this sequence of instructions, effectively executing nothing while being guided to the attacker’s malicious code.

7. Exploit code and shellcode

At the heart of the exploit code is the shellcode. It’s called a shellcode because, historically, successful exploit of a vulnerability included code that would also deliver a remote shell back to the attacker.

Crafting shellcode for an exploit is akin to a precise art, so it has to have certain characteristics to be reliable.

Once all the key parts of the exploit process have been meticulously curated, it’s now time to piece them together into the complete exploit code. The exploit code is the final piece of code that now contains:

  • The unique overflow pattern string
  • Calculated offset memory padding to reach the EIP
  • The jump instructions for redirecting program control flow
  • The sequence of “no operation” CPU instructions (NOP sled)
  • The malicious payload which will ultimately generate the reverse shell for the attacker

The image below summarizes these phases.

8. Reverse shell listener

Successful shellcode execution lets the attacker gain a reverse shell back to their infrastructure. This will setup remote control to deploy additional appropriate post-exploit executable types for the victim system, such as EXE or DLL for Windows, ELF for Linux, and APKs for Android.  

At this point, the attacker now has remote code execution through an exploited buffer overflow attack. They can now download more capable malware payloads to spread the attack through the network using lateral movement techniques.  

I’ve written on examples of these kinds of techniques in my other articles, including How Attackers Move Laterally Through Your Environment and Malware Payloads & Beacons: How Malicious Communications Start.

Stack-based buffer overflow attacks work by overwriting a buffer and then running malicious code that’s been slipped in. To protect against them, security teams should focus on these key defenses:

  • Validate input. Properly check user input and use safe functions to accept that input. ‍
  • Turn on no execute / data execution prevention (NX / DEP). The operating system marks the stack as non-executable so that an attacker can’t inject and execute code. ‍
  • Enable address space layout randomization (ASLR). The operating system randomizes where the stack and other parts of memory are located, so it’s hard for attackers to predict addresses and jump to them.

Other options include stack canaries and secure coding practices, but no one method is a silver bullet to mitigate the risk.  

Why memory exploits matter for defenders

Virtual memory gives every process a predictable layout, with code, data, heap, and stack each kept in its own place. That predictability keeps programs running smoothly, and attackers rely on it too. Once they know where the return address sits on the stack, a single unchecked buffer can let them send the program somewhere it was never meant to go.

Memory corruption flaws have been around for decades, and they keep turning up in operating systems, applications, and the network devices organizations depend on every day. Patching closes individual holes, but there’s always a gap between when a vulnerability is discovered and when it’s fixed, and attackers work quickly to use that window.

That’s why it pays to plan for the moment an exploit succeeds. If an attacker gains code execution on one system, segmentation limits where that foothold can lead, so a single compromised process stays contained instead of spreading across the network.

Test drive Illumio Segmentation to see how you can close lateral movement paths and contain breaches at the point of entry.

Want more technical content? Join the Illumiverse, the Illumio user community, to connect with security peers and get hands-on with breach containment.

Related articles

Experience Illumio Insights today

See how AI-powered observability helps you detect, understand, and contain threats faster.