Mapping and Obfuscation with mmap, Part 1

The Lost Book of the Forbidden Syscalls. Chapter 3 - Shellcode run and Mapping Manipulation
SYSCALL LINUX MMAP SHELLCODE MEMORY MODULE STOMPING PROGRAMMING LINUX CODE INJECTION

The system calls we’re going to talk about in this chapter aren’t that exotic, but they’re key for many of the techniques we’ll be discussing in this book, so we better get familiar with them earlier than later. I’m talking about mmap and mprotect, used to allocate and manipulate memory at, maybe, the lowest level allowed by the operating system, at least from user space.

In this chapter, we’ll learn how to use those system calls and how they are used in different security-related techniques. Among other things, we’ll see how to allocate memory in a remote process for our own purposes (like running injected code), make that memory look like a regular library when seen from outside, how to generate code at runtime, obfuscate it, or patch files in memory easily. Yes, mmap is at the core of some pretty cool techniques. We’ve already met mprotect in previous chapters, but we’ll learn some specifics about this system call in this chapter too.

Let’s start with the basics.

Memory allocation

Let’s start with the system call prototype, for those of you not familiar with it. Here it is:

void *mmap(void addr[.length], size_t length, int prot, int flags,
                  int fd, off_t offset);

Basically, mmap allows us to allocate a memory block of a given length, assigning some permissions and properties in the way. We’ll talk later about the flags and the last parameters fd and offset. For now, let’s obviate them and we’ll set them all to zero in our very first programs.

What mmap actually does is create a so-called VMA or Virtual Memory Area. We’ve briefly talked about them when learning about process memory maps in Chapter 2. A VMA, when created with mmap, defines a piece of the virtual memory address space mapped to a given process, but initially, no real memory is assigned for that virtual memory block. When the process first accesses that memory, for reading or writing, the kernel will actually assign real memory to the process. This may sound confusing—like: Are we allocating memory or not? I’ve got you. We need to look a bit deeper to fully understand this. It’s easier than it looks, but for the impatient ones: Yes, we do.

The Linux kernel uses pages to manage computer memory. A page is a block of memory with a fixed size. In Linux, as of this writing, the page size is 4096 bytes. The physical memory of the computer is also logically organized in pages, so addresses from 0 to 4095 belong to page 0, addresses 4096 to 8191 belong to page 1, and so on.

Memory Pages and Page Alignment

Working with pages is pretty easy if you choose a page size that is a multiple of 2, like 4096. 4096 is 2 to the 12th power (you can check it). Which means that, given a 32-bit address, the lower 12 bits are the offset in each page, and the 20 remaining bits are the page number. Let’s see this with real numbers. For that, let’s consider our addresses to be 32 bits and make our pages 16KB, which is 2 to the power of 16 (16 bits). This way, the page offset is two bytes (remember 1 byte is 2 hex digits), and we can easily write the addresses in hex and do the required calculations. Let’s see how this works with a few addresses:

0x000000ff -> This is page 0x0 (0x0000) offset (0x00ff)
0x000100ff -> This is page 0x1 (0x0001) offset (0x00ff)
0x12344321 -> This is page 0x1234 (0x1234) offset (0x4321)

Easy right? The high part of the address is the page number, and the lower is the offset inside that page. You calculate the base address of each page by multiplying the page number by the size of the page, which, in binary, when multiplying by a multiple of 2, is just a left shift of the bits. Think about it—when you multiply any number by 10, you are actually shifting the digits left and adding zeros to the right. With base two, it’s the same when you multiply by 2 and therefore by any power of two. In the same way, given an address, you calculate the page number associated with it by shifting bits to the left. In Linux, the page size is by default 4096 bytes, or 0x1000, which is 12 bits. So, shifting a page number 12 bits to the left gives us the base address of the page, shifting an address 12 bits to the right gives us the page number, and keeping the lower 12 bits of an address gives us the offset of that address in the page.

This is a good time to talk about page alignment, which is something that keeps popping up while doing low-level programming. An address is page aligned when it is located at offset 0 of a page, or, in other words, that the lower bits of the address are 0. For a page size of 0x1000, the first offset in the page is 0, and the highest is 0x0FFF. The next value is 0x1000, which is offset 0 in page 1. So, how do you align any address to a page boundary? Take the page size (0x1000), minus 1 (0xfff); this gives you the last offset in the page, which happens to be a bit mask with as many 1s as bits are used by the page size (12 bits in this case, remember that each hex digit is 4 bits). To make a bit zero in any binary number, the easiest way is to use the AND operation with a mask. Any bit in the mask set to 1 keeps its value in the original operand; otherwise, it’s set to zero. Therefore, we need to negate the value we have (pagesize - 1) before doing the AND operation. Let’s see an example:

    0x401000 -> 0x401000 & 0xFFF000 = 0x401000
    0x401234 -> 0x401234 & 0xFFF000 = 0x401000
    0x517023 -> 0x517023 & 0xFFF000 = 0x517000

