Обсуждение: [PATCH] Fix possible string overflow with sscanf (xlog.c)

Поиск
Список
Период
Сортировка

[PATCH] Fix possible string overflow with sscanf (xlog.c)

От
Ranier Vilela
Дата:
Hi,
I know it's very hard, but is possible. Just someone with the knowledge to do.

Here a proof of concept:
#include <stdlib.h>
#include <string.h>

#define MAXPGPATH 256

int main(int argc, char ** argv)
{
    char        tbsoid[MAXPGPATH];
    char        str[MAXPGPATH];
    int            ch,
                prev_ch = -1,
                i = 0,
                n;
    FILE * lfp;

    lfp = fopen("c:\\tmp\\crash.dat", "rb");
    while ((ch = fgetc(lfp)) != EOF)
    {
        if ((ch == '\n' || ch == '\r') && prev_ch != '\\')
        {
            str[i] = '\0';
            if (sscanf(str, "%s %n", tbsoid, &n) != 1) {
               printf("tbsoid size=%u\n", strlen(tbsoid));
               printf("tbsoid=%s\n", tbsoid);
               exit(1);
            }
            i = 0;
            continue;
        }
        else if ((ch == '\n' || ch == '\r') && prev_ch == '\\')
            str[i - 1] = ch;
        else
            str[i++] = ch;
        prev_ch = ch;
    }
    fclose(lfp);
}

Overflow with (MAXPGPATH=256)
C:\usr\src\tests\scanf>sscanf3
tbsoid size=260
tbsoid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx

Now with patch:
C:\usr\src\tests\scanf>sscanf3
tbsoid size=255
tbsoid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxx

The solution is simple, but clumsy. I hope that is enough.
sscanf(str, "%1023s %n", tbsoid, &n)

Best regards.
Ranier Vilela
Вложения