Main Content

Loop bounded with tainted value

Loop controlled by a value from an unsecure source

Description

This defect occurs when a loop is bounded by values obtained from unsecure sources.

Risk

A tainted value can cause over looping or infinite loops. Attackers can use this vulnerability to terminate your program or cause other unintended behavior.

Fix

Before starting the loop, validate unknown boundary and iterator values by validating their low bounds and high bounds. Execute the loop only when both the lower bound and upper bound of the tainted values are validated. Explicitly check that both the lower and upper bound of the tainted value is acceptable. Alternatively, saturate or clamp the tainted value.

Extend Checker

By default, Polyspace® assumes that data from external sources are tainted. See Sources of Tainting in a Polyspace Analysis. To consider any data that does not originate in the current scope of Polyspace analysis as tainted, use the command line option -consider-analysis-perimeter-as-trust-boundary.

Examples

expand all

#include<stdio.h>
enum {
    SIZE10  =  10,
    SIZE100 = 100,
    SIZE128 = 128
};

int taintedloopboundary(void) {
    int count;
    scanf("%d", &count);
    int res = 0;
    for (int i=0 ; i < count; ++i) {//Noncompliant
        res += i;
    }
    return res;
}

In this example, the function uses a user input to loop count times. count could be any number because the value is not checked before starting the for loop.

Correction: Clamp Tainted Loop Control

One possible correction is to clamp the tainted loop control. To validate the tainted loop variable count, this example limits count to a minimum value and a maximum value by using inline functions min and max. Regardless of the user input, the value of count remains within a known range.

#include<stdio.h>
#include<algorithm>
#define MIN 50
#define MAX 128
static  inline int max(int a, int b) { return a > b ? a : b;}
static inline int min(int a, int b) { return a < b ? a : b; }

int taintedloopboundary(void) {
	int count;
	scanf("%d", &count);
	int res = 0;
	count = max(MIN, min(count, MAX));
	for (int i=0 ; i<count ; ++i) { 
		res += i;
	} 
	return res;
}
Correction — Check Tainted Loop Control

Another possible correction is to check the low bound and the high bound of the tainted loop boundary variable before starting the for loop. This example checks the low and high bounds of count and executes the loop only when count is between 0 and 127.

#include<stdio.h>

enum {
    SIZE10  =  10,
    SIZE100 = 100,
    SIZE128 = 128
};


int taintedloopboundary(void) {
    int count;
    scanf("%d", &count);
    int res = 0;

    if (count>=0 && count<SIZE128) {
        for (int i=0 ; i<count ; ++i) { 
            res += i;
        }
    }
    return res;
}

Result Information

Group: Tainted Data
Language: C | C++
Default: Off
Command-Line Syntax: TAINTED_LOOP_BOUNDARY
Impact: Medium

Version History

Introduced in R2015b