You’ll see this code all over the place (addr & ~(pagesize - 1)). Hopefully, now you know where this comes from.

On the other hand, the kernel manages a so-called virtual memory address space, which is the basis for a lot of the amazing things the kernel can do. Let’s see what is maybe one of the first applications of the virtual memory concept. Imagine two different programs, ELF files, whose PHDRs say that the code has to be loaded at address 0x400000. That’s the usual case with old good non-PIE 64-bit static binaries. When loading the first one into memory, there is no problem—we read the code from the file and write it at physical address 0x400000, and everything will work OK. We’re assuming that the computer has physical memory accessible at that address.

Now, imagine that you want to run a second program that has to be loaded at the very same address. Think about it—we cannot make each program use a different load address (that was the case in the very early days for specific systems). That would be a management nightmare. So, we cannot load a second program at the same memory address without overwriting the first one. We could just allow one program at a time and have a monoprocessing system. We could also let the kernel overwrite that memory page every time each process has to run (when the kernel scheduler assigns the CPU to each program). That could be a possibility, but it’s very inefficient and introduces other problems. So, what the kernel does is define a virtual address space, which roughly means introducing an indirection or an address translation layer if you prefer. Note that even when the kernel orchestrates all this, the actual operations are done by the processor at the hardware level.

So, each process has its own virtual address space, and that’s achieved by giving them their own page table. A page table is a table that maps virtual memory pages (or addresses, in the last instance) into physical memory pages. This way, in our previous example, process1 may have its code loaded at the physical memory address 0x100000 (for example), and the second process at 0x200000 (for example). Each process has a table that maps the address 0x400000 to those different physical addresses.

Process 1 Page table                          Physical Memory Pages
~          ~                                  ~
+----------+                                  +----------+
| 0x400000 |--------------------------------> | 0x100000 |
+----------+                                  +----------+
| 0x401000 |                                  | 0x101000 |
~          ~                                  ~          ~
Process 2                                     | ........ |
~          ~                                  ~          ~
+----------+                                  +----------+
| 0x400000 |--------------------------------> | 0x200000 |
+----------+

The figure above shows the page table for process 1 and process 2. Address 0x400000 of process 1 points to physical address 0x100000, while address 0x400000 of process 2 points to physical address 0x200000. The translation between virtual and physical addresses is done automatically by the processor, actually by the so-called MMU or Memory Management Unit. Your program just accesses address 0x400000, and the processor will read/write the data in the correct physical address.

NOTE: In the past, the MMU was a separated chip sitting between the CPU and the memory doing this kind of operation. Nowadays (actually, quite some years ago), this functionality was moved into the processor where it makes more sense.

The mmap system call creates a VMA as mentioned above but doesn’t assign physical memory to the process. What happens is that a page fault is fired on the first access to any address on the VMA defined by mmap, and it’s at that point when the kernel allocates a physical memory page assigned to those virtual addresses and updates the process page table accordingly (actually, just the table entry or PTE, Page Table Entry). In the figure above, the process 1’s page at 0x400000 has physical memory assigned, but the page at 0x401000 doesn’t. That page is mapped to the process, but has no physical memory assigned to it. When the process accesses an address in that page, a page fault exception is fired (because there is no page associated with that PTE), and the kernel will assign a physical memory page to that page table entry. This provides a very efficient way to manage the memory at the same time that allows different processes to use the same virtual memory address range even when the content of those addresses is different for each one of the processes. We’ll see how all this works in detail in a later chapter; for now, this is more than enough to follow this chapter.

Sparse arrays

Sparse arrays are data structures in which most of their entries have a default value, usually zero or undefined. They are common in scientific and mathematical software; think, for instance, of a diagonal matrix of 1024x1024 entries. From the almost 105000 entries in the matrix, only 1024 are non-zero. There are different ways to store this kind of data structure effectively. mmap is a natural way to implement them because of what we’ve just described.

