Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

possible buffer overflow vulnerability for va_list in C?

I have the following code:

int ircsocket_print(char *message, ...)
{
    char buffer[512];
    int iError;
    va_list va;
    va_start(va, message);
    vsprintf(buffer, message, va);
    va_end(va);
    send(ircsocket_connection, buffer, strlen(buffer), 0);
    return 1;
}

And I wanted to know if this code is vulerable to buffer overflows by providing char arrays with a size > 512 to the variables list? And if so - How can I fix this?

thank you.

like image 523
Andreas Grapentin Avatar asked Nov 27 '22 22:11

Andreas Grapentin


1 Answers

Yes, it is vulnerable.

You can implement your function this way:

int ircsocket_print(char *message, ...)
{
    char buf[512];
    char *buffer;
    int len;
    va_list va;

    buffer = buf;
    va_start(va, message);
    len = vsnprintf(buffer, 512, message, va);
    va_end(va);

    if (len >= 512)
    {
        buffer = (char*)malloc(len + 1);
        va_start(va, message);
        len = vsnprintf(buffer, len + 1, message, va);
        va_end(va);
    }

    send(ircsocket_connection, buffer, len, 0);

    if (buffer != buf)
        free(buffer);
    return 1;
}
like image 139
Andrey Kamaev Avatar answered Dec 16 '22 22:12

Andrey Kamaev