Without a doubt, reading Secure Coding in C and C++ made me quite scared of coding securely. In particular, all the ways you can mess up integer security. Ever since I had read that book, it has given me a whole new perspective on things to look out for and security problems that can arise. Lets take a look at what’s going to be a future interview question I’m going to ask people.
// Returns true if set, false if not set
bool ToDecimal(char* string, unsigned long* pdw)
{
char* end = NULL;
unsigned long dw = strtol(string, &end, 10);
if ( dw == LONG_MAX || dw == LONG_MIN
|| (dw == 0 && wzEnd=string) )
{
return false;
}
*pdw = dw;
return true;
}
Find the bug!
So what’s wrong with this code? Hint: many things are wrong (which is why I like it), but I’m speaking of what’s relevant to my post. Well, strtol happens to return a signed integer, not an unsigned integer. What happens if –1 is passed in? Well, strtol will return –1 (and on most machines it’s represented as 0xffffffff). The compiler will then stick it into the unsigned long and away they go!
int main()
{
//Sploits!
unsigned long age = 25;
unsigned long brosAge = 0;
char* theInput = "-1000" //Nasty input
if (ToDecimal(theInput, &brosAge))
{
printf("My age + my brothers age = %d",
(age+brosAge)); //4294966320
}
}
In my theoretical program, it’s hardly a problem, but what happens if I reserved a buffer, was doing pointer arithmetic, or something else that could cause serious damage? This could have just become an entry point into a security hole. So please, check your signs!
2 Responses to “Be scared of doing arithmetic”
I wouldn’t stand against this question without:
1) Documentation for strtol. Mere mortals don’t know it and spoiled people learn to love the compiler’s type safety. More than type safety, spoiled people are used to libraries with overloaded “smart” behavior that “just works” or makes a lot of noise when it doesn’t.
2) Some motivation for asking the question. This question is say… 50% about C, 50% about testing.
Basically, I think C is scary! No worries though, TDD eats code like this for breakfast
This post was suppose to be more about gotcha’s, but I agree that there are some things that would have to be done in order to make it a real interview question. I would probably have a few functions on a board with a description, and ask the person to come up with the function mentioned above.