AppSec Blog

Top 25 Series - Rank 17 - Integer Overflow Or Wraparound

At first sight, the integer overflow doesn't look all that serious. Any system has a maximum integer number it is able to represent. For example, this would be 255 for an 8 bit system. Right? (keeping it simple to 8 bits for now) Not always. if the number is a signed integer, the maximum integer represented would be 128. Anything "larger" would become a negative number. The description for CWE 190 [1] got a number of nice examples, and I don't just want to repeat them here. Let me instead point to a less common, but similar issue I ran into coding in PHP, to illustrate the problem from a different angle.

Like most languages, PHP implements a function to retrieve random numbers. In the PHP case, the function is called "rand" and it takes two argument. One sets the lower end and the other one the higher end of the output range. For example, rand(100,999) will create three digit random numbers.

At some point, I needed some decent random numbers for an ill conceived session implementation. I knew enough at the time to ask PHP for "large" random numbers. So I wrote code that looked a bit like this sample:

for ($b=1;$b<10;$b++) {
print rand($min,$max)."\n";

If you run this code, you will get something like this (yes... this is the output I got from php 5.1.6 right now on my Mac)


So what happened? These are 9 digits numbers, and they are negative as well as positive!

When I filed a bug report back when, I was essentially told: RTFM! I swallowed my ego and broke down to find the manual and read it [2]. Turns out, that the arguments only work as advertised if they are smaller then "getrandmax". If you don't stick within these limits, you essentially end up with an integer wraparound. Depending on the exact parameters you choose, you may actually get numbers that "look ok", but only the last couple digits change.

Lesson learned: RTFM and be aware of the limitations of your platform!


Post a Comment - Cancel Reply


* Indicates a required field.