When allocated, no real memory will be assigned to the array. Only when we write data into the array will physical memory be assigned. Note that, in the case of reading, the system will map the associated page to the very same physical page full of zeros, so you can access the array normally but only using the memory that you really need.

Despite the simplicity of this approach, there is one caveat: granularity. Using mmap for this purpose will set the granularity of the data to a page or 4KB (the current Linux page size). If the sets of data in your array are close to this size, then the solution will be pretty good; otherwise, you may end up having quite some internal fragmentation and waste more memory than using other methods to represent the sparse array. You may also want to organize the bytes in memory in a way that really takes advantage of this memory feature.

This overall structure is pretty cool because it can also be used the other way around, making processes share physical memory. Imagine the case in which the same process is run twice, or even better, think about two different processes both using LibC, which has to be loaded into memory. LibC is loaded into physical memory only once. Then each process using the library will populate its page table accordingly to point to the right physical pages.

Process 1 Page table                          Physical Memory Pages
      ~          ~                       ~          ~
      +----------+                       +----------+
code  | 0x400000 |---------------------> | 0x100000 | .text segment Pocess 1
      +----------+                       +----------+
lib C | 0x401000 |-----------+---------> | 0x101000 | .text shared segment for LibC
                             |           ~          ~
      Process 2              |           | ........ |
      ~          ~           |           ~          ~
      +----------+           |           +----------+
      | 0x400000 |---------------------> | 0x200000 | .text segment Process 2
      +----------+           |
lib C | 0x401000 |-----------+      

In the diagram above, both processes map LibC at the same virtual address, but they could be mapped at pretty different addresses. Actually, that is what happens in reality when ASLR is active. However, instead of having two copies of the LibC code, the kernel just makes the relevant page entries in each process point to the correct physical page. This is how shared libraries are managed and the reason why programs load faster when their libraries have already been used before.

This is all the theory we need to know in order to follow this chapter. There are a few more concepts that will be introduced a bit later, but for now, let’s start seeing the most basic usage of this system call: memory allocation.

Shellcode execution

In previous chapters, we’ve seen how to inject system calls and pieces of code into existing memory blocks in a process. Depending on what you want to do, that may be enough, but, for instance, non-destructive injections require saving the original code, changing memory permissions (depending on the technique used), writing the new code, running it, and restoring the previous code. Alternatively, we could just allocate a memory block, copy code into it, run it, and discard it afterwards. This last step may be tricky, but we’ll talk about it later.

The following code shows how to allocate memory, copy code into it, and run it:

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <sys/mman.h>

unsigned char hello_bin[] = {
  0xb8, 0x01, 0x00, 0x00, 0x00, 0xbf, 0x01, 0x00, 0x00, 0x00, 0x48, 0x8d,
  0x35, 0x13, 0x00, 0x00, 0x00, 0xba, 0x0e, 0x00, 0x00, 0x00, 0x0f, 0x05,
  0xb8, 0x3c, 0x00, 0x00, 0x00, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x05,
  0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64,
  0x21, 0x0a
};
unsigned int hello_bin_len = 50;

int main () {
  uint8_t *sc;

  sc = mmap (NULL, 4096, PROT_EXEC | PROT_WRITE | PROT_READ,
         MAP_ANON | MAP_PRIVATE, 0 ,0);
  memcpy (sc, hello_bin, hello_bin_len);
  ((void (*)())sc)();
  puts ("DONE");
}

You may recognize our Hello world! shellcode used in previous chapters. The program above just allocates 1 page of anonymous (MAP_ANON) private (MAP_PRIVATE) memory, with read, write, and exec permissions. It copies the shellcode into that memory block and then runs it. The run instruction is a bit convoluted, as we have to convert our byte pointer to a function pointer in order to be able to call the injected code as a function from our C program. We can make it a bit more readable by defining a type to represent the function pointer.

  typedef void (*FUNC)();
  ((FUNC)sc)();

The first line declares a type named FUNC that is a pointer to a function returning void and receiving any number of parameters. Then, we cast the sc byte pointer to this type (a function pointer) and we call it as a function. That is done by the last () in the second line. We can make it even more readable:

  typedef void (*FUNC)();
  FUNC f = (FUNC)sc;
  f();

All three pieces of code do the same.

Note that the shellcode we’re using calls exit, so control is never returned to main. We can easily update the shell code by removing the second syscall and changing it to a ret (opcode 0xc3). Doing that, control will be returned to main, and that will give us a chance to take a look at the memory map of the process. This is the final code:

