Search code examples
cx86buffer-overflowstack-memoryexploit

can you identify any vulerabilty in this C code


Please can someone help me to look into this code and tell if there is a vulnerability? I'm new to the C language and also just started studying ethical hacking. If there is, can someone tell me the vulnerability and how to exploit it?

I was given a hint

hint: Your task is to inject a command line argument such that function4 gets called, instead of function3

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

int function1(int x, int y, int z)
{
    int result_func1;
    result_func1 = x + y + z;
    return result_func1;
}

int function2(int x, int y, char *input_string)
{
    int result_func2;
    char buffer[20];
    strcpy(buffer, input_string);
    printf("your input string %s is copied in the buffer \n", input_string);
    result_func2 = x - y;
    return result_func2;
}

void function3(int result1, int result2)
{
    printf("The result of function 1 is %d\n", result1);
    printf("The result of function 1 is %d\n", result1);
}

void function4(void)
{
    printf("The function never gets called is \n");
    exit(-1);
}

int main(int argc, char *argv[])
{
    int result1;
    int result2;
    result1 = function1(5, 10, 15);
    result2 = function2(20, 8, argv[1]);
    function3(result1, result1);
}

Solution

  • There is a straightforward buffer overflow on the strcpy line in function2. If you provide a parameter longer than 20 characters, the stack will start to get overwritten and you will be able to set EIP for the function to return to function4. Note that this will only work so easily in special environments nowadays where protections against bof are turned off.

    The process to come up with the right input could be something along the lines of

    • find a debugger (like eg. gdb)
    • add a patameter to this program that consists of 20 characters that don't matter, and then something like \x01\x02\x03\x04... (the actual bytes, not the literal string ofc)
    • run it with the debugger
    • take note where EIP points after the stack got overwritten, those are the characters in your input that you will use to set EIP to the address of function4