Main Content

MISRA C:2012 Rule 21.21

The Standard Library function system of <stdlib.h> shall not be used

Since R2021a

Description

Rule Definition

The Standard Library function system of <stdlib.h> shall not be used.

This rule comes from MISRA C™: 2012 Amendment 2.

Rationale

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

Polyspace Implementation

The checker flags uses of the Standard Library function system.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

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

enum { 
SIZE512=512,
SIZE3=3};

void func_noncompliant(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) { //Noncompliant
    /* Handle error */
  }
} 

void func_compliant(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) { //Compliant
      /* Handle error */
    }
} 

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

In the compliant version of the same function, func_compliant, the argument of any_cmd is sanitized, and then passed to the execve function for execution. exec-family functions are not vulnerable to command-injection attacks.

Check Information

Group: Standard Libraries
Category: Required
AGC Category: Required

Version History

Introduced in R2021a