#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>

unsigned char hello_bin[] = {
  0xb8, 0x01, 0x00, 0x00, 0x00, 0xbf, 0x01, 0x00, 0x00, 0x00, 0x48, 0x8d,
  0x35, 0x13, 0x00, 0x00, 0x00, 0xba, 0x0e, 0x00, 0x00, 0x00, 0x0f, 0x05,
  0xb8, 0x3c, 0x00, 0x00, 0x00, 0xbf, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x00, // <--- RET goes here (see the 0xc3)
  0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64,
  0x21, 0x0a
};
unsigned int hello_bin_len = 50;

int main () {
  uint8_t *sc;

  printf ("PID: %ld\n", getpid());
  getchar ();
  sc = mmap (NULL, 4096, PROT_EXEC | PROT_WRITE | PROT_READ,
         MAP_ANON | MAP_PRIVATE, 0 ,0);
  memcpy (sc, hello_bin, hello_bin_len);
  getchar ();
  typedef void (*FUNC)();
  ((FUNC)sc)();
  puts ("DONE");
  munmap (sc, hello_bin_len);
  getchar ();
  return 0;
}

TECHNIQUE: Shellcode execution on mmaped memory

Code injection

Use mmap to allocate memory with the right permissions, copy shellcode into that memory area, and transfer control to it in order to get the code executed.

This is the same code we used before, but with the exit syscall removed from the shellcode and a few getchar() calls to stop the program at specific points to examine the memory map of the process. We’ve also added a call to munmap, which is the system call to unmap memory and effectively free it. The prototype for this syscall is as follows:

  int munmap(void addr[.length], size_t length);

It requires the address to be freed and its size. The address provided to munmap has to be the same returned by mmap.

Back to our example, let’s run the program in a console and use another console to look at the memory map at the relevant points in the program. That’s where we added getchars.

The original map (remember, this is the output of /proc/PID/maps), before doing anything, would look like this:

559ba8b12000-559ba8b13000 r--p 00000000 fd:01 49676469    /opt/syscalls/mmap/mmap2
559ba8b13000-559ba8b14000 r-xp 00001000 fd:01 49676469    /opt/syscalls/mmap/mmap2
559ba8b14000-559ba8b15000 r--p 00002000 fd:01 49676469    /opt/syscalls/mmap/mmap2
559ba8b15000-559ba8b16000 r--p 00002000 fd:01 49676469    /opt/syscalls/mmap/mmap2
559ba8b16000-559ba8b17000 rw-p 00003000 fd:01 49676469    /opt/syscalls/mmap/mmap2
559bcc5bd000-559bcc5de000 rw-p 00000000 00:00 0           [heap]
7f7a2177f000-7f7a21782000 rw-p 00000000 00:00 0
7f7a21782000-7f7a217aa000 r--p 00000000 fd:01 50080079    /usr/lib/x86_64-linux-gnu/libc.so.6
7f7a217aa000-7f7a2190d000 r-xp 00028000 fd:01 50080079    /usr/lib/x86_64-linux-gnu/libc.so.6
7f7a2190d000-7f7a21963000 r--p 0018b000 fd:01 50080079    /usr/lib/x86_64-linux-gnu/libc.so.6
7f7a21963000-7f7a21967000 r--p 001e0000 fd:01 50080079    /usr/lib/x86_64-linux-gnu/libc.so.6
7f7a21967000-7f7a21969000 rw-p 001e4000 fd:01 50080079    /usr/lib/x86_64-linux-gnu/libc.so.6
7f7a21969000-7f7a21976000 rw-p 00000000 00:00 0
7f7a21994000-7f7a21996000 rw-p 00000000 00:00 0
7f7a21996000-7f7a2199a000 r--p 00000000 00:00 0           [vvar]
7f7a2199a000-7f7a2199c000 r-xp 00000000 00:00 0           [vdso]
7f7a2199c000-7f7a2199d000 r--p 00000000 fd:01 50080073    /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f7a2199d000-7f7a219c5000 r-xp 00001000 fd:01 50080073    /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f7a219c5000-7f7a219d0000 r--p 00029000 fd:01 50080073    /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f7a219d0000-7f7a219d2000 r--p 00034000 fd:01 50080073    /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f7a219d2000-7f7a219d3000 rw-p 00036000 fd:01 50080073    /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7f7a219d3000-7f7a219d4000 rw-p 00000000 00:00 0
7ffca3da5000-7ffca3dc6000 rw-p 00000000 00:00 0           [stack]

