Mapping and Obfuscation with mmap, Part 2

The Lost Book of the Forbidden Syscalls. Chapter 3 - Bouncers
SYSCALL LINUX MMAP SHELLCODE MEMORY BOUNCERS PROGRAMMING LINUX CODE INJECTION

In this installment we'll see how to write small pieces of code to copy and delete memory blocks on remote procedures while injecting code. I've called those pieces of code Bouncers and you'll learn how to write them.

Bouncers

In this section, we’re going to use some small pieces of code with a very specific purpose, and I have to say that I had a tough time finding a name for them. Finally, I decided to refer to them as bouncers. These code blocks are not really functions but just a bunch of instructions. We’ll transfer control to them, let them do their stuff, and then they will jump back to the very same place from where they were called. To some extent, they resemble a trampoline, but they aren’t quite the same, so I think “bouncer” is a better name. However, the important thing is that you understand what we’re doing; the name doesn’t really matter that much.

Trampolines, Thunks, and Bouncers

In computation, there are some general constructs that are used by compilers to produce certain kinds of code. Those concepts are pretty complex, but when they are applied at assembly level, things become much simpler and clearer. Even though, as I said before, I had a tough time choosing a name for the code we’ll be running in this section, but for the sake of completeness, I’ll tell you about what’s out there, and then you can choose the name that you prefer in case you don’t agree with me.

The first thing that may come to our mind is to call this code a trampoline. A trampoline, at ASM level, is just a piece of code that transfers execution somewhere else, so its name. Your code jumps into some address and immediately it’s sent somewhere else. Trampolines usually don’t do much more; they just take some value from somewhere and use it to determine the address to jump to. In essence, most of the time, they are indirect jumps.

A thunk function is conceptually pretty similar but usually represents a computation that has been postponed (not to be performed immediately). The name comes from a fun transformation of the past participle tense of the verb think (Thought), which was transformed into thunk (like in sink/sunk, swim/swum, so think/thunk). These pieces of code were used in situations where you think that something needs to be done, then you postpone that task, and, therefore, when the action is finally performed, it was thunk before. The origin of the word was born in the domain of programming language design/implementation where those postponed calculations have a very specific meaning. In ASM, the term thunk or thunk function/code is usually referred to some instructions that take control, perform some operation, and then continue execution somewhere else.

What we’ll use in this section is something halfway between both but with the peculiarity that execution will be transferred back to the point where it was initiated. In this context, the Bounce word seems to better represent it. We jump somewhere, execute a few instructions, and then we jump back to the same place (ok, almost the same). You won’t find this name in literature. You’ll likely find the terms trampoline or thunk instead of bouncer, but I really think this term fits better here :)

Note that back in the golden age of the IRC, a bouncer was a program used to jump between computers before actually connecting to the IRC server. They had multiple purposes back in the day, like being always connected (to keep the op status in a channel), keep the log of messages, hide your IP, etc. Conceptually, they can be seen like proxies but much more simpler. Nowadays, services like IRCCloud offer similar capabilities.

In the previous section, when talking about non-destructive code injection, we introduced the problem of restoring the original code of a dynamically patched function. The problem is that code has to be run from the memory area that needs to be restored, and therefore, at first glance, it’s impossible to completely restore the original code because, at some point, the original code will overwrite the code that is restoring the code and eventually will break it. The loop restoring the original code will be overwritten by itself at some point. Yes, I know, all this sounds weird, but you see the problem, right?

So, in those cases, we need a small piece of code located somewhere else in memory where it can be run to restore the original instructions without overwriting itself in the process. I’ll refer to such a piece of code as a bouncer. We jump to the bouncer, it restores the original code, and jumps back into the original code. A similar situation occurs when trying to unmap the page of memory that contains the unmap system call; once the memory running the code to unmap the memory is unmapped, the code cannot be run anymore, and the program will crash. Again, we need to generate (or copy, or find) that code somewhere else in order to be able to unmap and free the memory used by the code. We’ll discuss this case later in this chapter.

There are two main ways of achieving this:

  • Allocating a memory page using mmap to copy the code we want to run, and execute it from there.
  • Or find some free space in the current code segment to inject the code and run it from there.

