Search code examples
gdbx86-64system-callsinline-assemblyshellcode

c shellcode: how to use syscall


I tried to make shell code with syscall

void main()
{
    __asm__ __volatile__
    (
     "movq $0x0068732f6e69622f, %rdx \n\t"
     "pushq %rdx \n\t"
     "movq $0x3b, %rax \n\t"
     "movq %rsp, %rdi \n\t"
     "movq %rsp, %rdx \n\t"
     "pushq %rdi \n\t"
     "lea 0x0(%rsp), %rsi \n\t"
     "movq $0x2a, %r10 \n\t"
     "movq $0x2, %r8 \n\t"
     "movq $0x6, %r9 \n\t"
     "syscall \n\t"
     "pop %rdi \n\t"
     "pop %rdx \n\t"
     );
}

This is my source

It compiled successfully.

But It doesn't execute sh function which I aimed

Is there any problem with code???


Solution

  • Try this, taken from here and spiffed up a bit.

    void main()
    {
        __asm__ __volatile__
        (
          "xor %rdi,%rdi \n\t"
          "push %rdi \n\t"
          "push %rdi \n\t"
          "pop %rsi \n\t"
          "pop %rdx \n\t"
          "movq $0x68732f6e69622f2f,%rdi \n\t"
          "shr $0x08,%rdi \n\t"
          "push %rdi \n\t"
          "push %rsp \n\t"       
          "pop %rdi \n\t" 
          "push $0x3b \n\t"
          "pop %rax \n\t"          
          "syscall \n\t"
         );
    }
    

    Your assembler is similar but seems to go awry on the $rdi and $rdx load. The working code sets them to NULL (0) before the syscall. This link indicates that the exec call takes three parameters apparently the second two can be null.

    I did the set with your code and it worked!

    void main()
    {
        __asm__ __volatile__
        (
         "movq $0x0068732f6e69622f, %rdx \n\t"
         "pushq %rdx \n\t"
         "movq $0x3b, %rax \n\t"
         "movq %rsp, %rdi \n\t"
         "movq %rsp, %rdx \n\t"
         "pushq %rdi \n\t"
         "lea 0x0(%rsp), %rsi \n\t"
         "movq $0x2a, %r10 \n\t"
         "movq $0x2, %r8 \n\t"
         "movq $0x6, %r9 \n\t"
         "movq $0x0, %rsi \n\t"
         "movq $0x0, %rdx \n\t"
         "syscall \n\t"
         "pop %rdi \n\t"
         "pop %rdx \n\t"
         );
    }
    

    Fun little puzzle, gave me a chance to brush up on my assembler :)