Static Code Analysis

Next to protection mechanisms that are active during program execution, static code analysis tools can help to prevent memory corruptions1). By analyzing the source code, dangerous function calls and control flow combinations can be discovered automatically and reported to the developer. Especially dangerous standard library functions are perfect candidates to be discovered by static code analysis. While there are multiple tools available2), the usage of the open-source application Flawfinder3) shall be demonstrated.

The very first buffer overflow example is used as an analysis target.

basic/control.c
// gcc -g -O0 -m32 -std=c99 control.c
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
 
struct User
{
    char name[8];
    bool is_admin;
};
 
int main()
{
    struct User user = {0};
 
    printf("Enter user name:\n");
    gets(user.name);
    if(strcmp(user.name, "admin") == 0)
        user.is_admin = true;
 
    if(user.is_admin)
        printf("Welcome back administrator!\n");
    else
        printf("Meh, hello %s. I was hoping for the administrator.\n", user.name);
 
    return 0;
}

Running Flawfinder on the source code file yields the following output.

$ flawfinder basic/control.c    
Flawfinder version 1.31, (C) 2001-2014 David A. Wheeler.
Number of rules (primarily dangerous function names) in C/C++ ruleset: 169
Examining basic/control.c

FINAL RESULTS:

basic/control.c:17:  [5] (buffer) gets:
  Does not check for buffer overflows (CWE-120, CWE-20). Use fgets() instead.
basic/control.c:8:  [2] (buffer) char:
  Statically-sized arrays can be improperly restricted, leading to potential
  overflows or other issues (CWE-119:CWE-120). Perform bounds checking, use
  functions that limit length, or ensure that the size is larger than the
  maximum possible length.

ANALYSIS SUMMARY:

Hits = 2
Lines analyzed = 27 in approximately 0.00 seconds (6493 lines/second)
Physical Source Lines of Code (SLOC) = 21
Hits@level = [0]   0 [1]   0 [2]   1 [3]   0 [4]   0 [5]   1
Hits@level+ = [0+]   2 [1+]   2 [2+]   2 [3+]   1 [4+]   1 [5+]   1
Hits/KSLOC@level+ = [0+] 95.2381 [1+] 95.2381 [2+] 95.2381 [3+] 47.619 [4+] 47.619 [5+] 47.619
Minimum risk level = 1
Not every hit is necessarily a security vulnerability.
There may be other security vulnerabilities; review your code!
See 'Secure Programming for Linux and Unix HOWTO'
(http://www.dwheeler.com/secure-programs) for more information.

Flawfinder reports the obviously dangerous usage of gets(). Additionally, the tool recommends to check the bounds of the statically allocated array.



← Back to Control-flow Integrity (CFI) Overview

1) M. Alvares, T. Marwala and F. B. de Lima Neto, „Applications of computational intelligence for static software checking against memory corruption vulnerabilities,“ 2013 IEEE Symposium on Computational Intelligence in Cyber Security (CICS), Singapore, 2013, pp. 59-66.