Main Content

Use of externally controlled environment variable

Value of environment variable is from an unsecure source

Description

This defect occurs when functions that add or change environment variables, such as putenv and setenv, obtain new environment variable values from unsecure sources.

Risk

If the environment variable is tainted, an attacker can control your system settings. This control can disrupt an application or service in potentially malicious ways.

Fix

Before using the new environment variable, check its value to avoid giving control to external users.

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

#define _XOPEN_SOURCE
#define _GNU_SOURCE
#include "stdlib.h"

void taintedenvvariable(void)
{
    char* path = getenv("APP_PATH");
    putenv(path); //Noncompliant
}

In this example, putenv changes an environment variable. The path path has not been checked to make sure that it is the intended path.

Correction — Sanitize Path

One possible correction is to sanitize the path, checking that it matches what you expect.

#define _POSIX_C_SOURCE
#include <stdlib.h>
#include <string.h>

/* Function to sanitize a path */
const char * sanitize_path(const char* str) {
	/* secure allowlist of paths */
	static const char *const authorized_paths[] = {
		"/bin",
		"/usr/bin"
	};
	if (str != NULL) {
		for (int i = 0; i < sizeof(authorized_paths) / sizeof(authorized_paths[0]); i++)
		if (strcmp(authorized_paths[i], str) == 0) {
			return authorized_paths[i];
		}
	}
	return NULL;
}

void taintedenvvariable(void)
{
	const char* path = getenv("APP_PATH");
	path = sanitize_path(path);
	if (path != NULL) {
		if (setenv("PATH", path, /* overwrite = */1) != 0) {
			/* fatal error */
			exit(1);
		}
	}
} 

Result Information

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

Version History

Introduced in R2015b