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.

Python’s eval, exec, and compile functions execute strings as Python code in the current execution context.

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

def run(role):
    eval(f"handle_{role}()")  # Noncompliant

Compliant solution

from enum import Enum

class Role(Enum):
    USER = "user"
    ADMIN = "admin"

HANDLERS = {
    Role.USER: handle_user,
    Role.ADMIN: handle_admin,
}

def run(role: Role):
    HANDLERS[role]()

Resources

Standards