## Shellcode

* [linux syscalls](https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/) Are used to craft the shellcode in assembly language
* [asmtutor.com](https://asmtutor.com) to check the assembly

## Staged and Unstaged Payloads

* An unstaged payload is directly embedded in a binary and executes as is. This may be used to start malicious payload which does not need a remote connection or nearly none.
* A small stub of the staged payload is embedded in the binary and should load additional instructions from remote which build the final reverse shell. The downloaded part will only reside in memory. The downloaded shellcode can be changed

## Writing Shellcode Manually

* Executing the shellcode relies on syscalls of the system

* A 32 bit version looks like this
```assembly
SECTION .data
msg     db      'Hello World!', 0Ah
 
SECTION .text
global  _start
 
_start:
 
    mov     edx, 13
    mov     ecx, msg
    mov     ebx, 1
    mov     eax, 4
    int     80h
 
    mov     ebx, 0      ; return 0 status on exit - 'No Errors'
    mov     eax, 1      ; invoke SYS_EXIT (kernel opcode 1)
    int     80h
```

* A 64 bit version looks like this 
```assembly
global _start

section .text
_start:
    jmp MESSAGE      

OUTPUT:
    mov rax, 0x1
    mov rdi, 0x1
    pop rsi          

    mov rdx, 0xd
    syscall

    mov rax, 0x3c
    mov rdi, 0x0
    syscall

MESSAGE:
    call OUTPUT       
    db "Hello, world!", 0dh, 0ah
```

### Compilation

* Compile and link 32 bit
```sh
nasm -f elf helloworld.asm
ld -m elf_i386 helloworld.o -o helloworld
```

* Compile and link 64 bit
```sh
nasm -f elf64 helloworld.asm
ld helloworld.o -o helloworld
```

### Dump the binary

* Dump the binary with `objdump -d helloworld` and take a look at the text section
* Dump the text section into a file via
```sh
objcopy -j .text -O binary helloworld helloworld.text
```

### Format the Shellcode

* Format and test the code by dumping it into a c file
```
xxd -i helloworld.text > helloworld.c
sed -i '1s/^/#include<stdio.h>\n\n/' helloworld.c
echo -e "\n\t(*(void(*)())helloworld_text)();\n\treturn 0;\n}" >> helloworld.c
```

* Compile the c file with an exectuable stack
```sh
gcc -z execstack -g -o helloworld helloworld.c
```

## Automated Shellcode Generation

* Automate the creation via msfvenom
* Staged payloads look like this
```sh
msfvenom -p linux/x64/meterpreter/reverse_tcp
```
* Stageless payloads look like this
```sh
msfvenom -p linux/x64/meterpreter/reverse_tcp
```