NOTE: There is a third way that consists in finding the pieces of code you need in memory and chaining them together to do what you want. We’ll talk about this later, but in any case, the code we need to run has to be executed from a different memory area. Same constraints apply.

In any case, it is not possible (in the general case, we’ll see how to do it, though) to completely get rid of all the injected code. The bouncer function will always stay for the reasons discussed above, so the goal is to make it as small and simpler as possible so that it won’t give any information about the code we’re trying to hide.

Let’s use our small RPG game from chapter 2 for demonstration purposes, and let’s inject some code, but this time, instead of restoring the code from the injecting program, let’s make the injected code restore itself. The whole system shall do something like the following:

  • The injector attaches to the target program.
  • Creates a memory block to back up the original code that will be overwritten with injected code.
  • Copies a small memory-copying code in the allocated memory to actually perform the copy.
  • Injects the payload in process.
  • Prepares the payload to return to the bouncer when finishing its stuff.
  • Runs the bouncer to restore original code.
  • Restores control to original process.

The first thing we need is a payload to implement this. Let’s keep using our effective payload, Hello, world!, and let’s add the additional code we need to make our plan work:

    global _start
_start:
    ;; Payload is just a hello world
    mov rax, 1
    mov rdi, 1
    lea rsi, [rel msg] ; buf = msg
    mov rdx, 14
    syscall ; (SYS_write = rax(1), fd = rdi (1), buf = rsi (msg), count = rdx (13))
    
    ;;  Bouncer code - Restore original code
    mov rsi, 0x1122334455667788 ; mbuf
    mov rdi, 0x1122334455667788 ; addr
    mov rcx, 0x00000000000001f8 ; size (pagesize / 8) - 8
    mov rax, 0x1122334455667788 ; Jump into reps movs (payload+pagesize/2 - 8)
    push rax
    mov rax, 0x1122334455667788 ; Jump into original rip
    push rax
    
    ret
msg:
db 'Hello, world!',0x0a

Don’t panic; I’ll explain what all those extra instructions added at the end are. It’s code that needs to be patched. For each specific binary it’s injected in, those values have to be carefully crafted to do what we want it to do. We’ll get to it in a sec.

Now we can create the hex dump to be included in our loader with the following commands, as we’ve already done many times before:

$ nasm -felf64 -o payload.o payload.asm
$ objcopy --dump-section .text=payload.bin payload.o
$ xxd -i payload.bin
unsigned char payload_bin[] = {
  0xb8, 0x01, 0x00, 0x00, 0x00, 0xbf, 0x01, 0x00, 0x00, 0x00, 0x48, 0x8d,
  0x35, 0x37, 0x00, 0x00, 0x00, 0xba, 0x0e, 0x00, 0x00, 0x00, 0x0f, 0x05,
  0x48, 0xbe, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x48, 0xbf,
  0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0xb9, 0xf8, 0x01, 0x00,
  0x00, 0x48, 0xb8, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x50,
  0x48, 0xb8, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x50, 0xc3,
  0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64,
  0x21, 0x0a
};
unsigned int payload_bin_len = 86;

Let’s dump the generated code so we can easily identify the offsets to the parts of the instructions that we need to patch.

$ objdump -d payload.o
__--snip--__
0000000000000000 <_start>:
   0:   b8 01 00 00 00          mov    $0x1,%eax
   5:   bf 01 00 00 00          mov    $0x1,%edi
   a:   48 8d 35 37 00 00 00    lea    0x37(%rip),%rsi        # 48 <msg>
  11:   ba 0e 00 00 00          mov    $0xe,%edx
  16:   0f 05                   syscall
  18:   48 be 88 77 66 55 44    movabs $0x1122334455667788,%rsi <==== 0x18 + 2
  1f:   33 22 11
  22:   48 bf 88 77 66 55 44    movabs $0x1122334455667788,%rdi <==== 0x22 + 2
  29:   33 22 11
  2c:   ba 00 10 00 00          mov    $0x01f8,%ecx
  31:   48 b8 88 77 66 55 44    movabs $0x1122334455667788,%rax <==== 0x31 + 2
  38:   33 22 11
  3b:   50                      push   %rax
  3c:   48 b8 88 77 66 55 44    movabs $0x1122334455667788,%rax <==== 0x3c + 2
  43:   33 22 11
  46:   50                      push   %rax
  47:   c3                      ret

