Skip to content
Injection Reviewed 2026-09-12

Dynamic code execution from untrusted input

Dynamic code execution becomes dangerous when untrusted input controls instructions that run with the application's privileges. Common review points include eval, exec, script engines and generated templates. Executing fixed, developer-controlled code is a different situation; first establish who controls the evaluated text and how it reaches the interpreter.

For broader language examples, continue to code injection using eval, command injection or template injection. These mechanisms have different interpreters and require different fixes.

Parse data instead of executing it

A Python application expects a small JSON configuration object. Enforce a body-size limit before this snippet and handle parse errors as invalid input.

Unsafe: evaluate the payload as Python.

settings = eval(payload)

Safer: parse the declared format and check the result.

import json

settings = json.loads(payload)
if not isinstance(settings, dict):
    raise ValueError('Expected a JSON object')
if set(settings) != {'mode'} or settings['mode'] not in ('demo', 'standard'):
    raise ValueError('Unsupported configuration')

The parser accepts data syntax; the application then restricts the fields and supported values. It does not invoke arbitrary Python expressions. Python documents the security implications of eval and the behavior of JSON parsing.

Check the fix

Use the harmless payload {"mode":"demo"} and assert its expected value. Reject a list, an unexpected field, an unknown mode and the non-JSON text 1 + 2. These checks do not need an executable attack payload. Keep the request-size limit in the test so parsing cannot consume unbounded resources.

A parser alone is not authorization. An allowed mode may still require a permission check, and a parsed path or URL needs validation at its eventual use. Do not assume that deleting dangerous words, limiting globals or using a different evaluation helper creates a general-purpose sandbox.

See the Python guide and TypeScript runtime validation guide for related examples. This reference explains a trust boundary; detection depends on the language, code path and enabled scanner rules.