C
C & C++¶
Modern C++¶
Strings¶
Stringcmp¶
Using strncmp() instead of memcmp() to compare the SHA hash
- strncmp will returns when a nul byte is reached. If the comparison is good up till the nul byte then it is true. If the first byte was nul, no comparison would be done and the check would pass.
Test in C:
/* strncmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "\x99\x00";
char str2[21] = "\x99\x88\x00\xAA\xBB\xCC\xDD\xEE\xFF";
printf("strlen str1: %d", strlen(str1)); //strlen str1: 9
printf("strlen str2: %d", strlen(str2)); //strlen str2: 9
int ret = strncmp(str2,str1,21);
printf("strncmp %d\n", ret); //strncmp 0
}
Others¶
strcpy
strcat
strncpy
strncat
sprintf
vsprintf
Time¶
gmtime
localtime
ctime
ctime_r
asctime
asctime_r
Memory Safety¶
Dangling pointer:
A pointer that originally pointed to valid data before was freed/deallocated.
free(foo);
*foo = 23;
Out-of-bounds pointer:
Original Pointer pointed inside of the object but pointer was changed to point outside of the object.
char foo[40];
foo[42] = 23;
Control Flow Hijack Attack:
int vuln(int usr, int usr2){
void *(func_ptr)(); //func_ptr is on the stack
int *q = buf + usr; //Out of Bounds Pointer from usr
//Using the Out of bounds pointer you can point q to the address on the stack that has the func_ptr
...
func_ptr = &foo;
...
*q = usr2; //q is being dereferenced and can overwrite the func_ptr pointer
...
(*func_ptr)(); // Overwritten function is executed (Gadgets)
}
Static Analysis¶
FlawFinder:
>>> flawfinder ../Programs/aes-brute-force/test
Flawfinder version 2.0.10, (C) 2001-2019 David A. Wheeler.
Number of rules (primarily dangerous function names) in C/C++ ruleset: 223
Examining ../Programs/aes-brute-force/test/aes-brute-force_origional.cpp
Examining ../Programs/aes-brute-force/test/aes-brute-force.cpp
FINAL RESULTS:
../Programs/aes-brute-force/test/aes-brute-force.cpp:208: [2] (buffer) memcpy:
Does not check for buffer overflows when copying to destination (CWE-120).
Make sure destination can always hold the source data.
../Programs/aes-brute-force/test/aes-brute-force.cpp:209: [2] (buffer) memcpy:
Does not check for buffer overflows when copying to destination (CWE-120).
Make sure destination can always hold the source data.
[...]
CPPCheck:
>>> cppcheck ../Programs/aes-brute-force/test/
Checking ../Programs/aes-brute-force/test/aes-brute-force.cpp ...
../Programs/aes-brute-force/test/aes-brute-force.cpp:148:9: error: Array 'cnt8[16]' accessed at index 16, which is out of bounds. [arrayIndexOutOfBounds]
cnt8[b]++;
^
../Programs/aes-brute-force/test/aes-brute-force.cpp:142:5: note: After for loop, b has value 16
for(b=0;b<16;b++){
^
../Programs/aes-brute-force/test/aes-brute-force.cpp:148:9: note: Array index out of bounds
cnt8[b]++;
^
[...]
Format string attack¶
- Vulnerable Functions
- fprint printf, sprintf, snprintf, vfprintf, vprintf, vsprintf, vsnprintf