Using Structures in NASM x64 Assembly

No replies
Erra
Erra's picture
Offline
Neophyte
Joined: 2014/05/01

There isn't a lot of examples out there on using structures in assembly, I'll preface this post by letting you know ahead of time that you should know x64 assembly. The reason you may want to do this is, for example you want to perform this operation in C (stripped from a port bind code):

        // Create sockaddr_in struct (man 7 ip)
        struct sockaddr_in host_addr;

        // AF_INET for IPv4
        host_addr.sin_family = AF_INET;
       
        // Set port number to 1234, set to network byte order by htons
        host_addr.sin_port = htons(1234);

        // Listen on any interface
        host_addr.sin_addr.s_addr = inet_addr("192.168.1.16");

and rather than doing it using conventional methods such as pushing values to the stack and using the stack pointer, I wanted a more natural approach by using actual C style structure. So normally, a C structure is defined as so:

    struct Customer{
       int  id;
       char  name[64];
       char  address[64];
       int   balance;
    };

   struct Customer calvin;
   calvin.name ="Calvin";
   ...

to do this in assembly, you simply write everything like so, I've gone ahead and included a method of accessing the parameters using a simple write syscall to print Calvin's name and address then exit:
segment .data
struc Customer
        c_id resb 4
        c_name resb 64
        c_address resb 64
        c_balance resb 4
endstruc

calvin istruc Customer
        at c_id , dd 7
        at c_name , db "Calvin" ,
        at c_address , db " 12 Mockingbird Lane",
        at c_balance , dd 12500
iend

        segment .text
global  _start
_start:
        xor             rax, rax
        mov             rax,1
        xor             rdi, rdi
        mov             rdi,1
        xor             rsi,rsi
        mov             rsi, calvin + c_name ;remember you are using the address of calvin and moving all the way up to the address of c_name.
        mov             rdx, 7
        syscall

        xor             rax, rax
        mov             rax,1
        xor             rdi, rdi
        mov             rdi,1
        xor             rsi,rsi
        mov             rsi, calvin + c_address
        mov             rdx, 24
        syscall

        xor             rax,rax
        mov             rax,60
        xor             rdi,rdi
        syscall

And that's pretty much it! Laughing out loud Later on I may write a full guide detailing how to write shellcode using Linux, if anything, I'll post it here.

"This is our world now... the world of the electron and the switch, the
beauty of the baud."
-The Mentor