Created
November 7, 2011 16:42
-
-
Save ozten/1345468 to your computer and use it in GitHub Desktop.
Detecting buffer overflows - first stab
This file contains hidden or 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
/** Callback function for streaming CURL response */ | |
static size_t write_cb(void *contents, size_t size, size_t nmemb, void *userp) | |
{ | |
size_t realsize = size * nmemb; | |
size_t nextsize; | |
struct json_response *mem = (struct json_response *)userp; | |
if (mem->size + realsize >= mem->realsize) { | |
nextsize = mem->size + realsize + JSON_BUFFER; | |
if (nextsize < mem->realsize) { | |
syslog(LOG_ERR, "Buffer Overflow, ignoring new contents"); | |
return realsize; | |
} | |
mem->realsize = nextsize; | |
void *tmp = malloc(mem->size + realsize + JSON_BUFFER); | |
if (tmp == NULL) { | |
syslog(LOG_ERR, "Unable to grow json_response tmp buffer"); | |
mem->memerr = 1; | |
return realsize; | |
} | |
memcpy(tmp, mem->memory, mem->size); | |
free(mem->memory); | |
mem->memory = malloc(mem->size + realsize + JSON_BUFFER); | |
if (mem->memory == NULL) { | |
syslog(LOG_ERR, "Unable to grow json_response memory slot"); | |
mem->memerr = 1; | |
return realsize; | |
} | |
memcpy(mem->memory, tmp, mem->size); | |
free(tmp); | |
} | |
memcpy(&(mem->memory[mem->size]), contents, realsize); | |
mem->size += realsize; | |
mem->memory[mem->size] = 0; | |
return realsize; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I originally thought that just a < check would be sufficient, but now think there are more cases that need to be tested for. The overflow check won't work if for some reason nextsize == mem->realsize due to an overflow. I can't say for certain if this is possible. There is also potential for the realsize calculation to overflow. In that scenario you would fail to copy enough bytes to the buffer which isn't as big a concern as writing too much to the buffer.