Thursday, March 25, 2010

Avoid using unsafe string functions




Avoid using unsafe string functions (UsageOfStringFunctions.rule)


Description

This rule detects code that uses unsafe string functions from C library.

Benefits:

Prevents the use of functions which may cause buffer overflows.

According to David A. Wheeler (see reference below), "C functions users must avoid using dangerous functions that do not check bounds unless they've ensured that the bounds will never get exceed.

Functions to avoid in most cases (or ensure protection) include the functions strcpy(), strcat(), sprintf() (with cousin vsprintf()), and gets().

These should be replaced with functions such as strncpy(), strncat(), snprintf(), fgets(), respectively."

Example:

#include
void main( void )
{
char* str1 = "testcase";
char* str2 = "testcase";
char* str3=0;

str3 = strcat( str1, str2 ); // Violation
}

Repair:

#include
void main( void )
{
char* str1 = "testcase";
char* str2 = "testcase";
char* str3=0;

str3 = strncat( str1, str2, 16 ); // OK
}

References:
http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/dangers-c.html

Author
ParaSoft


Tags: Avoid, unsafe, string, function, unsafe string, C library, buffer overflows, dangerous functions, strncpy, strncat, snprintf, fgets


No comments:

Post a Comment

Labels