Created
April 25, 2014 17:48
-
-
Save mattpresson/11297697 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <wchar.h> | |
/* | |
* Modified example to demonstrate a potential buffer overflow | |
* in the secure code example provided by Carnegie Mellon. | |
* | |
* Original URL: https://www.securecoding.cert.org/confluence/display/seccode/ARR38-C.+Guarantee+that+library+functions+do+not+form+invalid+pointers | |
* Section: Compliant Solution (Element Count) | |
*/ | |
// Original values for `str` and `w_str` | |
// static const char str[] = "Hello world"; | |
// static const wchar_t w_str[] = L"Hello world"; | |
// Modified values of `str` and `w_str` to demonstrate buffer overflow | |
static const char str[] = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; // 40 chars | |
static const wchar_t w_str[] = L"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; // 50 chars | |
void main(void) | |
{ | |
char buffer[32]; | |
wchar_t w_buffer[32]; | |
printf( "str: %s length: %d sizeof: %d\n", str, (unsigned int)strlen( str ), (unsigned int)sizeof( str ) ); | |
printf( "w_str: %S length: %d sizeof: %d\n", w_str, (unsigned int)wcslen( w_str ), (unsigned int)sizeof( w_str ) / 4 ); | |
printf( "\n" ); | |
printf( "buffer: %s length: %d sizeof: %d\n", buffer, (unsigned int)strlen( buffer ), (unsigned int)sizeof( buffer ) ); | |
printf( "w_buffer: %S length: %d sizeof: %d\n", w_buffer, (unsigned int)wcslen( w_buffer ), (unsigned int)sizeof( w_buffer ) / 4 ); | |
printf( "\n" ); | |
memcpy( buffer, str, strlen( str ) + 1 ); /* Problem here as str is longer than buffer */ | |
wmemcpy( w_buffer, w_str, wcslen( w_str ) + 1 ); /* Problem here as w_str is longer than w_buffer */ | |
printf( "buffer: %s length: %d sizeof: %d\n", buffer, (unsigned int)strlen( buffer ), (unsigned int)sizeof( buffer ) ); | |
printf( "w_buffer: %S length: %d sizeof: %d\n", w_buffer, (unsigned int)wcslen( w_buffer ), (unsigned int)sizeof( w_buffer ) / 4 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment