Writing binaries in Assembly language
- Distro: Debian 13
- Architecture: x86_64
- Sintax: Intel
- Commands/Tools used: nasm, ld, gcc, man, cat, auditd, xxd, file
Welcome, my dear hackers, to a new post in which I'll talk about how to write our first program in Assembly language. After some time of learning about this programming language, seeing it in CTFs, payloads, applications (while I was reverse engineering), and in dumps in hex format, I thought it would be a good idea for every self-respecting hacker to learn how to write in Assembly so that they can make their own shellcodes, for example, to be able to exploit vulnerabilities such as "Buffer Overflow".
Learning assembly language is not a complicated task. You just need to know what registers, mnemonics (assembly language instructions such as "mov" or "inc"), and sections are for. There are more important elements when programming in assembly, such as flags, it is a more advanced concept that I will not cover in this post.
Segments / Sections of memory
I already explained the memory sections in the post "Segmentación de memoria - Hacking: The Art Of Exploitation", so I will explain it well above so that the essential on this topic is understood for those who have not read the previous post.
- .data: Contains initialized variables.
- .bss: Contains non-initialized variables
- .text: Contains the assembly code the CPU will execute.
Comments
In Assembly (and any other programming language) it is a good practice to insert comments in the code that explain what each piece of written code does, in order to make it more readable and understandable for the developer. Commanders can be used in assembly using the symbol ;. Below I will leave an example of this.
- The symbol
;is used to write a single-line comment.
; Increments the value of "rax" by 1
inc raxIf I wanted to put multiple lines of comments, we'd use multiple times ; as shown below.
; Increments the value of "rax" by 1
; Then it decrements the value of "rax" by 1
inc rax
dec raxRegisters
Registers are the smallest and fastest storage units that exist in the CPU. They are commonly used in assembly to store data that will be used in the assembly code to perform operations with them. Seen in this way, they are similar to variables in a high-level programming language, although these registers are limited, unlike variables that can be created as many as desired in languages such as C or Python. I explained the registers in the post "Apuntes de lenguaje ensamblador (Assembly)", although I recommend reading this post that I just mentioned, I will leave here the same brief explanation that I used in the previous post for those who do not want to read it.
rax -> Accumulator (general arithmetic)
rbx -> Base register (general purpose)
rcx -> Counter (used in loops and shifts)
rdx -> Data, for in/out or multiplication/division
rsi -> Source index (copy strings of characters/memory, used along with "edi")
rdi -> Destination index (general purpose)
rsp -> Stack pointer (superior limit of the stack)
rbp -> Base pointer (stack frame reference)
rip -> Instruction pointer (Tells the CPU what to execute. It's a pointer to the next instruction that will be executed. Very important for hacking purposes)
r8 -> General purpose (Used in arguments of functions)
r9 -> General purpose (Used in arguments of functions)
r10 -> General purpose (Volatile register)
r11 -> General purpose (Volatile register)
r12 -> General purpose (Non-volatile register that holds data across functions)
r13 -> General purpose (Non-volatile register that holds data across functions)
r14 -> General purpose (Non-volatile register that holds data across functions)
r15 -> General purpose (Non-volatile register that holds data across functions)However, this definition does not apply when we talk about syscalls (system calls).
Registers applied to shellcodes
Registers have different roles depending on the context in which they are used. In the case of syscalls, each register has a specific role which is explained below.
rax -> Function/Syscall to execute (after the execution, it will hold the result)
rdi -> First argument
rsi -> Second argument
rdx -> Third argument
r10 -> Fourth argument
r8 -> Fifth argument
r9 -> Sixth argumentWhen you want to perform a syscall, you must specify in each register which and with which arguments to execute. This is explained below.
Syscalls
Syscalls or "system calls" are interfaces between the application and the kernel that allow the application to perform certain actions on the system that it otherwise couldn't. We can think of this in a similar way to executing functions in an application like C. Functions (sometimes) require arguments in order to execute, and syscalls also require these same arguments. For example, if you wanted to save information to a file, you would have to call the function, and specify in the Arguments, for example, what information I want to save and in which file. To call a function in C we would require a line like this:
execve("/bin/sh", NULL, NULL)In this case, "execve" would be the function to execute while "/bin/sh", "NULL" and "NULL" are the arguments that are passed to the function. We can see more information about this function using the command "man execve".
NAME
execve - execute program
LIBRARY
Standard C library (libc, -lc)
SYNOPSIS
#include <unistd.h>
int execve(const char *pathname, char *const _Nullable argv[],
char *const _Nullable envp[]);
DESCRIPTION
...It's possible to find more information about syscalls in GNU/Linux using the command man syscalls
While in "C" you need to specify its name in "C", in "Assembly" you need to specify its number. Each syscall has an identifying number to refer to it, so in assembly you don't call syscalls through numbers that identify them. We can see which number refers to each syscall by using the ausyscall command (which can be used by installing the audited package) as follows.
❱❱ ausyscall --dump
Using x86_64 syscall table:
0 read
1 write
2 open
3 close
4 stat
5 fstat
6 lstat
...Or you can take a look at the file /usr/include/x86_64-linux-gnu/asm/unistd_64.h.
❱❱ cat /usr/include/x86_64-linux-gnu/asm/unistd_64.h
#ifndef _ASM_UNISTD_64_H
#define _ASM_UNISTD_64_H
#define __NR_read 0
#define __NR_write 1
#define __NR_open 2
#define __NR_close 3
#define __NR_stat 4
...
#define __NR_execve 59
#define __NR_exit 60
...As we can see, the number that "execve" refers to is 59, so in order to execute the syscall, we have to make the rax register contain the number 59. On its own, if we specify that we want to execute the "execve" function with a syscall, we are going to cause an error, since it is mandatory that we specify what information its other three parameters will contain.
Parameters in syscalls
In case we want to replicate the line we saw earlier by calling the function (execve("/bin/sh", NULL, NULL)), we should specify in the first argument the string of characters "/bin/sh", and in the second and third arguments a string of characters that only has one null character.
But what is a null character? A Null Character or Null Pointer (depending on the context, it's the same thing), would be the hexadecimal equivalent of 0x0, which being an "empty" value (i.e., containing no information), is considered null. We can clean up the values contained in the records in different ways. One of the ways to put a null character in a record would be with the statement:
mov rax, 0However, a slightly more correct way would be to perform an xor operation on the registry as described below.
xor rax, raxXOR operations convert equal values to 0, so if we specify that we want to do an xor operation when the two entries are the same record, the entire record is deleted and remains at 0.
And now, how can we specify that we want the string in the first argument to be "/bin/sh"? Simple, we just have to convert this string of characters to hexadecimal. To do this, we can use the xxd and printf commands as follows.
❱❱ printf "/bin/sh" | xxd -ps
2f62696e2f7368Why do we use printf? Well, because this command is similar to echo, but it doesn't add the New-Line byte, so it doesn't add extra bytes. Here's what I mean:
❱❱ printf "/bin/sh" | xxd
00000000: 2f62 696e 2f73 68 /bin/sh
❱❱ echo "/bin/sh" | xxd
00000000: 2f62 696e 2f73 680a /bin/sh.Using echo, we can see that the byte 0x0a is added, which is what makes the line break. Since we only want the /bin/sh string, we will use printf for this task. Now that we have the string of characters we want transformed into hexadecimal, add a 0x in front of it to indicate to our program written in Assembly that we are going to use a set of bytes to represent the string. It would look like this.
0x2f62696e2f7368Once we have the string of characters and the values we want to set in the other two arguments (in this case they are 0, because we don't want to specify any value as an argument, that is, we want them to be null), we must start programming our binary.
Structure of the syntax of "nasm"
Depending on the assembler we choose, we will have to use one type of syntax when writing our code or another. Assemblers are responsible for transforming a file full of assembly code into a binary file with assembly code at the binary level, that is, as the name suggests, it "assembles" the code we have written to create a functional program. In my case, I chose "nasm" as an assembler because of the ease of its syntax, its ability to assemble binaries at a multi-platform level, and above all, the exaggerated amount of documentation it offers.
To be able to create binaries in assembly, it is not enough just to put the code. We need to specify the sections and the functions that the binary will have. This can be done with the section and global keywords.
section: Specifies which section to create and what information that section will save.global: A directive that allows the function declared with this same directive to be accessible from other files (i.e., it is a directive that allows the function to be exported from an.asmfile to other.asmfiles).
When we want to declare a function, we must include it in the .text section, just as the initialized variables would go in the .data section and the uninitialized variables would go in the .bss section. Here is an example of how to create a function in nasm.
section .text
global _start
_start:
<código_ensamblador>The section .text key line indicates that what comes next will be saved in the .text section. In this case, what will be saved will be the assembly code of the _start function. The global directive doesn't need to be put in the context of this guide, but I consider it a good practice to get used to using directives for when you want to create a larger code involving multiple files. For the purpose of this post, we could store the string we saw earlier (/bin/sh) in a variable to avoid having to translate it to hexadecimal and let nasm do the hard work. We could do this by adding the following lines to the code:
section .data
string db "/bin/sh"What I would do is create a variable called string that contains /bin/sh. This has many benefits, but since in the future I want to teach how to write shellcode in assembler (and when creating shellcode we can't use variables), I prefer to skip this point.
Programming in Assembly
Finally, we can get our hands dirty by writing a very simple code in assembler. What I'll do is create a simple program called create_shell that all it does is create a shell. To do this, we'll have to use two syscalls, execve's to be able to execute the shell, and exit to stop the program from running gracefully. To execute execve's syscall, we'll need the following instructions.
mov rbx, 0x68732f6e69622f
push rbx
push rsp
pop rdi
xor rsi, rsi
xor rdx, rdx
mov al, 59
syscallBelow I leave the operations carried out by the following lines.
mov rbx, 0x68732f6e69622f: We insert the string/bin/shin the registerrbx.push rbx: We insert the string into the stack to use it in the next instructions.push rsp: We insert the memory address containing the string/bin/shinto the stack.pop rdi: We take the memory address containing the desired string out of the stack and save that address in therdiregister to use as the first argument in the syscall.xor rsi, rsi: We convert the value (any it may have) of thersirecord to 0. This will be the second argument.xor rdx, rdx: We convert the value (any it may have) of thersirecord to 0. This will be the third argument.mov al, 59: We pass the number59to the first byte of theraxregister. This is the code of theexecvesyscall that will make it so that when we execute thesyscallinstruction, the shell will be executed.
Once we have the shell, we have already fulfilled the purpose of the program. Now, we want to exit it. To do this, we must execute the syscall exit using the following instructions.
mov al, 60
xor rdi, rdi
syscallmov al, 60: We make the syscall code that we are going to execute60, which belongs to the syscallexit.xor rdi, rdi: The second parameter specifies the output code of the program. Since I want it to be0, I remove the value that therdiregister had previously (which was/bin/sh) and leave it empty (i.e. with the value0).syscall: The syscall is executed and the program ends with an exit code of0.
The full code of the program would be as follows.
section .text
global _start
_start:
mov rbx, 0x68732f6e69622f
push rbx
push rsp
pop rdi
xor rsi, rsi
xor rdx, rdx
mov al, 59
syscall
mov al, 60
xor rdi, rdi
syscallCompiling the binary
To compile the binary, we will use nasm (the assembler we talked about before), and ld, which is a linker, specifically the GNU linker. A linker has the purpose of linking the symbol references and relocating the data contained in the generated object file/s (they can be one or more depending on the complexity and needs of the binary) by nasm to create an executable binary. That is, it is in charge of linking (for example) functions of one or more .asm files converted into object files (.o) in order to generate the executable file (the final ELF file).
To be able to assemble the .asm file into an object file in ELF format, we must use the following command.
nasm -f elf64 <fichero.asm> -o <fichero.o>Considering that the file containing the assembly code is called create_shell.asm, the command would be as follows.
❱❱ nasm -f elf64 create_shell.asm -o create_shell.oAnd once we have the object file (.o), we must link it to obtain the executable binary as follows.
ld <fichero_objeto.o> -o <ejecutable>Y finalmente, este sería el resultado.
❱❱ nasm -f elf64 create_shell.o -o create_shellExecuting the binary
Once we have the binary, we can verify that it is indeed an ELF 64 file using the file command.
❱❱ file ./create_shell
./create_shell: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not strippedAnd finally, we can try running the binary to verify that it does indeed create an interactive shell thanks to the syscall execve.
❱❱ ./create_shell
$ whoami
usuario
$ References






