Join our Newsletter — 33% off our NHI Course
Home› Guides› Dangerous Functions by Language Cheat Sheet: Eval, Exec…
Template Application Security

Dangerous Functions by Language Cheat Sheet: Eval, Exec and Unsafe Loaders

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 12 min read
On this page

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

  1. 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.
  2. 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.
  3. Apply the safer option: use the "Safer option" column as the default fix. Record any exception with an owner and review date.
  4. 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.
  5. Keep it current: [Organisation] AppSec reviews the list when a language or framework version changes behaviour.

CWE quick reference

CWENameTypical functions
CWE-94Improper Control of Generation of Code (Code Injection)Runtime compilation, script engines, dynamic includes
CWE-95Improper Neutralization of Directives in Dynamically Evaluated Code (Eval Injection)eval, exec, Function constructor, instance_eval
CWE-78Improper Neutralization of Special Elements used in an OS Command (OS Command Injection)system, shell_exec, child_process.exec, shell=True
CWE-88Improper Neutralization of Argument Delimiters in a CommandArgument lists built from user input, even without a shell
CWE-502Deserialization of Untrusted Datapickle, unserialize, readObject, BinaryFormatter, Marshal.load
CWE-611Improper Restriction of XML External Entity ReferenceXML parsers with external entity resolution on
CWE-1336Improper Neutralization of Special Elements Used in a Template EngineTemplates built from user input (Jinja2, Twig, FreeMarker and others)
CWE-470Use of Externally-Controlled Input to Select Classes or Code (Unsafe Reflection)Class lookup or method dispatch by user-supplied name

Python

FunctionRiskSafer optionCWE
eval(), exec(), compile()Runs any Python code in the stringParse the data you expect (json.loads, int()), or a lookup table of allowed operationsCWE-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 datajson.loads with size limitsCWE-400
pickle.load(), pickle.loads(), shelve, jsonpickle.decode()Unpickling can execute arbitrary code; the docs say only unpickle data you trustJSON or another data-only format; sign data with HMAC if pickle cannot be removedCWE-502
yaml.load() with Loader=yaml.Loader or UnsafeLoader, yaml.unsafe_load()Can construct arbitrary Python objectsyaml.safe_load(), with no custom constructors that create arbitrary objectsCWE-502
subprocess.run(..., shell=True), os.system(), os.popen()Passes the string to a shell; the docs make quoting the application's jobsubprocess.run([...]) with an argument list and the default shell=False; validate argumentsCWE-78
jinja2.Template(user_string), render_template_string()User input becomes template codeFixed template files; pass user data only as variables; autoescape onCWE-1336
__import__(), importlib.import_module(), getattr() with user namesUser chooses the code that runsMap allowed names to functions in a dictionaryCWE-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

FunctionRiskSafer optionCWE
eval(), new Function(), setTimeout or setInterval with a stringExecutes the string as JavaScript; OWASP notes that with user input this leads to remote code executionJSON.parse for data; pass functions, not strings, to timersCWE-95
vm.runInNewContext(), vm.ScriptNode's docs state node:vm is not a security mechanism and must not run untrusted codeDo not run untrusted code; if unavoidable, use a separate process or isolate with OS-level sandboxingCWE-94
child_process.exec(), execSync(), spawn or execFile with shell: trueRuns through /bin/sh; Node's docs say never pass unsanitised user inputexecFile() or spawn() with an argument array and no shellCWE-78
Serialisers that revive functions (for example node-serialize unserialize)Rebuilds functions from dataJSON.parse with schema validationCWE-502
require() or import() with a user-controlled pathLoads attacker-chosen modulesStatic imports or an allowlist mapCWE-94
innerHTML, document.write(), insertAdjacentHTML() (browser)Turns strings into markup and scripttextContent, framework binding, Trusted TypesCWE-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

FunctionRiskSafer optionCWE
ObjectInputStream.readObject(), readUnshared(), custom readObject, readResolve, readExternalNative deserialisation can trigger gadget chains in the classpathJSON or another data format into plain data objects; if unavoidable, an ObjectInputFilter or a resolveClass() allowlistCWE-502
java.beans.XMLDecoderOWASP quotes it as close to impossible to deserialise securely from untrusted inputA data-binding parser into fixed typesCWE-502
XStream before 1.4.17, YamlBeans before 1.16, SnakeYAML without SafeConstructorAllow deserialisation of arbitrary classesUpgrade and use allowlist or safe constructor modes as OWASP describesCWE-502
Runtime.exec(String)Deprecated since Java 18 as error-prone: splits on whitespace, so input can add argumentsProcessBuilder or Runtime.exec(String[]) with each argument separate, plus validationCWE-78, CWE-88
ScriptEngine.eval(), Spring Expression Language (SpEL) on user inputEvaluates user strings as code or expressionsAvoid; OWASP ASVS V1.3.2 asks applications to avoid eval and SpEL-style featuresCWE-95
Class.forName(), reflection with user namesUser selects classes or methodsFixed mapping of allowed namesCWE-470
XML parsers (DocumentBuilderFactory, SAXParserFactory) with defaultsExternal entity resolutionDisable DTDs and external entitiesCWE-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

