is your code secure against the threat of buffer overflow vulnerability? -凯发k8网页登录

buffer overflows have plagued the c/c development community for years. while the c language empowers developers to access memory directly via pointers, it also opens the door to overflow problems. safe coding practices help developers avoid buffer overflows to some extent (at the cost of performance), but sometimes buffer overflows can be subtle and complex to find and resolve.

often, only when a buffer overflow escapes into production and is discovered as a security flaw (or worse, exploited) does one realize how subtly it was introduced in the code. remember the heartbleed bug in the popular openssl library? the most recent or the provide good examples of the issue.

what is a buffer overflow?

broadly speaking, a buffer overflow occurs when an operation that writes data to an allocated buffer exceeds the buffer boundaries. in doing so, the operation accesses adjacent memory locations that it should not. let’s view an example:

#define maxsize 100
.
.
char localbuf [maxsize]
.
.
gets (localbuf)

the gets() function does not allow you to check if the data read to localbuf has less than maxsize characters. you rely on the sender of the data to stay within this limit. a malicious user can easily overflow the buffer by sending data greater than maxsize characters and access adjacent regions in the stack.

chart showing storage allocated to localbuf and the area that can be accessed by overflowing localbuf.

how serious are buffer overflows?

the severity of a buffer overflow depends on what is stored in the adjacent memory regions. when you call a function in your code, all data relevant to the call are stored in adjacent regions on the call stack.

consider these two situations:

  • area adjacent to the overflowing buffer stores another local variable or a function parameter
    the variable value is corrupted because of the buffer overflow. you can encounter the corrupted value causing a run-time error elsewhere in your code. the corrupted value can also lead to a silent incorrect behavior - one that can escape detection. you end up with unsafe and unreliable code.
  • area adjacent to the overflowing buffer stores return address of the function
    the call stack also stores the address that the program jumps to when the called function returns. this address is compromised because of the buffer overflow. an attacker can overflow your buffer precisely enough so that your program, instead of returning to the call site, jumps to the location of malicious code. if your program has sufficient privileges, this malicious code can take control of your application and lead to exploitation.

how difficult is it to avoid buffer overflows?

you might say that the issue shown above is easy to avoid. before using unsecured functions such as gets(), check the buffer size. or, even better, do not use such unsecured functions at all.

consider another example of a buffer overflow and see how subtle it can be. this code snippet comes from the libpng image decoder, used by several applications including mozilla and some versions of internet explorer (cf. ).

if (!(png_ptr->mode & png_have_plte)) {
		/* should be an error, but we can cope with it */
		png_warning(png_ptr, "missing plte before trns");
	}
	else if (length > (png_uint_32)png_ptr->num_palette) {
		png_warning(png_ptr, "incorrect trns chunk length");
		png_crc_finish(png_ptr, length);
		return;
	}
	...
	png_crc_read(png_ptr, readbuf, (png_size_t)length);

on first glance, the following check:

length > (png_uint_32)png_ptr->num_palette

is exactly what is needed to avoid a buffer overflow when you use length. however, the snag here is that the check occurs in an else if block. the if block preceding the else if block performs an unrelated check on png_ptr->mode; if that previous check fails, control goes outside the if - else if chain with just a warning. the second check on the variable length is not performed at all.

in other words, a subset of execution paths exists where, despite the check, a buffer overflow can occur. an issue as subtle as this can be detected only if you can keep track of all execution paths in the program. and that is precisely what polyspace static analysis does.

how can you use polyspace static analysis to avoid buffer overflows?

there is a plethora of static analysis tools that claim to check for buffer overflows, and they do so using different heuristics or some form of data flow analysis. however, this is an insufficient approach since safety- and security-critical systems cannot afford to have any false negatives (i.e., a missed instance of a buffer overflow) in the deployed embedded software.

polyspace® products take a two-step approach to address this challenge. this approach is in alignment with the requirements of the software development workflow.

polyspace bug finder™ applies fast formal methods to enable developers to comply with coding guidelines, which helps avoid buffer overflows. polyspace bug finder provides various checkers that not only identify buffer overflow issues, but also other potential constructs that can lead to and exploit a buffer overflow vulnerability. this early and quick feedback enables the development teams to address such issues before they propagate further downstream into the software builds, saving testing and debugging resources.

for example, if you are following a security standard such as cwe or cert c, you can use polyspace bug finder to adhere to the rules. the following cwe ids, cert c rules, and iso 17961 secure coding guidelines handle buffer overflows:

  • cwe
    • : stack-based buffer overflow
    • : improper validation of array index
  • cert c
    • : enforce limits on integer values originating from tainted sources
    • arr30-c: do not form or use out-of-bounds pointers or array subscripts
  • iso/iec 17961
    • invptr: forming or using out-of-bounds pointers or array subscripts
    • taintformatio: using a tainted value to write to an object using a formatted input or output function

you also have the misra c:2012 directive 4.14 that states, “the validity of values received from external sources shall be checked.”

polyspace bug finder, through its , provides extensive support for detecting and avoiding stack-based buffer overflows.

  • you can use an index to go beyond the size of the array.
    int i;
        int fib[10];
     
        for (i = 0; i < 10; i  ) 
           {
            if (i < 2) 
                fib[i] = 1;
             else 
                fib[i] = fib[i-1]   fib[i-2];
           }
        printf("the 10-th fibonacci number is %i .\n", fib[i]);   
    
  • you can use a pointer assigned to a block of memory to access memory beyond that block.
    int arr[10];
     int *ptr=arr;
     for (int i=0; i<=9;i  )
       {
        ptr  ;
        *ptr=i;
        /* defect: ptr out of bounds for i=9 */
       }
    
  • : you can obtain a variable from an external source and use it as array index without checking if the value is less than array size.
    #define maxsize 100 
    int arr[maxsize];
      
      int func(int num) {
      int localvar;
      /* inermediate code where no check on num is done */
    arr[num]= localvar;
    }
    
  • : you use string manipulation functions such as sprintf() and write strings that are too large for the buffer that you are writing to.
    char buffer[20];
    char *fmt_string = "this is a very long string, it does not fit in the buffer";
    sprintf(buffer, fmt_string);
    
  • : when you use functions such as sscanf, your string format specifier indicates a string size greater than the storage area allocated for the string.
       
    char buf[32];
    sscanf(str[1], "3c", buf);
    

despite the polyspace bug finder analysis, a few subtle and complex buffer overflow defects can remain in the source code, since polyspace bug finder is not a sound tool (i.e., it can have false negatives). this is where polyspace code prover™ can help, as it is an abstract interpretation-based formal semantic analysis tool that can exhaustively verify the dynamic run-time behavior.

how can you use polyspace code prover to avoid buffer overflows?

in our previous example, despite a check on length, a buffer overflow could potentially creep in unnoticed through one control path. you encounter more complexity when such paths are dependent on the run-time information.

polyspace code prover performs precisely this function. the polyspace code prover run-time checks, and , look for potential buffer overflows along all execution paths for all combinations of inputs and other variables in your program. this means that in the example discussed earlier:

if (!(png_ptr->mode & png_have_plte)) {
		/* should be an error, but we can cope with it */
		png_warning(png_ptr, "missing plte before trns");
	}
	else if (length > (png_uint_32)png_ptr->num_palette) {
		png_warning(png_ptr, "incorrect trns chunk length");
		png_crc_finish(png_ptr, length);
		return;
	}
	...
	png_crc_read(png_ptr, readbuf, (png_size_t)length);

polyspace code prover can identify that the variable length is not bounded along all paths. the corresponding polyspace bug finder checkers, array access out of bounds and pointer access out of bounds, look for such issues, too. they report when at least one control path causing an overflow is found. however, these checkers do not perform an exhaustive analysis. you must use a code verification tool such as polyspace code prover and ensure that all pointer accesses are green and are therefore never proven to result in a buffer overflow.

such detailed analysis is ideal before code reviews and unit testing, as you can reduce and optimize your test cases based on the run-time data provided by polyspace code prover. thus, using both polyspace bug finder and polyspace code prover, you can ensure safety and security against the malignant threat of buffer overflows.

other real-world examples

references

网站地图