0000000000000048 <msg>:
  48:   48                      rex.W
  49:   65 6c                   gs insb (%dx),%es:(%rdi)
  4b:   6c                      insb   (%dx),%es:(%rdi)
  4c:   6f                      outsl  %ds:(%rsi),(%dx)
  4d:   2c 20                   sub    $0x20,%al
  4f:   77 6f                   ja     c0 <msg+0x78>
  51:   72 6c                   jb     bf <msg+0x77>
  53:   64 21 0a                and    %ecx,%fs:(%rdx)

Now we’re ready to code our loader. Let’s get started.

Memory allocation and permission fixing

The first thing our loader has to do is to attach to the process and allocate memory. We’ll skip the first step that we’ve done a dozen times by now. In order to create a memory block to store the original code, we have to run an mmap syscall, which we can do in-place, the same way we’ve run mprotect other times. We already have a function to run syscalls in-place, but we need to extend it as mmap is a system call taking six parameters, which is something pretty unusual, and our previous implementation to use mprotect only took four.

int inject_syscall (pid_t pid, struct user_regs_struct *regs, uint64_t syscall,
            uint64_t p1, uint64_t p2, uint64_t p3, uint64_t p4,
            uint64_t p5, uint64_t p6) {
  int status;
  
  regs->rax = syscall;
  regs->rdi = p1;
  regs->rsi = p2;
  regs->rdx = p3;
  regs->r10 = p4;
  regs->r8  = p5;
  regs->r9  = p6;

  if (ptrace (PTRACE_SETREGS,pid,0,regs) < 0)  DIE ("PTRACE_SETREGS:");
  if (ptrace (PTRACE_SINGLESTEP,pid,0,0) < 0)  DIE ("PTRACE_SINGLESTEP:");
  wait (&status);

  return status;
}

We have just added two more parameters in the correct registers (as per the System V kernel ABI) before calling the system call. Now in the main program, we can create the memory block with a piece of code like:

  if ((v = ptrace (PTRACE_PEEKTEXT, pid, regs.rip, 0)) < 0)  DIE ("PTRACE_PEEKTEXT:");
  if (ptrace (PTRACE_POKETEXT, pid, regs.rip, 0x000000000000050f) < 0)  DIE ("PTRACE_POKETEXT:");
  inject_syscall (pid, &regs, 10, // mprotect
          addr & ~(pagesize - 1), pagesize, PROT_WRITE | PROT_READ | PROT_EXEC, 0, 0,0);
  inject_syscall (pid, &regs, 10, // mmap
          NULL, pagesize, PROT_WRITE | PROT_READ | PROT_EXEC, 0, 0, 0);
  if (ptrace (PTRACE_GETREGS,   pid, 0, &regs) < 0)  DIE ("PTRACE_GETREGS:");
  mbuf = regs.rax;

TECHNIQUE: Allocate memory in remote project

Code injection/Support Technique

Use ptrace to inject a syscall instruction and use the mmap system call to allocate memory. Then read back the register and get the pointer to the newly allocated memory from register rax. Check the System V ABI for your platform if working with a different architecture.

The code above injects a syscall instruction at the current RIP position in order to be able to run system calls in the target process memory addressing space. Then, it first invokes mprotect to enable writing in the code segment and after that calls mmap to allocate one memory page. In order to get the address for the newly allocated memory, we need to read the registers back and store the value of rax where mmap returns the pointer to the allocated VMA.

The values of pid and addr are provided from the command line to the program. Note that we’ll use one single page, but if your payload is much bigger, you may need to update those values. As mentioned before, I’m trying to keep the code as simple as possible but complete enough to fully demonstrate each technique.

Backing up original code

Our next step is to back up the original code of the program in the just created buffer, so we can restore it later. It’s possible to do this using ptrace_peek and ptrace_poke as we’ve seen on Chapter 1. process_vm_readv/writev is also an option, but it requires transferring the data back and forth between the processes, something that is actually not needed.

