УНИВЕРСИТЕТ
Название работы: Статический анализ кода.
Цель: Научиться использовать статические анализаторы кода для поиска уязвимостей в программной обеспечении. Выполнили: Студенты гр. № 4406 ФИО Лукманов И.Р., Сибгатуллин А.А. Ход работы: 1.1. В файле flawtest.c были найдены следующий уязвимости: Отсутствие контроля за переполнением буфера – может возникнуть при копировании, конкатенации; переполнение статичных массивов; неправильное использование функций. 1.2. В файле junk.c были найдены следующий уязвимости: Переполнение статичных массивов; малый размер форматных строк. 1.3. В файле test.c были найдены следующий уязвимости: Неправильное использование функций; размер длинны параметра должен быть постоянным; максимальная длинна должна записываться в символах, а не в байтах; выставлено значение NULL для ACL; отсутствует контроль за переполнением буфера при копировании; отсутствует контроль за переполнением буфера; использование процедуры создания нового процесса; переполнение статичных массивов. 2.1. Результаты работы программы FlawFinder для файла flawtest.c: Flawfinder version 1.27, (C) 2001-2004 David A. Wheeler. Number of dangerous functions in C/C++ ruleset: 160 Examining flawtest.c flawtest.c:17: [5] (buffer) strncat: Easily used incorrectly (e.g., incorrectly computing the correct maximum size to add). Consider strlcat or automatically resizing strings. Risk is high; the length parameter appears to be a constant, instead of computing the number of characters left. flawtest.c:18: [5] (buffer) _tcsncat: Easily used incorrectly (e.g., incorrectly computing the correct maximum size to add). Consider strlcat or automatically resizing strings. Risk is high; the length parameter appears to be a constant, instead of computing the number of characters left. flawtest.c:21: [5] (buffer) MultiByteToWideChar: Requires maximum length in CHARACTERS, not bytes. Risk is high, it appears that the size is given as bytes, but the function requires size as characters. flawtest.c:10: [4] (buffer) _mbscpy: Does not check for buffer overflows when copying to destination. Consider using a function version that stops copying at the end of the buffer. flawtest.c:13: [4] (buffer) lstrcat: Does not check for buffer overflows when concatenating to destination. flawtest.c:6: [2] (buffer) char: Statically-sized arrays can be overflowed. Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length. flawtest.c:7: [2] (buffer) char: Statically-sized arrays can be overflowed. Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length. flawtest.c:11: [2] (buffer) memcpy: Does not check for buffer overflows when copying to destination. Make sure destination can always hold the source data. flawtest.c:12: [2] (buffer) CopyMemory: Does not check for buffer overflows when copying to destination. Make sure destination can always hold the source data. flawtest.c:14: [1] (buffer) strncpy: Easily used incorrectly; doesn't always \0-terminate or check for invalid pointers. flawtest.c:15: [1] (buffer) _tcsncpy: Easily used incorrectly; doesn't always \0-terminate or check for invalid pointers. flawtest.c:16: [1] (buffer) strncat: Easily used incorrectly (e.g., incorrectly computing the correct maximum size to add). Consider strlcat or automatically resizing strings. flawtest.c:19: [1] (buffer) strlen: Does not handle strings that are not \0-terminated (it could cause a crash if unprotected). flawtest.c:23: [1] (buffer) MultiByteToWideChar: Requires maximum length in CHARACTERS, not bytes. Risk is very low, the length appears to be in characters not bytes. Hits = 14 Lines analyzed = 26 in 0.52 seconds (1213 lines/second) Physical Source Lines of Code (SLOC) = 17 Hits@level = [0] 0 [1] 5 [2] 4 [3] 0 [4] 2 [5] 3 Hits@level+ = [0+] 14 [1+] 14 [2+] 9 [3+] 5 [4+] 5 [5+] 3 Hits/KSLOC@level+ = [0+] 823.529 [1+] 823.529 [2+] 529.412 [3+] 294.118 [4+] 294.118 [5+] 176.471 Minimum risk level = 1 Not every hit is necessarily a security vulnerability. There may be other security vulnerabilities; review your code! 2.2. Результаты работы программы FlawFinder для файла junk.c: Flawfinder version 1.27, (C) 2001-2004 David A. Wheeler. Number of dangerous functions in C/C++ ruleset: 160 Examining junk.c junk.c:5: [2] (buffer) char: Statically-sized arrays can be overflowed. Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length. junk.c:7: [1] (buffer) fscanf: it's unclear if the %s limit in the format string is small enough. Check that the limit is sufficiently small, or use a different input function. Hits = 2 Lines analyzed = 9 in 0.52 seconds (476 lines/second) Physical Source Lines of Code (SLOC) = 7 Hits@level = [0] 0 [1] 1 [2] 1 [3] 0 [4] 0 [5] 0 Hits@level+ = [0+] 2 [1+] 2 [2+] 1 [3+] 0 [4+] 0 [5+] 0 Hits/KSLOC@level+ = [0+] 285.714 [1+] 285.714 [2+] 142.857 [3+] 0 [4+] 0 [5+] 0 Minimum risk level = 1 Not every hit is necessarily a security vulnerability. There may be other security vulnerabilities; review your code! 2.3. Результаты работы программы FlawFinder для файла test.c: Flawfinder version 1.27, (C) 2001-2004 David A. Wheeler. Number of dangerous functions in C/C++ ruleset: 160 Examining test.c test.c:32: [5] (buffer) gets: Does not check for buffer overflows. Use fgets() instead. test.c:56: [5] (buffer) strncat: Easily used incorrectly (e.g., incorrectly computing the correct maximum size to add). Consider strlcat or automatically resizing strings. Risk is high; the length parameter appears to be a constant, instead of computing the number of characters left. test.c:57: [5] (buffer) _tcsncat: Easily used incorrectly (e.g., incorrectly computing the correct maximum size to add). Consider strlcat or automatically resizing strings. Risk is high; the length parameter appears to be a constant, instead of computing the number of characters left. test.c:60: [5] (buffer) MultiByteToWideChar: Requires maximum length in CHARACTERS, not bytes. Risk is high, it appears that the size is given as bytes, but the function requires size as characters. test.c:62: [5] (buffer) MultiByteToWideChar: Requires maximum length in CHARACTERS, not bytes. Risk is high, it appears that the size is given as bytes, but the function requires size as characters. test.c:73: [5] (misc) SetSecurityDescriptorDacl: Never create NULL ACLs; an attacker can set it to Everyone (Deny All Access), which would even forbid administrator access. test.c:73: [5] (misc) SetSecurityDescriptorDacl: Never create NULL ACLs; an attacker can set it to Everyone (Deny All Access), which would even forbid administrator access. test.c:17: [4] (buffer) strcpy: Does not check for buffer overflows when copying to destination. Consider using strncpy or strlcpy (warning, strncpy is easily misused). test.c:20: [4] (buffer) sprintf: Does not check for buffer overflows. Use snprintf or vsnprintf. test.c:21: [4] (buffer) sprintf: Does not check for buffer overflows. Use snprintf or vsnprintf. test.c:22: [4] (format) sprintf: Potential format string problem. Make format string constant. test.c:23: [4] (format) printf: If format strings can be influenced by an attacker, they can be exploited. Use a constant for the format specification. test.c:25: [4] (buffer) scanf: The scanf() family's %s operation, without a limit specification, permits buffer overflows. Specify a limit to %s, or use a different input function. test.c:27: [4] (buffer) scanf: The scanf() family's %s operation, without a limit specification, permits buffer overflows. Specify a limit to %s, or use a different input function. test.c:38: [4] (format) syslog: If syslog's format strings can be influenced by an attacker, they can be exploited. Use a constant format string for syslog. test.c:49: [4] (buffer) _mbscpy: Does not check for buffer overflows when copying to destination. Consider using a function version that stops copying at the end of the buffer. test.c:52: [4] (buffer) lstrcat: Does not check for buffer overflows when concatenating to destination. test.c:75: [3] (shell) CreateProcess: This causes a new process to execute and is difficult to use safely. Specify the application path in the first argument, NOT as part of the second, or embedded spaces could allow an attacker to force a different program to run. test.c:75: [3] (shell) CreateProcess: This causes a new process to execute and is difficult to use safely. Specify the application path in the first argument, NOT as part of the second, or embedded spaces could allow an attacker to force a different program to run. test.c:91: [3] (buffer) getopt_long: Some older implementations do not protect against internal buffer overflows. Check implementation on installation, or limit the size of all string inputs. test.c:16: [2] (buffer) strcpy: Does not check for buffer overflows when copying to destination. Consider using strncpy or strlcpy (warning, strncpy is easily misused). Risk is low because the source is a constant string. test.c:19: [2] (buffer) sprintf: Does not check for buffer overflows. Use snprintf or vsnprintf. Risk is low because the source has a constant maximum length. test.c:45: [2] (buffer) char: Statically-sized arrays can be overflowed. Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length. test.c:46: [2] (buffer) char: Statically-sized arrays can be overflowed. Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length. test.c:50: [2] (buffer) memcpy: Does not check for buffer overflows when copying to destination. Make sure destination can always hold the source data. test.c:51: [2] (buffer) CopyMemory: Does not check for buffer overflows when copying to destination. Make sure destination can always hold the source data. test.c:97: [2] (misc) fopen: Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?. test.c:15: [1] (buffer) strcpy: Does not check for buffer overflows when copying to destination. Consider using strncpy or strlcpy (warning, strncpy is easily misused). Risk is low because the source is a constant character. test.c:18: [1] (buffer) sprintf: Does not check for buffer overflows. Use snprintf or vsnprintf. Risk is low because the source is a constant character. test.c:26: [1] (buffer) scanf: it's unclear if the %s limit in the format string is small enough. Check that the limit is sufficiently small, or use a different input function. test.c:53: [1] (buffer) strncpy: Easily used incorrectly; doesn't always \0-terminate or check for invalid pointers. test.c:54: [1] (buffer) _tcsncpy: Easily used incorrectly; doesn't always \0-terminate or check for invalid pointers. test.c:55: [1] (buffer) strncat: Easily used incorrectly (e.g., incorrectly computing the correct maximum size to add). Consider strlcat or automatically resizing strings. test.c:58: [1] (buffer) strlen: Does not handle strings that are not \0-terminated (it could cause a crash if unprotected). test.c:64: [1] (buffer) MultiByteToWideChar: Requires maximum length in CHARACTERS, not bytes. Risk is very low, the length appears to be in characters not bytes. test.c:66: [1] (buffer) MultiByteToWideChar: Requires maximum length in CHARACTERS, not bytes. Risk is very low, the length appears to be in characters not bytes. Hits = 36 Lines analyzed = 117 in 0.53 seconds (3629 lines/second) Physical Source Lines of Code (SLOC) = 80 Hits@level = [0] 0 [1] 9 [2] 7 [3] 3 [4] 10 [5] 7 Hits@level+ = [0+] 36 [1+] 36 [2+] 27 [3+] 20 [4+] 17 [5+] 7 Hits/KSLOC@level+ = [0+] 450 [1+] 450 [2+] 337.5 [3+] 250 [4+] 212.5 [5+] 87.5 Suppressed hits = 2 (use --neverignore to show them) Minimum risk level = 1 Not every hit is necessarily a security vulnerability. There may be other security vulnerabilities; review your code! 3. Исходный тест программы lab2.cpp, выполняющей конкатенацию 2-х строк:
// prog.cpp: main project file. #include "stdafx.h" //подключение библиотек #include "stdlib.h" #include "stdio.h" #include "string.h" int main() { char *s; //строка, в к-рую записываются 2 введенные char s1[50]; //первая вводимая строка, размерность 50. Я не помню как вводить безразмерную char s2[50]; //вторая вводимая строка printf("\n vvedite s1\n"); //тупо текстовая подсказака(по сути вывод 2 слов через "фотошоп" ^_^) gets(s1); //считывание 1 строки. Ввод прекратится по нажатию ENTER printf("\n vvedite s2\n"); //кстати, \n - это перевод на следующую строку gets(s2); s = strcat(s1,s2); //Функция strcat - объединение строк и запись их в s printf("\n%s\n", s); //вывод результата //free(s1); - пыталтся наладить очищение памяти компа, но почему-то не вышло //free(s2); - поэтому мусор в памяти так и лежит) //free(s); return 0; //не помню зачем нужна эта штука, но она присутсвует в каждой проге на С++ }
4. Результаты анализа программы lab2.cpp при помощи программы FlawFinder следующие:
Flawfinder version 1.27, (C) 2001-2004 David A. Wheeler. Number of dangerous functions in C/C++ ruleset: 160 Examining prog.cpp prog.cpp:13: [5] (buffer) gets: Does not check for buffer overflows. Use fgets() instead. prog.cpp:15: [5] (buffer) gets: Does not check for buffer overflows. Use fgets() instead. prog.cpp:16: [4] (buffer) strcat: Does not check for buffer overflows when concatenating to destination. Consider using strncat or strlcat (warning, strncat is easily misused). prog.cpp:10: [2] (buffer) char: Statically-sized arrays can be overflowed. Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length. prog.cpp:11: [2] (buffer) char: Statically-sized arrays can be overflowed. Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length. Hits = 5 Lines analyzed = 22 in 0.52 seconds (1121 lines/second) Physical Source Lines of Code (SLOC) = 17 Hits@level = [0] 0 [1] 0 [2] 2 [3] 0 [4] 1 [5] 2 Hits@level+ = [0+] 5 [1+] 5 [2+] 5 [3+] 3 [4+] 3 [5+] 2 Hits/KSLOC@level+ = [0+] 294.118 [1+] 294.118 [2+] 294.118 [3+] 176.471 [4+] 176.471 [5+] 117.647 Minimum risk level = 1 Not every hit is necessarily a security vulnerability. There may be other security vulnerabilities; review your code!
5. Для того, чтобы избежать ошибок связанных с переполнением буфера в языках C/C++ необходимо вести контроль за переполнением буфера, думать головой, проводить исследование исполняемого кода на наличие уязвимостей. УНИВЕРСИТЕТ
|