Q: Custom shellcode in C? I am trying to develop a shellcode that would execute the following command /bin/ls / (list root directory).
So, I first try to develop a script in assembly to do the job for me, below is the script:
SECTION .data
    buf: db "./", 0
SECTION .text
global _start

_start:
    xor eax, eax
    xor edx, edx
    push eax
    push long 0x736c2f2f    ; "sl/"
    push long 0x6e69622f    ; "nib/"
    mov ebx, esp
    push eax
    push byte 0x2f
    mov esi, esp

    push eax
    push esi
    push ebx
    mov ecx, esp
    mov eax, 0x0b
    int 0x80

    mov eax, 1
    int 0x80

I then compile with following: nasm -f elf -g shell.asm && ld -s -o shell shell.o -m elf_i386. This works perfectly, If executed, it list root directory.
Then, I disassemble the binary using objdump to get the op-codes:
#objdump -d ./shell


./shell:     file format elf32-i386


Disassembly of section .text:

08049000 <.text>:
 8049000:   31 c0                   xor    %eax,%eax
 8049002:   31 d2                   xor    %edx,%edx
 8049004:   50                      push   %eax
 8049005:   68 2f 2f 6c 73          push   $0x736c2f2f
 804900a:   68 2f 62 69 6e          push   $0x6e69622f
 804900f:   89 e3                   mov    %esp,%ebx
 8049011:   50                      push   %eax
 8049012:   6a 2f                   push   $0x2f
 8049014:   89 e6                   mov    %esp,%esi
 8049016:   50                      push   %eax
 8049017:   56                      push   %esi
 8049018:   53                      push   %ebx
 8049019:   89 e1                   mov    %esp,%ecx
 804901b:   b8 0b 00 00 00          mov    $0xb,%eax
 8049020:   cd 80                   int    $0x80
 8049022:   b8 01 00 00 00          mov    $0x1,%eax
 8049027:   cd 80                   int    $0x80

To make life easy, I did the following: objdump -d ./shell | awk -F "       " '{print $1}' |awk -F ":" '{print $2}' | tr -d " " | tr -d "\n" | tr -d "\t" | xclip -selection c. Basically it copies the opcodes to the clipboard. 31c031d250682f2f6c73682f62696e89e3506a2f89e650565389e1b80b000000cd80b801000000cd80.
I then to test my shellcode, I inject it to a c program as below:
#include<stdio.h>
#include<string.h>

unsigned char shellcode[] = "\x31\xc0\x31\xd2\x50\x68\x2f\x2f\x6c\x73\x68\x2f\x62\x69\x6e\x89\xe3\x50\x6a\x2f\x89\xe6\x50\x56\x53\x89\xe1\xb8\x0b\x00\x00\x00\xcd\x80\xb8\x01\x00\x00\x00\xcd\x80";

int main(int argc, char **argv) {
    int *ret;
    ret = (int *)&ret + 2;  
    (*ret) = (int)shellcode;
}

# gcc -g -o foo foo.c -z execstack -fno-stack-protector
foo.c: In function 'main':
foo.c:9:11: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
9 |  (*ret) = (int)shellcode;
  |

with that done, If I execute my foo binary, it execute the program but do not list the root directory.
I am using nasm with the following arc: Linux kali 5.2.0-kali2-amd64 #1 SMP Debian 5.2.9-2kali1 (2019-08-22) x86_64 GNU/Linux