Pretty standard mapping. From now on, I won’t show the libc, ld-linux, [heap], [stack], [vvar], and [vdso] entries to keep the output short, unless it’s relevant for the topic under discussion. Let’s press Enter and let the program execute the mmap system call. The map is now different.

559ba8b12000-559ba8b13000 r--p 00000000 fd:01 49676469   /opt/syscalls/mmap/mmap2
559ba8b13000-559ba8b14000 r-xp 00001000 fd:01 49676469   /opt/syscalls/mmap/mmap2
559ba8b14000-559ba8b15000 r--p 00002000 fd:01 49676469   /opt/syscalls/mmap/mmap2
559ba8b15000-559ba8b16000 r--p 00002000 fd:01 49676469   /opt/syscalls/mmap/mmap2
559ba8b16000-559ba8b17000 rw-p 00003000 fd:01 49676469   /opt/syscalls/mmap/mmap2
7f7a2177f000-7f7a21782000 rw-p 00000000 00:00 0
7f7a21969000-7f7a21976000 rw-p 00000000 00:00 0
7f7a21993000-7f7a21994000 rwxp 00000000 00:00 0  <======================
7f7a21994000-7f7a21996000 rw-p 00000000 00:00 0

You can see the new VMA created by mmap. Its size is one single page (0x1000 in hex is 4096), it has all permissions (rwx), and everything else is zero, which is in line with anonymous, private VMAs. We’ll see what this means a little bit later, but in a nutshell, it means that the memory block is not backed up by a file—that’s what anonymous means—and any change to the memory cannot be seen by other processes—that’s what private means.

Pressing Enter again will run the shell code and unmap it afterwards. As there is only one single reference to that VMA, it can be destroyed and the associated pages freed. You can dump the memory map again and check that the VMA is gone.

Now, you can get back to the examples in previous chapters where we run mprotect to change permissions, read old code, copy new code, execute it, and restore it, and change those examples using mmap instead of mprotect (note that mmap allows us to specify the permissions so we don’t need to call mprotect in many cases), copy data over to the new allocated memory, run it, and finally execute munmap to delete the memory and leave no hint behind. That will be a nice exercise and a much more clean solution to the non-destructive code injection.

Memory Mapping Manipulations

We’ve just seen how the mmaped memory allocated by our previous example flashes out in the process memory map, especially when all the permissions, read, write, and execution are all set and no backing file is associated with that module, which is the nominal case for regular code. On the other hand, it’s easy to have a file backing up a memory block; however, if we’re talking about, for example, malware or some anti-cheat system, the creators of the software will prefer not to leave any file behind, because it may provide useful information to security researchers analyzing it. So, what can you do?

A common technique used to hide injected code in programs is known as memory mapping manipulation, in-memory code modification, or module stomping—even though this last term is more common in the Windows realm. The technique is very simple: instead of allocating a brand-new and flashy memory block, the attacker just overwrites an existing or legitimate system module, usually a library. The library may already exist (think, for instance, of the LibC library we’ve just seen), or may be loaded specifically for that purpose. This same (or at least similar from the implementation point of view) technique can be used to inject code in running programs as we’ve done in previous chapters, but instead of using mmap to allocate memory to store the injected code, an existing memory block associated to a library is used instead.

Let’s show how to use this technique by loading our own library first. This makes the code a bit shorter because we’ll know where the library gets loaded from our program without checking the process memory map. The standard way to load and use a shared library is using the dlopen/dlsym functions. The technique is very simple:

  • Load some library
  • Find a function in the library
  • Change permissions of the page containing that function
  • Inject your code there
  • Restore permissions
  • Call the function normally

Let’s see how this steps looks like in a program:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <dlfcn.h>

#include <sys/mman.h>
#include <gnu/lib-names.h>

#define DIE(s) {perror(s); exit(1);}

unsigned char hello_bin[] = {
  0xb8, 0x01, 0x00, 0x00, 0x00, 0xbf, 0x01, 0x00, 0x00, 0x00, 0x48, 0x8d,
  0x35, 0x13, 0x00, 0x00, 0x00, 0xba, 0x0e, 0x00, 0x00, 0x00, 0x0f, 0x05,
  0xb8, 0x3c, 0x00, 0x00, 0x00, 0xbf, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x00,
  0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64,
  0x21, 0x0a
};
unsigned int hello_bin_len = 50;

