Saturday, February 10, 2007

White Board Software Security Question #2

What is wrong with this code?

char * foo(int len, char* value)
char * buf;
buf = (char*)malloc(len + 5);
return (NULL);
try {
if(len <= 5) memcpy(buf,value,len); } catch (Exception* ex) { Console::WriteLine(S"Generic Exception Handler: {0}", ex); } return buf; } For finding the answer, think which values passed to "len" might create a problem. For example, look at this code that call the function "foo" #include "stdafx.h" #using
using namespace System;
char* foo(int l, char* value);

int main()
char value[]={'H','A','C','K','\0'};
char* buf;
//this will work
buf = foo(5,value);
//this will overflow the buffer
buf = foo(-4,value);
return 0;

Basically the problem of this code is that is prone to integer overflow. When len is negative (e.g -4) the amount of memory allocated for buf is one byte (-4+5). The call to memcpy will take the size_t (unsigned int) (4) value and will try to copy a value in "buf" that will be larger than the one that can be allocated by "buf".

In general, integer overflows occur when a program fails to check that an arithmetic operation can result in a quantity either greater than a data type's maximum value or less than its minimum value. This can happen when comparing values that have been casted (for example from int to long that is from 16 bit to 32 bits and compared to max boundaries that can be bypassed since the sign is maintained during casting such as exceeding the actual representation for int that is 32K). In the example herein, the cause of integer overflow is due to the memory allocation function, where user input stumbles with an implicit conversion between signed and unsigned values (like done in memcpy() for example). An attacker can cause the program to under-allocate memory (set len to -4) so that the program may be vulnerable to a buffer overflow.

No comments: