简体   繁体   中英

What is the vulnerability in this C code?

I'm trying to understand buffer overflow attacks better, this is one of the exercises that came up, that has a buffer overflow vulnerability. I would like to know how one can exploit the vulnerability in this code. I wasn't sure how to search for it.

int
main(int argc, char **argv)
{
    (void) foo(argv[1]);
    exit(0);
}

int
foo(char *arg)
{
    return bar(arg);
}

int
bar(char *arg)
{
    char lbuf[1024];
    if (strlen(arg) >= 1024)
        return -1;

    memset(lbuf, 0, sizeof(lbuf));
    sprintf(lbuf, "%s", "Welcome: ");
    read(0, lbuf + strlen(lbuf), sizeof(lbuf) - strlen(lbuf) - 1);
    printf(lbuf);
    fflush(stdout);

    return 0;
}

There is no buffer-overflow there, at all. But that doesn't mean it's secure.

The problem you are expected to find is this line:

printf(lbuf);

Whenever you provide a format-string, make sure it is safely under your control and only asks for those arguments you provided. Accessing arguments not provided, or of the wrong type, results in undefined behavior (all kinds of bizarre and potentially dangerous things can happen). Additionally, one can use %n to poke some memory, which is more obviously dangerous.
In this case, lbuf contains Welcome: followed by arbitrary insecure user-input.

In addition, the program unconditionally reads argv[1] (assumption argc > 0 ), and further assumes it points to a string (assumption argc > 1 ) when passing it to strlen() .

Your code is just an UB without any possible hacks (if we consider only the buffer overflow and will analyze any other possible ones).

Buffer overflow to be used a attacking technique must overwrite some data used later in the program. It may be changing the variables, or placing some code (less common but possible)

an example:

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

int CheckPassword(void)
{
    char passwd[5];
    int passwordcorect = 0;

    printf("Enter password:");
    gets(passwd);

    if(!strcmp(passwd, "1234"))
    {
        passwordcorect = 1;
    }
    return passwordcorect;
}

int main()
{
    if(CheckPassword())
    {
        printf("\nSpecial priviledges granted!!\n");
    }
    else
    {
        printf("\nWrong!!\n");
    }
    return 0;
}

Compiled with mingw. 在此处输入图片说明

And the result:

在此处输入图片说明 在此处输入图片说明

Why did it happen? Because the buffer has overwritten the passwordcorrect variable. It is system, implementation etc related but hacking is not something abstract or portable :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM