Dynamic code execution APIs allow code to be provided and executed as strings at runtime.

Why is this an issue?

Some APIs enable the execution of code provided as strings at runtime. These APIs might be useful in specific meta-programming use-cases, but they also increase the risk of code injection. When user-controlled data is included in the code string, an attacker can inject and execute arbitrary instructions within the application.

PHP’s eval function executes the string passed to it as PHP code.

What is the potential impact?

When user-controlled data reaches a dynamic code execution API, an attacker can craft input that alters the intended logic of the program.

Arbitrary code execution

An attacker who can influence the code being executed can run arbitrary commands on the host system or within the database, potentially leading to full system compromise, data exfiltration, or privilege escalation.

How to fix it

Code examples

Noncompliant code example

function run(string $role): void {
    eval("handle_$role();"); // Noncompliant
}

Compliant solution

enum Role: string {
    case User = 'user';
    case Admin = 'admin';
}

function run(Role $role): void {
    $handlers = [
        Role::User->value => 'handle_user',
        Role::Admin->value => 'handle_admin',
    ];
    $handlers[$role->value]();
}

Resources

Standards