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. Evaluating code
1.A. Evaluating code with eval
Evaluating code can be dangerous if dynamic content is used as input. If this input originates from outside of the program it can lead to a code injection vulnerability.
Examples:
References
Mitigation
- Don’t use
eval(),class_eval(),module_eval(), orinstance_eval()if possible. - If you need to use
eval(),class_eval(),module_eval(), orinstance_eval()with non-literal values, ensure that executed content is not controllable by external sources. - If it’s not possible, strip everything except alphanumeric characters from the input.
Semgrep rule
ruby.lang.security.no-eval.ruby-eval
1.B. Evaluating code with RubyVM::InstructionSequence
TheInstructionSequence class represents compiled instructions for the Ruby Virtual Machine. See details in RubyVM::InstructionSequence documentation. The RubyVM class itself is not intended for regular users. As the RubyVM class enables compiling code it may insecurely interpret user input. Providing user input to this class or its methods can result in a code injection vulnerability.
Example:
References
Mitigation
- Don’t use
RubyVM, orRubyVM::InstructionSequenceif possible. - If you need to use
RubyVMorRubyVM::InstructionSequencewith non-literal values or user input, ensure that inputs are from trusted sources.
Semgrep rule
ruby.lang.security.no-eval.ruby-eval