int main (int argc, char *argv[]) {
  void   *h;
  int    (*cos)();
  pid_t  pid;
  int    pagesize = sysconf (_SC_PAGESIZE);

  printf ("PID: %ld\n", (pid = getpid()));
  h = dlopen (LIBM_SO, RTLD_LAZY);
  cos = dlsym (h, "cos");
  getchar();
  mprotect ((void*)((uint64_t)cos & ~(pagesize - 1)), pagesize, PROT_WRITE | PROT_READ);
  memcpy (cos, hello_bin, hello_bin_len);
  mprotect ((void*)((uint64_t)cos & ~(pagesize - 1)), pagesize, PROT_EXEC | PROT_READ);
  getchar  ();
  cos ();
  dlclose (h);
  return 0;
}

TECHNIQUE: Memory Mapping Manipulation with Shared Libraries

Code injection/Diversion/Memory Mapping Manipulation

Load a standard library, locate a function on it, change permissions of the page holding that function, and inject your code there. Then, restore the permissions and just run the substituted function normally.

We’re reusing our Hello, world! shellcode with a ret instead of an exit once again. Note the use of gnu/lib-names.h that defines the names for the main standard libraries. They’re just strings, so you can just use the library name, but this is the recommended way to use standard libraries as per the dlopen man page example. The program opens the library using dlopen and gets the address of a function. I just chose cos (the mathematical cosine function) in this example, but we could choose anything. Then, we write the shellcode at that address after changing the permissions.

Note that I called mprotect only activating read and write permissions so they will work even if W^X protection is activated. Also note that I restore the permissions to the correct ones so the memory map looks OK after the modification. Finally, note how I get the base address of the page containing the cos function, which we need to call mprotect. See the box “Memory Pages and Page Alignment” at the beginning of the chapter for details.

I added a getchar call before calling the cos function so you can print the memory map of the process from a different console and check that there is no strange memory mapping with executable permissions.

However, if you dump the memory map after and before the call to mprotect, you will see something like this:

$ cat /proc/2829463/maps | grep xp
55a305d3f000-55a305d40000 r-xp 00001000 fd:01 49676483   /opt/syscalls/mmap/mmap-manip01
7fdeef02f000-7fdeef0ac000 r-xp 00011000 fd:01 50080082   /usr/lib/x86_64-linux-gnu/libm.so.6
7fdeef139000-7fdeef29c000 r-xp 00028000 fd:01 50080079   /usr/lib/x86_64-linux-gnu/libc.so.6
7fdeef329000-7fdeef32b000 r-xp 00000000 00:00 0          [vdso]
7fdeef32c000-7fdeef354000 r-xp 00001000 fd:01 50080073   /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2

After pressing Enter again to run mprotect, you’ll see:

$ cat /proc/2829463/maps | grep xp
55a305d3f000-55a305d40000 r-xp 00001000 fd:01 49676483   /opt/syscalls/mmap/mmap-manip01
7fdeef02f000-7fdeef09f000 r-xp 00011000 fd:01 50080082   /usr/lib/x86_64-linux-gnu/libm.so.6
7fdeef09f000-7fdeef0a0000 r-xp 00081000 fd:01 50080082   /usr/lib/x86_64-linux-gnu/libm.so.6
7fdeef0a0000-7fdeef0ac000 r-xp 00082000 fd:01 50080082   /usr/lib/x86_64-linux-gnu/libm.so.6
7fdeef139000-7fdeef29c000 r-xp 00028000 fd:01 50080079   /usr/lib/x86_64-linux-gnu/libc.so.6
7fdeef329000-7fdeef32b000 r-xp 00000000 00:00 0          [vdso]
7fdeef32c000-7fdeef354000 r-xp 00001000 fd:01 50080073   /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2

What is happening is that the kernel is splitting the VMA containing the cos function, because we’re changing the permissions for only one page. The cos function in my previous example was located at 0x7fdeef09ff50, somewhere in the middle of the first VMA associated to the libm. However, that first VMA of the library extends through quite some pages, from 0x2f000 to 0xac000. Taking into account that each page is 0x1000, that memory range takes 125 pages. When we modify the cos page, which is located at 0x7fdeef09f000 (getting rid of the ASLR base address), that page is somehow in the middle of the VMA. In this case, the kernel splits the VMA into three parts: the initial part of the VMA remains the same, the page in between gets its own VMA because we have changed permissions, and the rest of pages after the modified page also remains the same. We’ll use this behavior later in the chapter to manipulate the process memory map. Let’s look at the addresses of the second dump of the memory map:

