Home > other >  Can someone explain how this Buffer Overflow works?
Can someone explain how this Buffer Overflow works?

Time:02-23

I'm trying to give an example of how that stack works by presenting a working buffer overrun example to my colleagues at work. It's hard to find working modern day examples but I have one that works, the only problem is I don't understand it!

I think by providing a string longer than the buffer as a password it is overwriting the compare variable. The example said to provide a password of zzzzzzzzzzzz but I don't see how that turns a 1 to a 0.

Can anyone help?

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

#define PASSWORD "secret233"
#define BUFFER_SIZE 10

int check_pass(char *input)
{
    int compare = 1;
    char buffer[BUFFER_SIZE];

    compare = strcmp(input, PASSWORD);
    printf("[matched value]:%d\n", compare);

    strcpy(buffer, input);
    printf("[matched value]:%d\n", compare);

    return !compare;
}

main()
{
    int passed = 0;
    char input[1024];

    while (1) {
        printf("Enter password: ");
        scanf("%s", input);

        passed = check_pass(input);
        if (passed) {
            printf("--Password correct!\n");
            break;
        }
        else
            printf("--Wrong password. Try again.\n\n");
    }
}

 

CodePudding user response:

Best example of Buffer Overflow would be like this:

The following program obtains an input from the user and compare it with a password. That's fairly simple to demonstrate.

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

int main(void)
{
    char my_input[12];
    char my_password[12] = "password123";
    scanf("%s", my_input);

    if (strcmp(my_input, my_password) == 0)
        printf("PASS\n");
    else
        printf("ERROR\n");
    return 0;
}

Now, compile the above program like:

gcc main.c -o main

Then, type the following command:

./main < <(python -c "print('AAAAAAAAAAA'   '\x00'   'AAAAAAAAAAA'   '\x00')")

Result would be:

PASS

Q: How did this happen?

ANS: scanf() function does not check for the length of the string, if it goes above a certain limit then it just overwrites the next stack stored variable. (my_password)

Q: How to fix this issue?

Ans: Use %<LIMIT>s instead of %s to prevent buffer overflow. OR Simply use fgets() function which is a lot better option.

So, your final code should be like:

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

int main(void)
{
    char my_input[12];
    char my_password[12] = "password123";
    scanf("s", my_input); // limit is now only 12

    if (strcmp(my_input, my_password) == 0)
        printf("PASS\n");
    else
        printf("ERROR\n");
    return 0;
}

Now re-run the above command:

./main < <(python -c "print('AAAAAAAAAAA'   '\x00'   'AAAAAAAAAAA'   '\x00')")

Result:

ERROR
  • Related