The easiest way to copy the original code is to run a rep movsq instruction, which, being just one instruction, we can run in-place. Exactly the same thing we do with the syscall but using another instruction. However, these Intel string instructions have the peculiarity that, even when they look like one single instruction when debugging, they behave like a loop, and we cannot use the PTRACE_SINGLESTEP to execute it. Instead, we have to insert a breakpoint after the instruction to fully run it. Fortunately, we already know everything about breakpoints.

The following code will effectively copy the main text segment of the target process (actually, the first page) into the mmap buffer we have just allocated:

  regs.rsi = addr;
  regs.rdi = mbuf;
  regs.rcx = (pagesize)/8 - 1; // Last word is for specialinstruction
  regs.rip = old_regs.rip;
  // in-place instruction execution
  if (ptrace (PTRACE_POKETEXT,   pid, regs.rip, 0x00000000cca548f3) < 0)  DIE ("PTRACE_POKETEXT:");
  if (ptrace (PTRACE_SETREGS,    pid, 0,        &regs) < 0)  DIE ("PTRACE_SETREGS:");
  if (ptrace (PTRACE_CONT, pid, 0,        0) < 0)  DIE ("PTRACE_SINGLESTEP:");
  wait (&status);
  
  // Inject rep movsq instruction in the allocated block to restore original code later
  if (ptrace (PTRACE_POKETEXT,   pid, payload + pagesize - 8, 0x00000000c3a548f3) < 0)  DIE ("PTRACE_POKETEXT:");

TECHNIQUE: Move memory blocks in remote project

Code injection/Support Technique/Intel specific

Use ptrace to inject a rep movsq followed by a break point to copy memory blocks within the target process without having to transfer the memory to the tracer process and back to the target. Set register accordingly and use PTRACE_CONT to complete the transfer.

The rep movsq instruction is encoded as 0xf3 0x48 0xa5. Note how we add the 0xcc (int3) breakpoint after the instruction to stop the execution just after the copy. Yes, it’s that simple. Therefore, we just need to set up the registers to work with that instruction. Register RSI contains the source of the data to copy, register RDI contains the destination, and register RCX the number of quadwords (we are using movsq, the q stands for quad words -8 bytes-) we want to copy. Note how we divide the page size by 8 so we transfer the right amount of quadwords.

NOTE: If you’re using other platforms than Intel, it’s likely that you won’t have string instructions. In that case, you need to inject instructions to run the loop, which, if you set up the registers using ptrace, can be easily done with 3/4 instructions. Check chapter 4 of Heavy Wizardry 101 if you don’t know how to do it ;)

I’m reserving the last word in the page to insert a rep movq and a ret (yes this contains a ret not a int3). That’s the 1 we subtract to rcx when setting it up. Remember we are moving quadwords so setting rcx to do one less transfer will leave 8 bytes unused at the end of the page. This code will be used to restore the overwritten code in the text segment whenever our payload is done with its task. That’s our next step.

Patching payload for clean-up

It’s time to inject our payload (that will be a single call to process_vm_writev) but before, we need to patch some values in it. Let’s take a look to the last part of the payload code:

    mov rsi, 0x1122334455667788 ; mbuf
    mov rdi, 0x1122334455667788 ; addr
    mov rcx, 0x00000000000001f8 ; size (pagezie / 8) - 8
    mov rax, 0x1122334455667788 ; Jump into original rip
    push rax                    ; (1)
    mov rax, 0x1122334455667788 ; Jump into reps movs (payload+pagesize/2 - 8)
    push rax                    ; (2)
    ret                         ; Effectivelly jump into reps movsq

This code is in charge of restoring the original instructions overwritten by the payload and return control to the original program. I know it doesn’t look like that, but it really is.

The first three instructions set the values of rsi, rdi, and rcx to execute the rep movsq instruction that we stored in the latest quad word of our allocated memory block. In the comments, you can see the values that we have to set, basically copying from mbuf (our allocated buffer) into addr that is the .text segment address we’ve overwritten.