7fdeef02f000-7fdeef09f000 <- Initial pages before the page containing the cos function
7fdeef09f000-7fdeef0a0000 <- 1 single page that contains the cos function
7fdeef0a0000-7fdeef0ac000 <- remaining pages in the original VMA

Even when this is likely to be overlooked by an administrator or an automatic tool, we can just change the permission of the whole VMA all together to avoid any split. This has the additional advantage of avoiding page boundaries artifacts. Look at the previous example, the cos function is at offset 0xf50 inside its page. We change the page permission but we can only insert:

0xfff - 0xf50 = 0xaf = 175 bytes

In our case, that’s more than enough to store our Hello, world! payload, but for a bigger payload or in case the chosen target function is closer to the end of the page, we may not have enough space and a segmentation fault will happen when we write in the next page that hasn’t write permissions. If we change the whole VMA, we’ll have all the existing space to inject as much code as we want.

Mapping Manipulations Issues

So, let’s change the program to use the whole VMA instead of just one single page:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <dlfcn.h>

#include <sys/mman.h>
#include <gnu/lib-names.h>

#define DIE(s) {perror(s); exit(1);}

unsigned char hello_bin[] = {
  0xb8, 0x01, 0x00, 0x00, 0x00, 0xbf, 0x01, 0x00, 0x00, 0x00, 0x48, 0x8d,
  0x35, 0x13, 0x00, 0x00, 0x00, 0xba, 0x0e, 0x00, 0x00, 0x00, 0x0f, 0x05,
  0xb8, 0x3c, 0x00, 0x00, 0x00, 0xbf, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x00,
  0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64,
  0x21, 0x0a
};
unsigned int hello_bin_len = 50;

int main (int argc, char *argv[]) {
  void   *h;
  int    (*cos)();
  pid_t  pid;
  uint64_t start, end;

  printf ("PID: %ld\n", (pid = getpid()));
  h = dlopen (LIBM_SO, RTLD_LAZY);
  cos = dlsym (h, "cos");
  printf ("cos: %p\n", cos);
  getchar ();
  
  FILE *f = fopen ("/proc/self/maps", "rt");
  while (!feof (f)) {
    char buf[1024];
    fgets (buf, 1024, f);
    if (strstr (buf, LIBM_SO) && strstr (buf, "r-xp")) {
      sscanf (buf, "%lx-%lx", &start, &end);
      if ((void*)cos > (void*) start && (void*)cos < (void*)end) break;
    }
  }
  fclose (f);
  
  printf ("Found segment at: %lx %lx\n", start, end);
  getchar ();
  mprotect ((void*)start, end - start, PROT_WRITE | PROT_READ);
  memcpy (cos, hello_bin, hello_bin_len);
  mprotect ((void*)start, end - start, PROT_EXEC | PROT_READ);
  getchar  ();
  cos ();
  dlclose (h);
  return 0;
}

TECHNIQUE: Memory Mapping Manipulation with Shared Libraries

Code injection/Camouflage/Deception

Load a standard library and choose an existing function. Change permissions of the whole executable VMA to overwrite the function with your shell code, restore permissions optionally, and call the substituted function to execute the shell code. This way, no new VMAs will be created.

Now we have a piece of code in the middle of the program that opens the map file and looks for the libm.so VMA with execution permissions, which will contain the cos function. Once found, it passes those values to mprotect and proceeds as in the previous example.

Note that our simple program already has libc and libld-linux mapped, so a variation of this technique is to choose a function from one of those libraries instead of loading an additional library. The code is the same; we just need to find our target function in a different VMA. The following code uses libc and system to do exactly the same thing:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <dlfcn.h>

#include <sys/mman.h>
#include <gnu/lib-names.h>

#define DIE(s) {perror(s); exit(1);}

unsigned char hello_bin[] = {
  0xb8, 0x01, 0x00, 0x00, 0x00, 0xbf, 0x01, 0x00, 0x00, 0x00, 0x48, 0x8d,
  0x35, 0x13, 0x00, 0x00, 0x00, 0xba, 0x0e, 0x00, 0x00, 0x00, 0x0f, 0x05,
  0xb8, 0x3c, 0x00, 0x00, 0x00, 0xbf, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x00,
  0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64,
  0x21, 0x0a
};
unsigned int hello_bin_len = 50;

