Main Content

Unsafe call to a system function

Unsanitized command argument has exploitable vulnerabilities

Description

This defect occurs when you use a function that invokes an implementation-defined command processor. These functions include:

  • The C standard system() function.

  • The POSIX popen() function.

  • The Windows® _popen() and _wpopen() functions.

Risk

If the argument of a function that invokes a command processor is not sanitized, it can cause exploitable vulnerabilities. An attacker can execute arbitrary commands or read and modify data anywhere on the system.

Fix

Do not use a system-family function to invoke a command processor. Instead, use safer functions such as POSIX execve() and WinAPI CreateProcess().

Examples

expand all

# include <string.h>
# include <stdlib.h>
# include <stdio.h>
# include <unistd.h>

enum { 
SIZE512=512,
SIZE3=3};

void func(char *arg)
{
	char buf[SIZE512];
	int retval=sprintf(buf, "/usr/bin/any_cmd %s", arg);
	
	if (retval<=0 || retval>SIZE512){
		/* Handle error */
		abort();
	}
	/* Use of system() to pass any_cmd with 
	unsanitized argument to command processor */
	
	if (system(buf) == -1) {
	/* Handle error */
  }
} 

In this example, system() passes its argument to the host environment for the command processor to execute. This code is vulnerable to an attack by command-injection.

Correction — Sanitize Argument and Use execve()

In the following code, the argument of any_cmd is sanitized, and then passed to execve() for execution. exec-family functions are not vulnerable to command-injection attacks.

# include <string.h>
# include <stdlib.h>
# include <stdio.h>
# include <unistd.h>

enum { 
SIZE512=512,
SIZE3=3};


void func(char *arg)
{
  char *const args[SIZE3] = {"any_cmd", arg, NULL};
  char  *const env[] = {NULL}; 
  
  /* Sanitize argument */
  
  /* Use execve() to execute any_cmd. */

  if (execve("/usr/bin/time", args, env) == -1) { 
    /* Handle error */
  }
} 

Result Information

Group: Security
Language: C | C++
Default: Off
Command-Line Syntax: UNSAFE_SYSTEM_CALL
Impact: High

Version History

Introduced in R2017b