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. Unsafe Reflection
1.A. Using unsafe reflection with user input in Class.forName
TheClass.forName function returns the Class object for the class or interface with the name as a string. If an attacker supplies values that the application then uses to determine which class to instantiate or which method to invoke, the attacker can instantiate classes that the application developers did not intend. This can lead to unexpected behavior. For example, broken authentication that results in access to private data, or otherwise allow the attacker to obtain control of application behavior causing the application to behave in an unexpected manner.
Example:
References
Mitigation
- Try to avoid non-literal values in the first argument of
Class.forName()such asClass.forName(userInput + ".AttackerThread"). - If it is not possible, use an allowlist for inputs.
Semgrep rule
java.lang.security.audit.unsafe-reflection.unsafe-reflection