Popular Posts

Sunday, May 16, 2010

Revising C++

I happened to explore the NIST's SAMATE database for insecure code over this weekend. The NIST SAMATE project is collecting examples of vulnerable code. It is designed to be used to "provide users, researchers, and software security assurance tool developers with a set of known security flaws.

Here is what I picked up:

1.    int main(int argc, char *argv[])
2.    {
3.      int loop_counter;
4.      char buf[10];
5.      for(loop_counter = 0; ; loop_counter++)
6.      {
7.        if (loop_counter > 4105) break;
8.        /*  BAD  */
9.        buf[4105] = 'A';
10.      }    
11.      return 0;
16.    }

So let’s start with problems in this code first.

Problems:

1. The first one is the breaking condition is placed in the middle of the loop although this will not create any runtime or compile time error but still it is not considered a good programming practice.

2. Terminating loop with break.

3. Assigning the value ‘A’ to a memory location outside the initialized space, which could result in a unexpected behavior of the program.

Solutions:

1. We can store the value ‘A’ on the buf’s reserved memory location (like from buf[0] to buf[9]) then we are able to see a defined behavior of this code. So if we replace the line buf[4105] = ‘A’; with buf[9] = ‘A’ then this code should run fine without any unexpected output, but it could substantially change the meaning of the code.

2. Another possible solution would be to increase the size of the char buf to a value bigger than 4105. This change would likely have been closest to the programmers original intention.

Are there anymore problems or solutions? Please share with me.

Post a Comment