Thursday, January 29, 2009

ASM - From the beginning

This outline is FreeBSD specific ( 64 bit ). The code will more than likely work on Linux but the syscalls will be different - refer to syscall.h for further details.


Here is the first chunk of code. Essentially all it does is writes "Hello" to screen followed by a new line character.


.data

string: .asciz "Hello\n" # the string
len= . - string - 1 # the length of the string

.text
.global _start # where the application 'begins'


_start:

#The following is a call to 'write' which is syscall 4 ( refer to syscall.h)
# write(int d, const void *buf, size_t nbytes)

movq $len,%rdx # length of string ( arg 3 )
movq $string,%rsi # string (arg 2 )
movq $1,%rdi # descriptor ( arg 1 )
movq $4,%rax # use the write syscall
syscall # call the kernel

# call syscall 1 ( exit ) to exit application
movq $1, %rax # exit syscall
syscall # call the kernel




Starting from the top we do the following
- create a variable called string in the 'data' section and assign it 'Hello\n'
- create a variable 'len' to hold the length of the string
- put the length of the string into the rdx register
- put the string into the rsi register
- put the file descriptor into the rdi register
- put the 'write' syscall ( 4 ) in the rax register
- call the kernel
- move the 'exit' syscall ( 1 ) into the rax register
- call the kernel


Things you should know about this code :
- rdi, rsi and rdx registers are used to hold the first, second and third variables of a function call respectively
- rax register is read by syscall which tells it which syscall to use


Compiling asm code:
I use 'as' and 'ld' to compile and link assembly code. You can use GCC if you like

# as sourcecode.s -o object_file.o
# ld object_file.o -o application_file

Some fun 'debugging':

If you want to debug your code, you can use a mix of 'gdb' and 'objdump'.
objdump will become very handy if you wish to start developing shellcode so it's a good idea to be able to read the output.


# objdump -Ds puts

puts: file format elf64-x86-64

Contents of section .text:
4000b0 4831d248 c7c20600 000048c7 c6e00050 H1.H......H....P
4000c0 0048c7c7 01000000 48c7c004 0000000f .H......H.......
4000d0 0548c7c0 01000000 0f05 .H........
Contents of section .data:
5000e0 48656c6c 6f0a00 Hello..
Disassembly of section .text:

00000000004000b0 <_start>:
4000b0: 48 31 d2 xor %rdx,%rdx
4000b3: 48 c7 c2 06 00 00 00 mov $0x6,%rdx
4000ba: 48 c7 c6 e0 00 50 00 mov $0x5000e0,%rsi
4000c1: 48 c7 c7 01 00 00 00 mov $0x1,%rdi
4000c8: 48 c7 c0 04 00 00 00 mov $0x4,%rax
4000cf: 0f 05 syscall
4000d1: 48 c7 c0 01 00 00 00 mov $0x1,%rax
4000d8: 0f 05 syscall
Disassembly of section .data:

00000000005000e0 :
5000e0: 48 rex64
5000e1: 65 gs
5000e2: 6c insb (%dx),%es:(%edi)
5000e3: 6c insb (%dx),%es:(%edi)
5000e4: 6f outsl %ds:(%esi),(%dx)
5000e5: 0a 00 or (%rax),%al

No comments: