Modify C code with buffer overflow vulnerability to skip code

I am trying to find a way to use the buffer overflow vulnerability in the following source code, so the line printf("x is 1")will be skipped:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void func(char *str) {
     char buffer[24];
     int *ret;
     strcpy(buffer,str);
}

int main(int argc, char **argv) {
    int x;
    x = 0;
    func(argv[1]);
    x = 1;
    printf("x is 1");
    printf("x is 0");
    getchar();
}

To do this, I want to change the function "func". I know that I will need to use the ret variable to change the return address only for the line I want to skip, but I'm not sure how to actually do this. Does anyone have a suggestion?

EDIT:

Using gdb, I was able to find the following calls in the main function:

Temporary breakpoint 1, 0x00000000004005ec in main ()
(gdb) x/20i $pc
=> 0x4005ec <main+4>:   sub    $0x20,%rsp
   0x4005f0 <main+8>:   mov    %edi,-0x14(%rbp)
   0x4005f3 <main+11>:  mov    %rsi,-0x20(%rbp)
   0x4005f7 <main+15>:  movl   $0x0,-0x4(%rbp)
   0x4005fe <main+22>:  mov    -0x20(%rbp),%rax
   0x400602 <main+26>:  add    $0x8,%rax
   0x400606 <main+30>:  mov    (%rax),%rax
   0x400609 <main+33>:  mov    %rax,%rdi
   0x40060c <main+36>:  callq  0x4005ac <func>
   0x400611 <main+41>:  movl   $0x1,-0x4(%rbp)
   0x400618 <main+48>:  mov    $0x4006ec,%edi
   0x40061d <main+53>:  mov    $0x0,%eax
   0x400622 <main+58>:  callq  0x400470 <printf@plt>
   0x400627 <main+63>:  mov    $0x4006f3,%edi
   0x40062c <main+68>:  mov    $0x0,%eax
   0x400631 <main+73>:  callq  0x400470 <printf@plt>
   0x400636 <main+78>:  callq  0x400490 <getchar@plt>
   0x40063b <main+83>:  leaveq
   0x40063c <main+84>:  retq
   0x40063d:    nop

Although, I am confused about where to go from here. I know that the function will return to line 0x400611 and that I need to get it to go to 0x400631, but I'm not sure how to determine how many bits to jump or how I should change the ret variable.

+4
1

, , , , . :

  • , :

    enter image description here

  • func (, ):

    enter image description here

  • , , :

    enter image description here

, :

void func(char *str) {
    // 1. Get the address of an object on the stack
    long *ret = (long*)(&str);      

    // 2. Move ret to point to the location of the return address from this function. 
    //    Per the example above on my system (Windows 64bit + VS) it was just -1
    ret -= NUMBER_OF_ITEMS_IN_THE_STACK_BEFORE_RETURN_ADDR;

    // 3. Modify the return address by adding it the offset to command to go to (in my 
    //   (case 33).
    *ret = *ret + OFFSET_TO_COMMAND;

    // The rest of your code
    char buffer[24];
    strcpy(buffer, str);
}

, (, OS, Compiler ..). , , .

, (, VS) . - , , .

+1

All Articles