FunctionRiskSafer optionCWE
unserialize()The PHP manual warns not to pass untrusted input regardless of allowed_classes, as code can be loaded and executedjson_decode() and json_encode()CWE-502
eval(), create_function() (removed in PHP 8), assert() with a string (older versions)Executes PHP code from stringsRemove; use real functions or a lookup tableCWE-95
system(), exec(), shell_exec(), passthru(), popen(), proc_open() with a string, backticksShell command executionNative PHP functions (for example mkdir()); if a command is needed, escapeshellarg() per argument, never escapeshellcmd() aloneCWE-78, CWE-88
include, require with user-controlled pathsLoads and runs attacker-chosen filesAllowlist of fixed file namesCWE-98
Phar archives opened through file functions on user pathsPhar metadata is deserialisedReject the phar:// wrapper for user inputCWE-502
Twig or Smarty templates built from user stringsTemplate injectionFixed templates; user data as variables; sandbox mode where offeredCWE-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

FunctionRiskSafer optionCWE
BinaryFormatterMicrosoft: insecure and cannot be made secure; from .NET 9 the in-box implementation throws on useSystem.Text.Json, or follow Microsoft's BinaryFormatter migration guideCWE-502
SoapFormatter, LosFormatter, NetDataContractSerializer, ObjectStateFormatterUnrestricted polymorphic deserialisation, dangerous just like BinaryFormatterSystem.Text.Json or DataContractSerializer with known typesCWE-502
Json.NET with TypeNameHandling other than NoneThe payload chooses the .NET type to createTypeNameHandling.None; a custom serialisation binder if polymorphism is requiredCWE-502
JavaScriptSerializer with a JavaScriptTypeResolverType selection from inputUse without a type resolver, or move to System.Text.JsonCWE-502
Process.Start with a shell (cmd.exe /c) or UseShellExecute = trueShell interpretation of inputFixed, fully qualified FileName, UseShellExecute = false, arguments via ArgumentList, plus validationCWE-78
Roslyn scripting (CSharpScript.EvaluateAsync), CodeDomProvider on user inputCompiles and runs user codeRemove, or a constrained expression library with an allowlistCWE-94
XmlDocument or XmlReader with an XmlResolver setExternal entity resolutionLeave XmlResolver null and DTD processing prohibitedCWE-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

FunctionRiskSafer optionCWE
eval, instance_eval, class_eval, binding.eval with stringsBuilds and runs Ruby code from stringsBlocks instead of strings; explicit method callsCWE-95
send, public_send, constantize with user namesUser selects methods or classesAllowlist of names mapped to methodsCWE-470
system, exec, backticks, %x(), IO.popen, Process.spawn with a single string, Kernel#open with a leading pipeOWASP lists most of these as ways to call system commandsMulti-argument form (system("cmd", arg)), File.open instead of Kernel#openCWE-78
Marshal.loadRuby's source docs say never unmarshal user-supplied or untrusted inputJSON or another simple formatCWE-502
YAML.unsafe_load (Psych), older YAML.loadPsych notes unsafe_load should not parse untrusted documentsYAML.safe_load with explicit permitted_classesCWE-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.

FunctionRiskSafer optionCWE
exec.Command("sh", "-c", ...) or cmd.exe /c with user inputReintroduces shell parsingexec.Command(program, args...) with validated argumentsCWE-78
exec.Command with user-controlled program name or option-like argumentsArgument or program injectionFixed program path; reject values starting with - or pass after -- where the program supports itCWE-88
text/template for HTML output, or templates parsed from user stringsNo contextual escaping; template injectionhtml/template, which Go documents as safe against code injection, with fixed template filesCWE-79, CWE-1336
plugin.Open on user-supplied pathsLoads arbitrary native codeFixed, signed plugin locations or no pluginsCWE-94

See the Go Secure Coding Guide.

Framework mapping and measurement

Function familyOWASP ASVS 5.0NIST SP 800-53 Rev 5
Eval and dynamic codeV1.3.2 avoid eval() and dynamic code execution such as SpELSI-10 Information Input Validation
OS commandsV1.2.5 protect against OS command injectionSI-10 Information Input Validation
Template enginesV1.3.7 no templates built from untrusted inputSI-10 Information Input Validation
Deserialisation and XMLV1.5.1 restrictive XML parsers; V1.5.2 safe deserialisation with type allowlistsSA-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.load and unserialize() from any path that handles external data.
  • Switch YAML loading to safe loaders (yaml.safe_load, YAML.safe_load, SnakeYAML SafeConstructor).
  • 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

Related NHI Mgmt Group resources: Secure Coding Guide · Insecure Deserialisation Guide · Command Injection Guide · SAST Triage Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.