int main (int argc, char *argv[]) {
  int    (*sys)();
  pid_t  pid;
  uint64_t start, end;

  printf ("PID: %ld\n", (pid = getpid()));
  sys = system;
  printf ("system: %p\n", sys);
  
  getchar ();
  
  FILE *f = fopen ("/proc/self/maps", "rt");
  while (!feof (f)) {
    char buf[1024];
    fgets (buf, 1024, f);
    if (strstr (buf, LIBC_SO) && strstr (buf, "r-xp")) {
      sscanf (buf, "%lx-%lx", &start, &end);
      if ((void*)system > (void*) start && (void*)system < (void*)end) break;
    }
  }
  fclose (f);
  printf ("Found segment at: %lx %lx\n", start, end);
  getchar ();
  if (mprotect ((void*)start, end - start, PROT_WRITE | PROT_READ) < 0) perror ("mprotect:");
  memcpy (sys, hello_bin, hello_bin_len);
  if (mprotect ((void*)start, end - start, PROT_EXEC | PROT_READ) < 0) perror ("mprotect:");
  getchar  ();
  sys ();
  return 0;
}

TECHNIQUE: Memory Mapping Manipulation using the Standard C Library

Code injection/Camouflage/Deception

Use the already available C library in the program and choose an existing function. Change permissions to overwrite the function with your shell code, restore permissions optionally, and call the substituted function to execute the shell code. Make sure to choose an unused function that is not in the same page than mprotect.

Now we’re skipping the loading of the extra library, as well as the target symbol resolution. LibC symbols are already available in our program, and we can just use them. However, if you compile and run this program as it is, it’ll crash, and the reason for that is pretty cool. Can you figure it out?

It took me a while, as it was very confusing, to get a segmentation fault when running a syscall. The problem was that the mprotect wrapper in LibC was in the same VMA as system. So, when we set the permissions to READ/WRITE, removing the execution permission, we no longer can run any function on that VMA, which includes mprotect. This was pretty curious because the segmentation fault doesn’t happen when calling mprotect. Remember, that mprotect is just a wrapper, so the function starts execution, gets things ready to do the syscall, runs the actual syscall ASM instruction, and when it just returns and tries to run the next instruction after syscall, that memory address doesn’t have execution permission anymore, and the program segfaults.

So, in order to make the previous example work, we need to keep the executable permission, which may not be possible if the W^X protection is activated. If that is the case, we either choose to load our own target library, we try to use ld-linux (be careful with dynamic symbol resolution), or use some small code which will require to temporarily allocate an anonymous memory block. We’ll talk about this last solution in the next section.

Before finishing this section, let’s introduce a couple more variations that may be useful in some cases.

The first one is that we don’t really have to overwrite a real function. We can feed our code anywhere in the mapped library; however, using an existing function is a cleaner way of doing it, especially if you just inject the code at the very beginning of the mapped library where the ELF header is. That will destroy the header and may be considered suspicious for some monitoring tools.

Another thing to take into account is what happens when this is done from a remote process using, for example, ptrace. In that case, the stack of the process while running the payload will be a bit suspicious because we are jumping into the library function from some weird place… usually somewhere deep inside LibC, which makes no sense. Why would the read syscall call from a fgets LibC function call the cos function on libm? In those cases, we can just fake a stack frame that makes sense or go for a more sophisticated solution in which we patch a function and wait for the process to execute it. Depending on if we want to break the original program or not (see Chapter 2), we may have to store the original code of the function, which is not that bad because having a mapped memory block with read/write permissions is not that suspicious, and we can easily just allocate memory to store it and restore it afterwards.

These kinds of operations (non-destructive ones) that try to keep the code hidden under an existing library may become tricky because, in order to restore the code in the original function, we need to run code to restore it, but the code we’ve injected and running is in the same memory addresses than the one we want restored. This may sound a bit confusing until you try to do it yourself, but hopefully will be more clear after reading the next section. In those cases, you can rely on an external program that will use ptrace again to restore the code or use some small piece of code somewhere else to do that. Let’s explore this last option in the next section, as we already know everything about ptrace ;)

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

Peek and Poke on Steroids process_vm_readv/writev. Part 5

The Lost Book of the Forbidden Syscalls. Chapter 5 - Credentials Stealing and Final Project

Read

SYSCALL LINUX PROCESS_VM_READV PROCESS_VM_WRITEV PROGRAMMING LINUX CODE INJECTION

Return to Home Page