Then we push onto the stack, in reverse order, the address in the main program to which we want to return (1) followed by the address where the rep movsq instruction is (2). When we run the ret instruction at the end of the payload, control will be transferred to the rep movsq instruction that, if you remember, is followed by another ret. That ret will restart the execution in the main program after the rep movsq is done. That’s because the next address in the stack is the original rip address that our bouncer has pushed strategically (1).

The C code that implements all this is as follows:

  *((uint64_t*)(payload_bin + 0x18 + 2))  = payload; // Source
  *((uint64_t*)(payload_bin + 0x22 + 2))  = addr; // Source
  *((uint64_t*)(payload_bin + 0x31 + 2))  = func; // Finally return into patched func  
  *((uint64_t*)(payload_bin + 0x3c + 2))  = payload + pagesize - 8; // movsq + ret

  local1[0].iov_base = payload_bin;
  local1[0].iov_len  = payload_bin_len;

  remote[0].iov_base = (void*)func;
  remote[0].iov_len  = payload_bin_len;
  
  if ((process_vm_writev (pid, local1, 1, remote, 1,0)) < 0) DIE ("process_vm_writev:");

Here, the func parameter is also provided by the user through the command-line. For this example, using our game from Chapter 2, the function I’m using is game_step which is pretty standalone and easy to reuse. It has little interaction with anything else except the game’s main loop.

Now we can just restore the instruction we overwrite for running our syscalls and the original registers to let the original program run but with some injected code in it that will be executed next time there is an iteration in the game (the user presses a key).

  if (ptrace (PTRACE_POKETEXT, pid, old_regs.rip, v) < 0)  DIE ("PTRACE_POKETEXT:");
  if (ptrace (PTRACE_SETREGS, pid, 0, &old_regs) < 0)  DIE ("PTRACE_SETREGS1:");

  // Let the tracee continue
  if (ptrace (PTRACE_DETACH,   pid,        0,         0) < 0) DIE ("PTRACE_DETACH:");
  return 0;     

Let’s add a simple diagram to clarify a bit more what we’ve done.

addr --> +----------------+                 +----------------+                 +----------------+
         | .text segment  |                 | .text segment  |                 | .text segment  |
         ~                ~  code injector  ~                ~  after running  ~                ~
func --> | game_step      |  executed       | payload        |  payload        | game_step      |
         |                | ==============> | restore code   | ==============> |                |
         | main           |                 |                |                 | main           |
         ~                ~                 ~                ~                 ~                ~
         +----------------+                 +----------------+                 +----------------+
         
mbuf/mmapped buffer ----------------------> +----------------+                 +----------------+ 
                                            | .text segment  |                 | .text segment  |
                                            ~                ~                 ~                ~
                                            | game_step      |                 | game_step      |
                                            |                |                 |                | 
                                            | main           |                 | main           |
                                            ~                ~                 ~                ~
                                            | rep movsq      |                 | rep movsq      |
                                            | ret            |                 | ret            |
                                            +----------------+                 +----------------+

The left side shows the original program executing normally. The center shows the state just after running the injector program. The right shows how memory looks like after running the payload and restore code. As you can see, the original program is perfectly fine but there are some leftovers. A whole page with a copy of the original code is left there. We’d better look for ways to get rid of this page and leave everything as we found it before injecting any code.

Techniques to remove the bouncer

I have titled this section after removing the bouncer because that’s the tricky part. We could just allocate two pages—one for the original code and one for the bouncer—and just unmap the first one, leaving us only with the bouncer code in memory, which isn’t that much. We already know it’s not that easy to do that because the memory areas where we can run code either contain the copy of the original code (which we’ve just restored and we don’t want to change again) or it contains the code to execute, and therefore if we unmap that block a segfault will happen. Despite how complex it is, the way to achieve this is to run the munmap system call from somewhere else and then get the final code executed somehow.

The idea is simple: if we cannot use our own syscall or jmp, let’s take a look at what is already available in the main program and use it. This is the basis of a technique called ROP (Return-Oriented Programming). We briefly introduced it in chapter 2 if you remember, and we have just used it in the previous section without formally naming it. The technique consists of finding the so-called gadgets (small sets of 2 or 3 instructions) that can be chained in a way that some arbitrary code is executed. To achieve that, those gadgets require some jump instruction at the very end that allows the programmer to set up a sequence or chain of gadgets to achieve some goal.

