JSON Injection
ID |
java.json_injection |
Severity |
high |
Resource |
Injection |
Language |
Java |
Tags |
CWE:116, NIST.SP.800-53, OWASP:2021:A3, PCI-DSS:6.5.1 |
Rationale
JSON Injection is a critical vulnerability in web applications that utilize JSON for transmitting data. When user inputs are not properly validated or sanitized, they can be used to execute an injection attack. This vulnerability arises when dynamic content manipulation is performed using user inputs that are directly injected into JSON data structures without adequate checks.
For instance, consider the following Java code snippet:
import org.json.JSONObject;
public class JsonInjectionExample {
public static void main(String[] args) {
String userInput = "\"name\": \"John\", \"role\": \"admin\""; // Simulated user input
JSONObject jsonObject = new JSONObject("{\"user\":{" + userInput + "}}");
System.out.println(jsonObject.toString());
}
}
---
In the above example, the `userInput` string is directly concatenated into the JSON object construction. If `userInput` comes from an untrusted source, an attacker could manipulate the data, altering the expected JSON structure, potentially leading to JS execution, unintentional data leakage, or corruption.
== Remediation
To remediate JSON Injection vulnerabilities, it is essential to ensure that all user inputs are appropriately sanitized and validated before incorporating them into structured JSON objects. Several strategies can be used in Java to prevent such issues:
1. **Use JSON Libraries:** Prefer using libraries that automatically handle escaping of JSON characters, such as org.json, Gson, or Jackson.
2. **Input Validation and Sanitization:** Perform thorough input validation to reject or sanitize dangerous characters or malformed inputs.
3. **JSON Encoding:** Use JSON-specific encoding functions provided by libraries to safely construct JSON objects.
4. **Whitelisting:** Implement whitelisting mechanisms to restrict the types and formats of data that are allowed.
Here’s how the previous example can be remediated:
[.source, java]
import org.json.JSONObject;
public class JsonSafeExample { public static void main(String[] args) { String userInput = "\"name\": \"John\", \"role\": \"admin\""; // Simulated user input JSONObject jsonObject = new JSONObject();
// Input validation/sanitization should be applied here userInput = sanitizeInput(userInput);
jsonObject.put("user", new JSONObject(userInput)); System.out.println(jsonObject.toString()); }
public static String sanitizeInput(String input) { // Example sanitization logic, customize as needed return input.replaceAll("[^a-zA-Z0-9,:\"\'{} ]", ""); } } ---
In this remediation example, the input is sanitized before being inserted into the JSON object, reducing the risk of JSON Injection. Implementing validation and leveraging safe libraries are crucial for avoiding vulnerabilities.