Cool Little Code Snippet...
At my work an email sometimes gets sent out asking us to spot the defect. I like these emails as it is usually with code / bugs that I have no f'ing experience and I can learn something that is a nice little trick. So enough rambling here is some code that basically has the same bug.
Note: This is a technical post so if you don't care about this geeky crap just stop reading now :).
Disclaimer: I wrote the below code in blogger so it might not compile but the part that is interesting is technically correct.
<codesnippet>
#include
using namespace std;
int main() {
char * c;
char * junkVar;
const char * f00;
junkVar = new char('a');
f00 = junkVar + 1;
c = junkVar + 2;
if(foo - c >= sizeof(int)) {
cout << "inside of if-statement" << endl;
} else {
cout << "hit else statement instead" << endl;
}
return 0;
}
</codesnippet>
So, where is the bug? How will this code execute if it was ran? If you look at the code you will notice that "foo - c" should have a difference of -1 since "c" is one higher than "foo". However, sizeof returns an unsigned integer and the compiler will cast the subtraction operation to an unsigned value as well. What does that mean? It means -1 becomes FFFFFFFF which is way bigger than "sizeof(int)" and the if condition would be correct. Pretty cool, eh? How would you fix this? Well just cast the return value of sizeof to something signed like say..int.
There are a few security implications of this code. Mainly if you could make this happen the pre-conditions of the code executed in the if-statement might not be correct and all sorts of weird issues could crop up.
Alright, back to work...
Labels: code snippets, cool stuff, security