BOX: ROP, JOP, SROP, etc.

I’ve described ROP in a very lousy way in the main text, so let’s explain with some more detail the exact meaning of all those terms. They all come from the exploitation world as techniques developed to circumvent protections like non-executable stacks, for example. The very first technique developed, which we can consider part of this family, is ret2libc, which, instead of trying to feed the payload in the stack and jump in there as a classical buffer overflow does, tries to force the function to return into some Libc function like system to achieve its goal, for instance, to get shell access.

The idea was generalized, and instead of returning into a specific function, why not build the function out of pieces of code already existing in the memory of the program? If each of those pieces ends in a ret instruction and we fill the stack with a sequence of pointers to those pieces, we can manipulate the values of registers and eventually jump into a syscall instruction to do whatever we want. This is the so-called ROP or Return Oriented Programming as it’s based on chaining code by running a sequence of ret instructions. This is actually what we’ve used to implement our bouncer but injecting some of the instructions ourselves instead of finding gadgets in the original code.

This technique can be generalized, and instead of using just ret, it can extend it with indirect jumps. This is known as JOP or Jump Oriented Programming. Both techniques, ROP and JOP, are sometimes referred to as COP Call Oriented Programming.

SROP or Sigreturn Oriented Programming is a similar technique that abuses the way signal handlers return, creating artificial signal frames, which provides control over all registers in one go. This is a pretty powerful technique because of this (controlling all registers).

I’d say that these are the main ones you need to know about. After these became well known, people started to do variations of them and create all kinds of acronyms finishing in OP, however, most of them are based on the same principles, and it’d be easy for you to learn the details of any of them once you know the general workings of the techniques.

This is one of those topics in which malware development or binary analysis meets exploitation techniques and shows you how things don’t just fit in one single category and can be used for different purposes whenever you know what you are doing.

The typical gadget example is some instruction used to set a register, either using other registers or the stack, followed by a ret. Carefully pushing the address of those gadgets onto the stack, arbitrary code can be executed just by running a ret instruction that will fire the sequence. There are much more complex ways of doing this, but for our purposes, I’ll keep it simple enough to be easy to follow at the same time I provide enough details for you to research the topic on your own in case you’re interested.

Let’s start with the more straightforward solution. As our program is linked to libC, let’s just call munmap (this is a ret-to-libc approach), actually the lib C wrapper to the munmap system call. For doing that, we need to do some changes. First, we need to add one more gadget to our ROP chain to call munmap and also we need to set the rsi and rdi parameters as the munmap syscall requires two parameters. Let’s first take a look at the changes to our payload:

    global _start
_start:
    ;; Payload is just a hello world
    mov rax, 1
    mov rdi, 1
    lea rsi, [rel msg] ; buf = msg
    mov rdx, 14
    syscall ; (SYS_write = rax(1), fd = rdi (1), buf = rsi (msg), count = rdx (13))
    ;;  Restore original code
    mov rsi, 0x1122334455667788 ; mbuf
    mov rdi, 0x1122334455667788 ; addr
    mov rcx, 0x0000000000001f8  ; size
    mov rax, 0x1122334455667788 ; Jump into game function
    push rax
    mov rax, 0x1122334455667788 ; Jump into munmap
    push rax
    push rsi                    ; Already set to mbuf
    mov rax, 0x1122334455667788 ; Jump into reps movsq
    push 4096   
    push rax
    ret
msg:
db 'Hello, world!',0x0a

TECHNIQUE: Return to LibC

Code injection/Exploitation/Support Technique

Inject into the stack the address of a LibC function you want to run and then let the program execute ret and fire execution of the LibC function. Note that you need to use some other technique to set the values of the registers you need to pass to the function you want to execute.

The code is almost the same with the exception of the extra jump to munmap through the stack and the required parameters that we’re passing also in the stack. Note that we have hard-coded the size of a page (4096) to save one step in the injector code.

For this code to work, we also need to update the small bouncer/trampoline in our allocated page, which will now look like this:

