Author: Cole Ellis (@heavycircle)
Minimizing ELF Binaries
Using Assembly to write ultra-small binaries used for ELF shellcoding.
This post was inspired in a shellcoding challenge where I had to send the remote host an ELF and it would execute it. However, the binary could be no larger than 1000 bytes. What ELF is that small?
Turns out, you can write some small binaries. Like, really small. Check out this example of a classic reverse shell payload:
minelf rev.asmINFO Log Level: INFOINFO Compiling "rev.asm" into "rev"INFO Architecture detected: 32 bitsINFO Compiled ELF written to "rev"INFO Total Size: 165 bytes.It compiles to only 165 bytes for the entire binary! How is this possible?
Introduction to ELFs
To understand how this works, we must understand the layout of an ELF file. This is how the runtime reads the ELF file and knows how to execute it.
TL;DR - This Wikipedia Page has the entire ELF file layout including many of the possible options for each section.
The ELF Header
The ELF header indicates firstly that it's an ELF file, and then tells the architecture, word size, object file type, etc. This is what file parses to understand the specifics of the binary. The format of the ELF header is:
1typedef struct
2{
3 unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */
4 Elf32_Half e_type; /* Object file type */
5 Elf32_Half e_machine; /* Architecture */
6 Elf32_Word e_version; /* Object file version */
7 Elf32_Addr e_entry; /* Entry point virtual address */
8 Elf32_Off e_phoff; /* Program header table file offset */
9 Elf32_Off e_shoff; /* Section header table file offset */
10 Elf32_Word e_flags; /* Processor-specific flags */
11 Elf32_Half e_ehsize; /* ELF header size in bytes */
12 Elf32_Half e_phentsize; /* Program header table entry size */
13 Elf32_Half e_phnum; /* Program header table entry count */
14 Elf32_Half e_shentsize; /* Section header table entry size */
15 Elf32_Half e_shnum; /* Section header table entry count */
16 Elf32_Half e_shstrndx; /* Section header string table index */
17} Elf32_Ehdr;Elf64_Ehdr, the 64-bit ELF header. You can find both of these in /usr/include/elf.h.This is a requirement for the ELF file. Fortunately, its size doesn't change -- 52 bytes for 32-bit and 64 bytes for 64-bit. Most of these values have defaults that we can just fill in.
ELF Program Header
The ELF Program Header tells the system how to process a segment of memory. This is most commonly used to determine the permissions for that segment and where to load it in virtual memory. This also has a pre-defined format:
1typedef struct
2{
3 Elf32_Word p_type; /* Segment type */
4 Elf32_Off p_offset; /* Segment file offset */
5 Elf32_Addr p_vaddr; /* Segment virtual address */
6 Elf32_Addr p_paddr; /* Segment physical address */
7 Elf32_Word p_filesz; /* Segment size in file */
8 Elf32_Word p_memsz; /* Segment size in memory */
9 Elf32_Word p_flags; /* Segment flags */
10 Elf32_Word p_align; /* Segment alignment */
11} Elf32_Phdr;Understanding program headers is the key to minimizing the binary. By default, gcc defines many segments with different permissions to ensure that non-writable data isn't allowed to be written. This includes distinguishing the .text and .data segments. .text is meant to be R-X while .data should be RW-.
Then, gcc makes the decision to align these sections with p_align = 0x1000. This means that gcc can simply set permissions on the page itself without having to set memory permissions on smaller segments. This is a speed optimization at the cost of size -- 0x1000 is equal to 4 kilobytes. This is clearly bigger than the size of our entire minelf binary!
Therefore, to best minimize this binary, we need to not only write condensed code, but remove padding like this to ensure that no bytes are unused.
ELF Section Header
The ELF Section header is the last segment. This gets placed after the sections (.text, .data, etc). It contains extra information for linking. It is also a pre-defined size:
1typedef struct
2{
3 Elf32_Word sh_name; /* Section name (string tbl index) */
4 Elf32_Word sh_type; /* Section type */
5 Elf32_Word sh_flags; /* Section flags */
6 Elf32_Addr sh_addr; /* Section virtual addr at execution */
7 Elf32_Off sh_offset; /* Section file offset */
8 Elf32_Word sh_size; /* Section size in bytes */
9 Elf32_Word sh_link; /* Link to another section */
10 Elf32_Word sh_info; /* Additional section information */
11 Elf32_Word sh_addralign; /* Section alignment */
12 Elf32_Word sh_entsize; /* Entry size if section holds table */
13} Elf32_Shdr;The important note here is that ELF Section Headers are not needed for execution. If we're writing our own ELF and want to minimize it, let's just remove this section altogether!
Making the Minimized ELF
The first thing we need is our instruction set. We can compile this into a hexdump using nasm:
nasm -f bin -o rev.bin rev.asmYour code doesn't need to be entirely position independent. You can use local references like functions and labels. When these compile, the jmp references are relative to the current location. call short functions are also relative. call long will not be relative, but we can handle this using the ORG directive. This directive allows us to define the intended address the binary gets loaded so it can place absolute values where required.
Now, we need to write the ELF header. Most of these values are standard. Let's assume we're compiling for a i386 (x86_32) system. We would make the ELF header:
1typedef struct
2{
3 unsigned char e_ident[EI_NIDENT] = {
4 0x1, // EI_CLASS, 32-bit
5 0x1, // EI_DATA, Little Endian
6 0x1, // EI_VERSION, Current Version
7 0x0, // EI_OSABI, System V
8 0x0, // EI_ABIVERSION, Current Version
9 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 // EI_PAD, Padding
10 }; // Identifiers
11 Elf32_Half e_type = 0x2; // ET_EXEC, Executable file
12 Elf32_Half e_machine = 0x3; // x86
13 Elf32_Word e_version = 0x1; // Current Version
14 Elf32_Addr e_entry = 0x8048054; // Address of first instruction
15 Elf32_Off e_phoff = 0x34; // Address of first program header
16 Elf32_Off e_shoff = 0x0; // None, there's no section header
17 Elf32_Word e_flags = 0x0; // No flags
18 Elf32_Half e_ehsize = 0x38; // Size of ELF header
19 Elf32_Half e_phentsize = 0x20; // Size of program header
20 Elf32_Half e_phnum = 0x1; // Number of program headers
21 Elf32_Half e_shentsize = 0x0; // None, no section headers
22 Elf32_Half e_shnum = 0x0; // None, no section headers
23 Elf32_Half e_shstrndx = 0x0; // None, no section headers
24} tmp_hdr;Most of these are default. We'll discuss e_entry's value once we discuss the program header below.
Let's define the single program header:
1typedef struct
2{
3 Elf32_Word p_type = 0x1; // PT_LOAD, loadable segment
4 Elf32_Off p_offset = 0x0; // Offset of the segment
5 Elf32_Addr p_vaddr = 0x8048000; // Virtual address of this segment
6 Elf32_Addr p_paddr = 0x8048000; // Physical address of this segment
7 Elf32_Word p_filesz = 0xa5; // Size of the file
8 Elf32_Word p_memsz = 0xa5; // Size of the segment
9 Elf32_Word p_flags = 0x7; // RWX (111)
10 Elf32_Word p_align = 0x0; // No Alignment
11} tmp_phdr;This program header is a PT_LOAD loading the entire file into memory. This requires two major things:
p_vaddr- Where this segment gets loaded. We mentioned this earlier when discussing position-independent code. This value must match whatever goes inORGto ensure position-dependent code gets executed properly.p_filesz- The size of the file. We can compute this manually. It's the total length of the ELF header, program header, and all instructions. Fortunately, we know all three of those:- The ELF header is
0x34bytes. - The Program header is
0x20bytes. - The instructions is the size of
rev.bin, which happens to be0x51.
- The ELF header is
Now that we have these, we can understand e_entry. e_entry represents the address of the first instruction. To ensure no padding, we put it right after the first program header. This will be at 0x8048000 (the starting address) + 0x34 (ELF Header) + 0x20 (Program Header) = 0x8048054. Once we add the hexdump generated by nasm -f bin, we have a full ELF! It'll start at 0x8048054 and execute all instructions.
Fortunately, this can all be made programmatically. This is what minelf does -- takes the original *.asm file, gets the hexdump, manually writes the ELF header and Program header, and sews it all together.
Making this Better
You'll notice that there are a few serious flaws with this, namely in the limit to what we can do.
1. Lack of a Data Segment
This first flaw is big. Not having a data segment is frustrating. This means that all strings must be passed onto the stack and cannot easily be used more than once. This not only becomes a functionality flaw, but a size flaw as well -- we would have to push the same string many times onto the stack to use it more than once.
We can fix that by defining the .data segment under the .text segment. That way, nasm -f bin will still be able to reference values there. It will also put no alignment between the segments. gcc will often align items within the data segment as well, but nasm will not do this.
2. What Gets Executed First
You won't notice this flaw until you use minelf more. The first thing that gets executed is the first line of assembly in the file. This is a flaw of nasm -f bin which simply converts instructions into binary. It doesn't put _start first (or even know what _start is). This means we must handle it ourselves.
This comes with its own set of challenges. nasm -f bin inherently strips binaries by simply converting instructions to binary. This means we can't simply find a _start and point e_entry there.
I have a few ideas for handling this:
- Run a preprocessor that moves
_startfirst and.textbefore.data. This seems like the easiest solution with one major roadblock:- We can't assume whitespace. However, no instructions have colons, meaning we could use this. Comments can have colons, so we'll need to be careful.
- Define a NASM macro and force users to put the macro before their main function. This allows users to easily rename their start function to anything.
- This requires more writing to disk than desirable... or it requires an extra file that we have to find/use. This isn't a horrible problem but I was hoping for more of a standalone binary.
I haven't tried implementing these yet. I'll keep updating the blog as I decide new things, but this is where I've stopped. You can find the implementation here; pull requests are welcome!
Thanks for reading! With love, heavycircle