A handful of standard library calls turn untrusted input straight into running code or shell commands, and they appear in almost every serious code review finding list. This cheat sheet lists, per language, the eval, exec, shell and unsafe deserialisation functions that reviewers and static analysis rules should flag, the risk each one carries, the safer option, and the CWE entry to use when you raise the finding. It covers Python, JavaScript and Node.js, Java, PHP, C# and .NET, Ruby and Go. It is for developers, code reviewers and AppSec teams building SAST rules. It names functions only and contains no exploit strings. Broader secure coding practice is in the Secure Coding Guide and the mechanics of deserialisation attacks in the Insecure Deserialisation Guide; this page does not repeat them.
Key takeaways
- Three families cause most findings. Dynamic code evaluation (CWE-95, a child of CWE-94), OS command execution through a shell (CWE-78) and deserialisation of untrusted data (CWE-502).
- The safe option is usually a different API, not a filter. Parse data with a data-only parser, call programs with an argument list and no shell, and replace native object serialisers with JSON or another plain data format.
- Allowlists of types help but do not finish the job. MITRE notes that limiting types and gadgets alone is insufficient because new gadgets keep appearing; prefer formats that cannot create arbitrary objects.
- Some functions are beyond saving. Microsoft states BinaryFormatter is insecure and cannot be made secure, and from .NET 9 the in-box implementation throws on use; Python's documentation says the pickle module is not secure.
- Trusted input is rarer than it looks. Data from caches, queues, cookies, files and other services often crosses a trust boundary without the developer noticing, so review each call by where its data can come from.
How to use this template
- Turn the tables into rules: load the function names below into your SAST or code search tool as a [Organisation] dangerous function list, with the CWE as the rule tag. See the SAST Triage Guide for handling results.
- Triage by data source: for each hit, trace whether any argument can be influenced by a user, a network peer, a file upload or another service. Constant arguments are usually a low-priority finding.
- Apply the safer option: use the "Safer option" column as the default fix. Record any exception with an owner and review date.
- Gate new uses: start the rules in report-only mode on existing code, then block new occurrences in pull requests once the backlog is triaged.
- Keep it current: [Organisation] AppSec reviews the list when a language or framework version changes behaviour.
CWE quick reference
| CWE | Name | Typical functions |
|---|---|---|
| CWE-94 | Improper Control of Generation of Code (Code Injection) | Runtime compilation, script engines, dynamic includes |
| CWE-95 | Improper Neutralization of Directives in Dynamically Evaluated Code (Eval Injection) | eval, exec, Function constructor, instance_eval |
| CWE-78 | Improper Neutralization of Special Elements used in an OS Command (OS Command Injection) | system, shell_exec, child_process.exec, shell=True |
| CWE-88 | Improper Neutralization of Argument Delimiters in a Command | Argument lists built from user input, even without a shell |
| CWE-502 | Deserialization of Untrusted Data | pickle, unserialize, readObject, BinaryFormatter, Marshal.load |
| CWE-611 | Improper Restriction of XML External Entity Reference | XML parsers with external entity resolution on |
| CWE-1336 | Improper Neutralization of Special Elements Used in a Template Engine | Templates built from user input (Jinja2, Twig, FreeMarker and others) |
| CWE-470 | Use of Externally-Controlled Input to Select Classes or Code (Unsafe Reflection) | Class lookup or method dispatch by user-supplied name |
Python
| Function | Risk | Safer option | CWE |
|---|---|---|---|
eval(), exec(), compile() | Runs any Python code in the string | Parse the data you expect (json.loads, int()), or a lookup table of allowed operations | CWE-95 |
ast.literal_eval() | Does not run code, but Python's docs warn small inputs can exhaust memory or the C stack and do not recommend it for untrusted data | json.loads with size limits | CWE-400 |
pickle.load(), pickle.loads(), shelve, jsonpickle.decode() | Unpickling can execute arbitrary code; the docs say only unpickle data you trust | JSON or another data-only format; sign data with HMAC if pickle cannot be removed | CWE-502 |
yaml.load() with Loader=yaml.Loader or UnsafeLoader, yaml.unsafe_load() | Can construct arbitrary Python objects | yaml.safe_load(), with no custom constructors that create arbitrary objects | CWE-502 |
subprocess.run(..., shell=True), os.system(), os.popen() | Passes the string to a shell; the docs make quoting the application's job | subprocess.run([...]) with an argument list and the default shell=False; validate arguments | CWE-78 |
jinja2.Template(user_string), render_template_string() | User input becomes template code | Fixed template files; pass user data only as variables; autoescape on | CWE-1336 |
__import__(), importlib.import_module(), getattr() with user names | User chooses the code that runs | Map allowed names to functions in a dictionary | CWE-470 |
Python's subprocess documentation also notes that on Windows, batch files may be run in a system shell regardless of the arguments passed, so avoid calling .bat and .cmd files with untrusted arguments. See the Python Security Guide.
JavaScript and Node.js
| Function | Risk | Safer option | CWE |
|---|---|---|---|
eval(), new Function(), setTimeout or setInterval with a string | Executes the string as JavaScript; OWASP notes that with user input this leads to remote code execution | JSON.parse for data; pass functions, not strings, to timers | CWE-95 |
vm.runInNewContext(), vm.Script | Node's docs state node:vm is not a security mechanism and must not run untrusted code | Do not run untrusted code; if unavoidable, use a separate process or isolate with OS-level sandboxing | CWE-94 |
child_process.exec(), execSync(), spawn or execFile with shell: true | Runs through /bin/sh; Node's docs say never pass unsanitised user input | execFile() or spawn() with an argument array and no shell | CWE-78 |
Serialisers that revive functions (for example node-serialize unserialize) | Rebuilds functions from data | JSON.parse with schema validation | CWE-502 |
require() or import() with a user-controlled path | Loads attacker-chosen modules | Static imports or an allowlist map | CWE-94 |
innerHTML, document.write(), insertAdjacentHTML() (browser) | Turns strings into markup and script | textContent, framework binding, Trusted Types | CWE-79 |
Node.js also offers a permission model that can restrict child process use (--allow-child-process). See the Node.js Security Guide, the Node.js Permission Model Guide and the TypeScript and JavaScript Secure Coding Guide.
Java
| Function | Risk | Safer option | CWE |
|---|---|---|---|
ObjectInputStream.readObject(), readUnshared(), custom readObject, readResolve, readExternal | Native deserialisation can trigger gadget chains in the classpath | JSON or another data format into plain data objects; if unavoidable, an ObjectInputFilter or a resolveClass() allowlist | CWE-502 |
java.beans.XMLDecoder | OWASP quotes it as close to impossible to deserialise securely from untrusted input | A data-binding parser into fixed types | CWE-502 |
XStream before 1.4.17, YamlBeans before 1.16, SnakeYAML without SafeConstructor | Allow deserialisation of arbitrary classes | Upgrade and use allowlist or safe constructor modes as OWASP describes | CWE-502 |
Runtime.exec(String) | Deprecated since Java 18 as error-prone: splits on whitespace, so input can add arguments | ProcessBuilder or Runtime.exec(String[]) with each argument separate, plus validation | CWE-78, CWE-88 |
ScriptEngine.eval(), Spring Expression Language (SpEL) on user input | Evaluates user strings as code or expressions | Avoid; OWASP ASVS V1.3.2 asks applications to avoid eval and SpEL-style features | CWE-95 |
Class.forName(), reflection with user names | User selects classes or methods | Fixed mapping of allowed names | CWE-470 |
XML parsers (DocumentBuilderFactory, SAXParserFactory) with defaults | External entity resolution | Disable DTDs and external entities | CWE-611 |
To block deserialisation of your own classes that must be Serializable, OWASP recommends a final readObject() method that always throws. See the Oracle Java Secure Coding Guidelines Guide.
PHP
| Function | Risk | Safer option | CWE |
|---|---|---|---|
unserialize() | The PHP manual warns not to pass untrusted input regardless of allowed_classes, as code can be loaded and executed | json_decode() and json_encode() | CWE-502 |
eval(), create_function() (removed in PHP 8), assert() with a string (older versions) | Executes PHP code from strings | Remove; use real functions or a lookup table | CWE-95 |
system(), exec(), shell_exec(), passthru(), popen(), proc_open() with a string, backticks | Shell command execution | Native PHP functions (for example mkdir()); if a command is needed, escapeshellarg() per argument, never escapeshellcmd() alone | CWE-78, CWE-88 |
include, require with user-controlled paths | Loads and runs attacker-chosen files | Allowlist of fixed file names | CWE-98 |
| Phar archives opened through file functions on user paths | Phar metadata is deserialised | Reject the phar:// wrapper for user input | CWE-502 |
| Twig or Smarty templates built from user strings | Template injection | Fixed templates; user data as variables; sandbox mode where offered | CWE-1336 |
OWASP explains that escapeshellarg() keeps input to a single argument, while escapeshellcmd() still allows extra parameters. Neither stops a single argument that is itself an option, so validate values too.
C# and .NET
| Function | Risk | Safer option | CWE |
|---|---|---|---|
BinaryFormatter | Microsoft: insecure and cannot be made secure; from .NET 9 the in-box implementation throws on use | System.Text.Json, or follow Microsoft's BinaryFormatter migration guide | CWE-502 |
SoapFormatter, LosFormatter, NetDataContractSerializer, ObjectStateFormatter | Unrestricted polymorphic deserialisation, dangerous just like BinaryFormatter | System.Text.Json or DataContractSerializer with known types | CWE-502 |
Json.NET with TypeNameHandling other than None | The payload chooses the .NET type to create | TypeNameHandling.None; a custom serialisation binder if polymorphism is required | CWE-502 |
JavaScriptSerializer with a JavaScriptTypeResolver | Type selection from input | Use without a type resolver, or move to System.Text.Json | CWE-502 |
Process.Start with a shell (cmd.exe /c) or UseShellExecute = true | Shell interpretation of input | Fixed, fully qualified FileName, UseShellExecute = false, arguments via ArgumentList, plus validation | CWE-78 |
Roslyn scripting (CSharpScript.EvaluateAsync), CodeDomProvider on user input | Compiles and runs user code | Remove, or a constrained expression library with an allowlist | CWE-94 |
XmlDocument or XmlReader with an XmlResolver set | External entity resolution | Leave XmlResolver null and DTD processing prohibited | CWE-611 |
OWASP also advises keeping assemblies that contain known gadget types, such as System.Windows.Data.ObjectDataProvider, out of services that deserialise untrusted data.
Ruby and Go
Ruby
| Function | Risk | Safer option | CWE |
|---|---|---|---|
eval, instance_eval, class_eval, binding.eval with strings | Builds and runs Ruby code from strings | Blocks instead of strings; explicit method calls | CWE-95 |
send, public_send, constantize with user names | User selects methods or classes | Allowlist of names mapped to methods | CWE-470 |
system, exec, backticks, %x(), IO.popen, Process.spawn with a single string, Kernel#open with a leading pipe | OWASP lists most of these as ways to call system commands | Multi-argument form (system("cmd", arg)), File.open instead of Kernel#open | CWE-78 |
Marshal.load | Ruby's source docs say never unmarshal user-supplied or untrusted input | JSON or another simple format | CWE-502 |
YAML.unsafe_load (Psych), older YAML.load | Psych notes unsafe_load should not parse untrusted documents | YAML.safe_load with explicit permitted_classes | CWE-502 |
See the Ruby on Rails Security Guide.
Go
Go has no general eval, and the os/exec documentation states the package intentionally does not invoke the system shell. Risk comes from code that brings the shell or code loading back in.
| Function | Risk | Safer option | CWE |
|---|---|---|---|
exec.Command("sh", "-c", ...) or cmd.exe /c with user input | Reintroduces shell parsing | exec.Command(program, args...) with validated arguments | CWE-78 |
exec.Command with user-controlled program name or option-like arguments | Argument or program injection | Fixed program path; reject values starting with - or pass after -- where the program supports it | CWE-88 |
text/template for HTML output, or templates parsed from user strings | No contextual escaping; template injection | html/template, which Go documents as safe against code injection, with fixed template files | CWE-79, CWE-1336 |
plugin.Open on user-supplied paths | Loads arbitrary native code | Fixed, signed plugin locations or no plugins | CWE-94 |
See the Go Secure Coding Guide.
Framework mapping and measurement
| Function family | OWASP ASVS 5.0 | NIST SP 800-53 Rev 5 |
|---|---|---|
| Eval and dynamic code | V1.3.2 avoid eval() and dynamic code execution such as SpEL | SI-10 Information Input Validation |
| OS commands | V1.2.5 protect against OS command injection | SI-10 Information Input Validation |
| Template engines | V1.3.7 no templates built from untrusted input | SI-10 Information Input Validation |
| Deserialisation and XML | V1.5.1 restrictive XML parsers; V1.5.2 safe deserialisation with type allowlists | SA-11 Developer Testing and Evaluation |
Measure: dangerous function hits per 10,000 lines by language, share of hits triaged within 30 days, number of new uses blocked at pull request, and count of remaining native deserialisers on untrusted paths. See the Command Injection Guide for command execution in depth.
Practitioner checklist
- Load the function names above into SAST or code search rules, tagged with the CWE.
- Remove
BinaryFormatter,pickle,Marshal.loadandunserialize()from any path that handles external data. - Switch YAML loading to safe loaders (
yaml.safe_load,YAML.safe_load, SnakeYAMLSafeConstructor). - Replace shell calls with argument-list APIs and validate each argument.
- Ban eval-style functions in new code; record and review any exception.
- Build templates only from fixed files, passing user data as variables.
- Disable external entity resolution in every XML parser.
- Run rules in report-only mode first, then block new uses in pull requests.
- Review the list when a language runtime or framework changes behaviour.
Standards and references
- MITRE: CWE-95 Eval Injection
- MITRE: CWE-502 Deserialization of Untrusted Data
- MITRE: CWE-78 OS Command Injection
- OWASP: Deserialization Cheat Sheet
- OWASP: OS Command Injection Defense Cheat Sheet
- OWASP: Application Security Verification Standard 5.0
- Microsoft: Deserialization Risks in Use of BinaryFormatter and Related Types
- Python: pickle Python Object Serialization
Related NHI Mgmt Group resources: Secure Coding Guide · Insecure Deserialisation Guide · Command Injection Guide · SAST Triage Guide