00: f3 48 a5                rep movsq
03: 5e                      pop    rsi
04: 5f                      pop    rdi
05: c3                      ret

The parameters from the stack are retrieved in reverse order, so rsi will contain the memory block size (one page 4096 bytes) and rdi will contain the address to the memory buffer.

The main program is almost identical to the previous version; we just need to inject the new trampoline and patch one more address. These are the relevant lines:

__--snip--__
  // Inject rep movsq instruction in the allocated block to restore original code later
  if (ptrace (PTRACE_POKETEXT,   pid, payload + pagesize - 8, 0x0000c35f5ea548f3) < 0)
    DIE ("PTRACE_POKETEXT:");

  // Original code copied. We can write payload at main code/ specific function
  // Patch payload
  *((uint64_t*)(payload_bin + 0x18 + 2))  = payload; // Source
  *((uint64_t*)(payload_bin + 0x22 + 2))  = addr; // Source
  *((uint64_t*)(payload_bin + 0x31 + 2))  = func; // Finally return into patched func  
  *((uint64_t*)(payload_bin + 0x3c + 2))  = umap; // munmap wrapper
  *((uint64_t*)(payload_bin + 0x48 + 2))  = payload + pagesize - 8; // movsq + ret
__--snip--__

Everything else remains the same. The munmap variable is the pointer to the munmap libC wrapper that we’ll pass as a new argument through the command-line. Now we just need to calculate that value.

Let’s start our game program in a console and get its PID. In my system, for this execution, the PID is: 4130993. This is the first parameter to our code injector. Next parameter is addr that we get from the process memory map:

$ cat /proc/4130993/maps | grep xp
5574b6d4c000-5574b6d4d000 rwxp 00001000 fd:01 49676378   /opt/syscalls/process_vm/game
7fbac561d000-7fbac5780000 r-xp 00028000 fd:01 50080079   /usr/lib/x86_64-linux-gnu/libc.so.6
7fbac580d000-7fbac580f000 r-xp 00000000 00:00 0          [vdso]
7fbac5810000-7fbac5838000 r-xp 00001000 fd:01 50080073   /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.s

The second parameter will then be 0x5574b6d4c000 (addr). The third parameter we get it from the output of game, I modify the source code to print the address of game_step which in this case is 0x5574b6d4c21c, and only the umap value is missing. Note that, in order to get the pointer to game_step, you can follow the same steps we’re going to do for munmap.

To calculate the memory address of munmap, we need three values: The executable VMA for libC (for game_step, you’ll use the VMA for game text segment), which we’ve already got from the process memory map listing above. In this case, it’s 0x7fbac561d000. Then, we need the offset of the symbol that we can easily get using readelf:

$ readelf -s /usr/lib/x86_64-linux-gnu/libc.so.6 | grep munmap
   925: 000000000010d710    33 FUNC    WEAK   DEFAULT   15 munmap@@GLIBC_2.2.5

That is 0x10d710 in this case. Finally, we need to know where in memory the .text segment gets loaded. We can get that information from the lib C program headers:

$ readelf -l /usr/lib/x86_64-linux-gnu/libc.so.6 | grep -B1 "R E"
  LOAD           0x0000000000028000 0x0000000000028000 0x0000000000028000
                 0x000000000016287d 0x000000000016287d  R E    0x1000

That, for this case, is 0x28000. Therefore, the address of munmap in memory is:

