This is a code injection prevention cheat sheet by Semgrep, Inc. It contains code patterns of potential ways to run arbitrary code in an application. Instead of scrutinizing code for exploitable vulnerabilities, the recommendations in this cheat sheet pave a safe road for developers that mitigate the possibility of code injection in your code. By following these recommendations, you can be reasonably sure your code is free of code injection. Learn more about Code Injection vulnerability concepts.Documentation Index
Fetch the complete documentation index at: https://docs.semgrep.dev/llms.txt
Use this file to discover all available pages before exploring further.
Check your project using Semgrep
1. Executing or evaluating code
1.A. running code with VM module
Thevm module enables compiling and running code within V8 Virtual Machine contexts. The vm module is not secure. Do not use it to run untrusted code. If user input is used as a part of the code passed to vm functions, it can result in code injection. See VM (executing JavaScript) documentation.
The following list documents all potentially vulnerable functions that compile and execute code from the vm module:
vm.runInContextvm.runInNewContextvm.runInThisContextvm.compileFunctionnew vm.Scriptnew vm.SourceTextModule
References
Mitigation
- Don’t use the
vmmodule for running untrusted code. - If you need to use functions of the
vmmodule with non-literal values, ensure that the executed content cannot be controlled by external sources. - If it’s not possible, strip everything except alphanumeric characters from the input.
Semgrep rule
javascript.lang.security.audit.vm-injection.vm-runincontext-context-injection
1.B. eval or new Function
Theeval() or new Function() function evaluates JavaScript code represented as a string. Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval() or new Function().
Example:
References
- Never use eval() in MDN Web Docs documentation.
Mitigation
- Don’t use
eval()ornew Function()if possible. - If you need to use
eval()ornew Function()with non-literal values, ensure that the executed content cannot be controlled by external sources. - If it’s not possible, strip everything except alphanumeric characters from the input.
Semgrep rule
javascript.lang.security.detect-eval-with-expression.detect-eval-with-expression