Do not use eval()

ID

php.no_use_eval

Severity

low

Resource

Risky Values

Language

Php

Tags

CWE:95, NIST.SP.800-53, OWASP:2021:A3, PCI-DSS:6.5.1

Description

Avoid dynamic evaluation of code, such as eval(code).

If the user has control over evaluated code (because the code is concatenated with user data), this leads to 'script injection' vulnerabilities, which could end in well-known security attacks.

Rationale

The eval() function in PHP takes a string as input and executes it as PHP code. This creates a significant security risk, as any unsanitized user input passed into eval() can lead to code injection.

For example, consider the following insecure PHP code:

<?php

$user_input = $_GET['code'];
eval($user_input);
?>

If an attacker supplies the following input in the URL:

code=phpinfo();

It would execute the phpinfo() function, potentially exposing sensitive server information. A more dangerous payload could allow an attacker to gain full control over the system.

Additionally, eval() makes debugging and maintaining the code more complex, as it introduces dynamically generated code that is harder to analyze statically.

Using eval() to parse JSON strings is unsafe and can lead to security vulnerabilities, such as code injection.

Remediation

To eliminate the risks associated with eval(), consider the following safer alternatives:

Sanitize and Validate Input:

If user input is required, use strict validation and whitelisting techniques to ensure only expected values are accepted.

Use Safer String Parsing Techniques:

If eval() is being used for configuration handling, consider using json_decode() or parse_ini_file().

Example (safe JSON decoding):

<?php
    $json_string = '{"name": "John", "age": 30}';
    $data = json_decode($json_string, true);
    echo "User: " . $data['name'];
?>

Avoid Dynamic Code Execution:

If eval() is used for dynamic function calls, consider using call_user_func() or call_user_func_array().

Example (safe function execution):

<?php
    function greet($name) {
        return "Hello, " . htmlspecialchars($name);
    }

    $function_name = 'greet';
    $parameter = 'Alice';

    if (function_exists($function_name)) {
        echo call_user_func($function_name, $parameter);
    }
?>

By removing eval() from the codebase, PHP applications can significantly reduce the risk of code injection attacks and improve overall security.

Configuration

This detector does not need any configuration.

References