$ printf %x <<< echo $((0x7fbac561d000 + 0x10d710 - 0x28000)
7fbac5702710

If we run the program now… It’ll crash. And you’ll have to debug. Debugging this kind of programs may be tricky because we’re using the debugging interface to inject the code and we cannot attach two debuggers to the same process. Fortunately for us, the way we have planted the code allows us to do all the injection and detach of the process without automatically firing the code. The payload will just be executed when the user presses a key in the game. So, after injecting the code, we can attach a debugger and see what happens.

If you place a few breakpoints here and there (actually game_step and the exit of our trampoline are good places), you’ll see that everything works as expected, but the program crashes when returning the code to the game_step function after running the payload and deleting the memory block. The problem happens exactly here:

000000000000121c <game_step>:
    121c:   55                      push   %rbp
    121d:   48 89 e5                mov    %rsp,%rbp
    1220:   48 83 ec 20             sub    $0x20,%rsp
    1224:   48 89 7d e8             mov    %rdi,-0x18(%rbp)
    1228:   48 8b 45 e8             mov    -0x18(%rbp),%rax

This is the prologue of the game_step function, which receives a parameter on rdi and stores it on the stack. What happens is that, when we return to this point from our trampoline (actually when we return from munmap), rdi is actually pointing to the memory block we’ve just unmapped, and therefore that memory is not valid anymore. Actually, rdi doesn’t point to the game status structure anymore. The correct way to solve this is to create a more complex ROP chain to set RDI to the right value (the pointer to the game state struct). Alternatively, we can just inject our code at 0x1228 instead of at 0x121c; this way, the function parameter gets stored on the stack before our payload gets executed, and when we restore the execution at 0x1228 instead of 0x121c, the required value is already on the stack. Just add 12 to the pointer to game_step and everything will work fine because we’re not touching rbp and rsp.

Note that it’s worth to spend sometime choosing an injection point to make our lives easier. A function without parameters is better, and a function with many parameters is more complicated (we need to restore much more). In any case, you may likely have to look for gadgets in libC itself instead of in your program.

In this case, the munmap function was available, so things were much easier. If not, we’d look for a syscall, which will work pretty much the same way.

BOX: Signal Return Programming

Check appendix 1 for the details on how to use this technique. In this box, I’d just give you an overview so you know this technique exists and what it can do, but I won’t tell you here how to implement it. As said, refer to appendix 1.

Signal-return programming is a technique that abuses the way signal handler returns control to the main program. It works like this:

  • The process receives a signal
  • The kernel sets a so-called signal frame in the stack and also a trampoline that gets executed when the handler returns
  • Then, control is given to the handler as a regular function; however, the return address for that function is the kernel-generated trampoline, not the address being executed by the process when the signal arrives.
  • The handler does its stuff and returns
  • The ret takes the return address from the stack and jumps into the kernel trampoline
  • The trampoline uses the signal frame to restore the values of registers and other information to prepare the return to the main program at the point where it was interrupted
  • This process is fired by the rt_sigreturn system call

This whole process can be abused to run arbitrary system calls at different places in the program, which is what we wanted to do in this section. The technique works as follows:

  • A fake signal frame is set up. This allows us to give values to all registers and prepare everything to run any syscall (rax value) with any set of parameters (rdi, rsi,…).
  • The rip register is set to an address that contains a syscall instruction
  • Then, the rt_sigreturn syscall is invoked

At that time, the kernel will restore all registers as per the signal frame context, which includes the value of rip, and give control back to user space. The program restarts at an address containing the syscall instruction (as we mentioned above), which will effectively run the syscall arranged in the signal frame registers. As you can see, if you find a convenient syscall followed by a ret or jmp, this technique may be very useful in cases like the one we discussed in this section.

We managed to inject code in a running process, run it, and then leave everything as it was before without a hint of what has happened. It was a bit complex, but I think it was pretty cool.

Don't miss the next installment. COMING SOON!
Get the code at https://github.com/0x00pf/lbofs

If you liked this post you may also find interesting our book "Heavy Wizardry 101".

Related Posts

System Programming

The path to fully understand how your computer works under the hood

Read

SYSTEM PROGRAMMING GNU/LINUX WEB SECTION

Peek and Poke on Steroids process_vm_readv/writev. Part 1

The Lost Book of the Forbidden Syscalls. Chapter 2 - Destructive Code Injection

Read

SYSCALL LINUX PROCESS_VM_READV PROCESS_VM_WRITEV PROGRAMMING LINUX CODE INJECTION

Mapping and Obfuscation with mmap, Part 1

The Lost Book of the Forbidden Syscalls. Chapter 3 - Shellcode run and Mapping Manipulation

Read

SYSCALL LINUX MMAP SHELLCODE MEMORY MODULE STOMPING PROGRAMMING LINUX CODE INJECTION

Return to Home Page