Link to this headingC & C++
Link to this headingModern C++
Link to this headingStrings
Link to this headingStringcmp
Using strncmp() instead of memcmp() to compare the SHA hash
- strncmp will return when a null byte is reached. If the comparison is good up to the null byte then it is true. If the first byte was null, no comparison would be done and the check would pass.
Test in C:
/* strncmp example */
int
Link to this headingOthers
Unsafe string manipulation functions:
strcpy- No bounds checking, can cause Buffer Overflowsstrcat- No bounds checking when concatenating stringsstrncpy- May not null-terminate, can leave uninitialized datastrncat- Off-by-one errors common with length parametersprintf- No bounds checking on output buffervsprintf- Variable argument version of sprintf with same issues
Memory functions:
memcpy- No overlap checking, can corrupt data if source/dest overlap
Safer alternatives:
- Use
strncpywith explicit null termination - Use
strlcpy/strlcatwhere available - Use
snprintf/vsnprintfinstead ofsprintf/vsprintf - Use
memmoveinstead ofmemcpyfor potentially overlapping regions
Link to this headingTime
Vulnerable time functions:
gmtime- Returns pointer to static buffer, not thread-safelocaltime- Returns pointer to static buffer, not thread-safectime- Returns pointer to static buffer, not thread-safeasctime- Returns pointer to static buffer, not thread-safe
Thread-safe alternatives:
gmtime_r- Reentrant version of gmtimelocaltime_r- Reentrant version of localtimectime_r- Reentrant version of ctimeasctime_r- Reentrant version of asctime
Link to this headingMemory Safety
Dangling pointer:
A pointer that originally pointed to valid data before it was freed/deallocated. This can turn into a [Use After Free](/Exploitation/Heap/Use After Free.md) vulnerability.
char *foo = ;
;
*foo = 23; // Use after free vulnerability
Out-of-bounds pointer:
Original pointer pointed inside the object but the pointer was changed to point outside the object.
char foo;
foo = 23;
Control Flow Hijack Attack:
int
Link to this headingStatic Analysis
FlawFinder:
CPPCheck:
;
for;;{
;
Link to this headingFormat string attack
Exploitation of a Format String Vuln
Vulnerable functions:
printffamily:printf,fprintf,sprintf,snprintfvprintffamily:vprintf,vfprintf,vsprintf,vsnprintfsyslogand custom logging functions
Example vulnerability:
// User input directly passed to printf
char *user_input = ;
; // Vulnerable - use printf("%s", user_input) instead
Impact:
- Information disclosure (reading stack/memory)
- Arbitrary memory writes
- Code execution in some cases
Prevention:
- Always use format strings:
printf("%s", user_input) - Use compiler flags:
-Wformat -Wformat-security - Static analysis tools can detect many format string bugs