Strings and Integers

From OWASP
Revision as of 13:45, 6 November 2007 by EoinKeary (Talk | contribs)

Jump to: navigation, search

Contents

Introduction:

Strings are not a defined Type in C or C++ but simply a contigous array of characters terminated by a null (\0) character The length of the string is the amount of characters which preseed the null character. C++ does contain template classes which address this feature of the programming language: std::basic_string and std::string These classes address some security issues but not all.

|W|E|L|C|O|M|E|\0|


Common String Errors

Common string errors can be related to mistakes in implementation which may cause drastic security and availability issues. C/C++ do not have the comfort other programming languages provide such as Java and C# .NET relating to buffer overflows and such due to a String Type not being defined.

Common issues include:

  1. Input validation errors
  2. Unbounded Errors
  3. Truncation issues
  4. Out-of-bounds writes
  5. String Termination Errors
  6. Off-by-one errors`

Some of the issues mentioned above have been covered in the "Reviewing Code for Buffer Overruns and Overflows" section previously in this guide.

Unbounded Errors

String Copies

Occur when data is copied from a unbounded source to a fixed length character array

void main(void) {
 char Name[10];
 puts("Enter your name:");
 gets(Name); <-- Here the name input by the user can be of arbitary length over running the Name array.
...
 }

String Termination Errors

Failure to properly terminate strings with a null can result in system failure

int main(int argc, char* argv[]) {
 char a[16];
 char b[16];
 char c[32];
 strncpy(a, "0123456789abcdef", sizeof(a));
 strncpy(b, "0123456789abcdef", sizeof(b));
 strncpy(c, a, sizeof(c));
}


It is recommended that it should be verified that the following is used:

strncpy() instead of strcpy()
snprintf() instead of sprintf()
fgets() instead of gets()


Off by one error

(Looping through arrays should be looped in a n-1 manner as we must remember arrays and vectors start as 0. This is not specific to C/C++ but Java and C# also.)

Off-by-one errors are common to looping functionlity wherein a looping functionality is performed on an object inorder to manipulate the contents of an object such as copy or add information. The off-by-one error is a result of an error on the loop counting functionality.

for (i = 0; i < 5; i++) {
   /* Do Stuff */
}

Here i starts with a value of 0, it then increments to 1, then 2,3 & 4. When i reaches 5 then the condition i<5 is false and the loop terminates.

If the condition was set such that i<=5 (less than or equal to 5) the loop wont terminate until i reaches 6 which may not be what is intended.

Also counting from 1 instead of 0 can cause similar issues as there would be one less iterations. Both of these issues relate to a off-by-one error where the loop either under or over counts.