January 01, 2019

How to make a shellcode using nasm and ld.

Write the following famous shellcode (23 Bytes) as a text file and save it as "mysh.s".
아래의 유명한 쉘코드(23 Bytes)를 텍스트 파일로 작성 후 "mysh.s" 이름으로 저장한다.

BITS 32
global _start

_start:
    xor eax, eax
    mov al, 11
    xor ecx, ecx
    xor edx, edx
    push ecx
    push 0x68732f2f
    push 0x6e69622f
    mov ebx, esp
    int 0x80

"int 80" is the assembly code that uses the system call to interrupt the CPU. On x86 architectures, put the number of the system call you want to call in eax, and on x64 architecture, in rax.

"int 80"은 CPU에 인터럽트를 걸어 시스템 콜을 사용하는 어셈블리 코드다. x86 아키텍처에서는 eax에, x64 아키텍처에서는 rax에 호출하고 싶은 시스템 콜의 번호를 넣으면 된다.

Functionx85x64arg 1arg 2arg 3
read30fdbufcount
write41fdbufcount
execve1159filenameargvenvp
dup26333oldnew
mprotect12510startlenprot

ArchitectureCodeNumberarg 1arg 2arg 3arg 4
x86int 0x80eaxebxecxedxesi
x64syscallraxrdirsirdir10


Enter the following command to make the shellcode executable file.
아래의 명령어를 입력하여 작성한 쉘코드를 컴파일한다.

# nasm -f elf32 ./mysh.s
# ld -m elf_i386 ./mysh.o

"nasm" is an assembler. It creates an object file(mysh.o).
"ld" is a linker. It makes an object file executable(a.out).

"nasm"은 어셈블러이며 오브젝프 파일을 생성한다(mysh.o).
"ld"는 링커이며 오브젝트 파일을 실행파일로 만든다(a.out).
* Linker and Loader[Link]

The supported architecture can be checked with the following command.
지원되는 아키텍처는 아래의 명령어로 확인할 수 있다.

# nasm -hf
# ld -mv 

The generated files have the following file formats.
생성된 파일들은 아래와 같은 파일 형식을 갖는다.

root@ubuntu:~/tmp/shellcode# file ./a.out ./mysh.o ./mysh.s
./a.out:   ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, not stripped
./mysh.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not stripped
./mysh.s: ASCII text

Now run the generated shellcode to test that it works.
이제 생성된 쉘 코드를 실행하여 잘 동작하는지 테스트한다.

root@ubuntu:~/tmp/shellcode# ./a.out
# id
uid=0(root) gid=0(root) groups=0(root)
# echo "Abc"
Abc
# uname -a
Linux ubuntu 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
#
# pwd
/root/tmp/shellcode
# echo $0

# bash
root@ubuntu:/root/tmp/shellcode# env | grep -i shlvl
SHLVL=1
root@ubuntu:/root/tmp/shellcode# exit
exit
# ps
   PID TTY          TIME CMD
  2118 pts/11   00:00:00 bash
  3466 pts/11   00:00:00 sh
  3483 pts/11   00:00:00 ps
# exit
root@ubuntu:~/tmp/shellcode#

It works well.
잘 동작한다.


Check environment  점검 환경
O   S Ubuntu 16.04(64 bits) CPU Intel i7
SHELL GNU bash (4.3.48) RAM 1 GB