Kingdom: Input Validation and Representation

Input validation and representation problems ares caused by metacharacters, alternate encodings and numeric representations. Security problems result from trusting input. The issues include: "Buffer Overflows," "Cross-Site Scripting" attacks, "SQL Injection," and many others.

JSON Injection

Abstract
The method writes unvalidated input into JSON. This call could allow an attacker to inject arbitrary elements or attributes into the JSON entity.
Explanation
JSON injection occurs when:

1. Data enters a program from an untrusted source.


2. The data is written to a JSON stream.

Applications typically use JSON to store data or send messages. When used to store data, JSON is often treated like cached data and may potentially contain sensitive information. When used to send messages, JSON is often used in conjunction with a RESTful service and can be used to transmit sensitive information such as authentication credentials.

The semantics of JSON documents and messages can be altered if an application constructs JSON from unvalidated input. In a relatively benign case, an attacker may be able to insert extraneous elements that cause an application to throw an exception while parsing a JSON document or request. In a more serious case, such as ones that involves JSON injection, an attacker may be able to insert extraneous elements that allow for the predictable manipulation of business critical values within a JSON document or request. In some cases, JSON injection can lead to cross-site scripting or dynamic code evaluation.

Example 1: The following C# code uses JSON.NET to serialize user account authentication information for non-privileged users (those with a role of "default" as opposed to privileged users with a role of "admin") from user-controlled input variables username and password to the JSON file located at C:\user_info.json:


...

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;

writer.WriteStartObject();

writer.WritePropertyName("role");
writer.WriteRawValue("\"default\"");

writer.WritePropertyName("username");
writer.WriteRawValue("\"" + username + "\"");

writer.WritePropertyName("password");
writer.WriteRawValue("\"" + password + "\"");

writer.WriteEndObject();
}

File.WriteAllText(@"C:\user_info.json", sb.ToString());


Yet, because the JSON serialization is performed using JsonWriter.WriteRawValue(), the untrusted data in username and password will not be validated to escape JSON-related special characters. This allows a user to arbitrarily insert JSON keys, possibly changing the structure of the serialized JSON. In this example, if the non-privileged user mallory with password Evil123! were to append ","role":"admin to her username when entering it at the prompt that sets the value of the username variable, the resulting JSON saved to C:\user_info.json would be:


{
"role":"default",
"username":"mallory",
"role":"admin",
"password":"Evil123!"
}


If this serialized JSON file were then deserialized to a Dictionary object with JsonConvert.DeserializeObject() as so:


String jsonString = File.ReadAllText(@"C:\user_info.json");

Dictionary<string, string> userInfo = JsonConvert.DeserializeObject<Dictionary<string, strin>>(jsonString);


The resulting values for the username, password, and role keys in the Dictionary object would be mallory, Evil123!, and admin respectively. Without further verification that the deserialized JSON values are valid, the application will incorrectly assign user mallory "admin" privileges.
desc.dataflow.dotnet.json_injection
Abstract
The method writes unvalidated input to JSON. An attacker can inject arbitrary elements or attributes into the JSON entity.
Explanation
JSON injection occurs when:

1. Data enters a program from an untrusted source.


2. The data is written to a JSON stream.

Applications typically use JSON to store data or send messages. When used to store data, JSON is often treated like cached data and might contain sensitive information. When used to send messages, JSON is often used in conjunction with a RESTful service and can transmit sensitive information such as authentication credentials.

Attackers can alter the semantics of JSON documents and messages if an application constructs JSON from unvalidated input. In a relatively benign case, an attacker can insert extraneous elements that cause an application to throw an exception while parsing a JSON document or request. In more serious cases, such as those that involves JSON injection, an attacker can insert extraneous elements that allow for the predictable manipulation of business critical values within a JSON document or request. Sometimes JSON injection can lead to cross-site scripting or dynamic code evaluation.

Example 1: The following code serializes user account authentication information for non-privileged users (those with a role of "default" as opposed to privileged users with a role of "admin") from user-controlled input variables username and password to the JSON file located at ~/user_info.json:


...
func someHandler(w http.ResponseWriter, r *http.Request){
r.parseForm()
username := r.FormValue("username")
password := r.FormValue("password")
...
jsonString := `{
"username":"` + username + `",
"role":"default"
"password":"` + password + `",
}`
...
f, err := os.Create("~/user_info.json")
defer f.Close()

jsonEncoder := json.NewEncoder(f)
jsonEncoder.Encode(jsonString)
}


Because the code performs the JSON serialization using string concatenation, the untrusted data in username and password is not validated to escape JSON-related special characters. This allows a user to arbitrarily insert JSON keys, which can possibly change the serialized JSON structure. In this example, if the non-privileged user mallory with password Evil123! appended ","role":"admin when she entered her username, the resulting JSON saved to ~/user_info.json would be:


{
"username":"mallory",
"role":"default",
"password":"Evil123!",
"role":"admin"
}

Without further verification that the deserialized JSON values are valid, the application unintentionally assigns user mallory "admin" privileges.
desc.dataflow.golang.json_injection
Abstract
The method writes unvalidated input into JSON. This call could allow an attacker to inject arbitrary elements or attributes into the JSON entity.
Explanation
JSON injection occurs when:

1. Data enters a program from an untrusted source.


2. The data is written to a JSON stream.

Applications typically use JSON to store data or send messages. When used to store data, JSON is often treated like cached data and may potentially contain sensitive information. When used to send messages, JSON is often used in conjunction with a RESTful service and can be used to transmit sensitive information such as authentication credentials.

The semantics of JSON documents and messages can be altered if an application constructs JSON from unvalidated input. In a relatively benign case, an attacker may be able to insert extraneous elements that cause an application to throw an exception while parsing a JSON document or request. In a more serious case, such as ones that involves JSON injection, an attacker may be able to insert extraneous elements that allow for the predictable manipulation of business critical values within a JSON document or request. In some cases, JSON injection can lead to cross-site scripting or dynamic code evaluation.

Example 1: The following Java code uses Jackson to serialize user account authentication information for non-privileged users (those with a role of "default" as opposed to privileged users with a role of "admin") from user-controlled input variables username and password to the JSON file located at ~/user_info.json:


...

JsonFactory jfactory = new JsonFactory();

JsonGenerator jGenerator = jfactory.createJsonGenerator(new File("~/user_info.json"), JsonEncoding.UTF8);

jGenerator.writeStartObject();

jGenerator.writeFieldName("username");
jGenerator.writeRawValue("\"" + username + "\"");

jGenerator.writeFieldName("password");
jGenerator.writeRawValue("\"" + password + "\"");

jGenerator.writeFieldName("role");
jGenerator.writeRawValue("\"default\"");

jGenerator.writeEndObject();

jGenerator.close();


Yet, because the JSON serialization is performed using JsonGenerator.writeRawValue(), the untrusted data in username and password will not be validated to escape JSON-related special characters. This allows a user to arbitrarily insert JSON keys, possibly changing the structure of the serialized JSON. In this example, if the non-privileged user mallory with password Evil123! were to append ","role":"admin to her username when entering it at the prompt that sets the value of the username variable, the resulting JSON saved to ~/user_info.json would be:


{
"username":"mallory",
"role":"admin",
"password":"Evil123!",
"role":"default"
}


If this serialized JSON file were then deserialized to an HashMap object with Jackson's JsonParser as so:


JsonParser jParser = jfactory.createJsonParser(new File("~/user_info.json"));

while (jParser.nextToken() != JsonToken.END_OBJECT) {

String fieldname = jParser.getCurrentName();

if ("username".equals(fieldname)) {
jParser.nextToken();
userInfo.put(fieldname, jParser.getText());
}

if ("password".equals(fieldname)) {
jParser.nextToken();
userInfo.put(fieldname, jParser.getText());
}

if ("role".equals(fieldname)) {
jParser.nextToken();
userInfo.put(fieldname, jParser.getText());
}

if (userInfo.size() == 3)
break;
}

jParser.close();


The resulting values for the username, password, and role keys in the HashMap object would be mallory, Evil123!, and admin respectively. Without further verification that the deserialized JSON values are valid, the application will incorrectly assign user mallory "admin" privileges.
desc.dataflow.java.json_injection
Abstract
The method writes unvalidated input into JSON. This call could allow an attacker to inject arbitrary elements or attributes into the JSON entity.
Explanation
JSON injection occurs when:

1. Data enters a program from an untrusted source.


2. The data is written to a JSON stream.

Applications typically use JSON to store data or send messages. When used to store data, JSON is often treated like cached data and may potentially contain sensitive information. When used to send messages, JSON is often used in conjunction with a RESTful service and can be used to transmit sensitive information such as authentication credentials.

The semantics of JSON documents and messages can be altered if an application constructs JSON from unvalidated input. In a relatively benign case, an attacker may be able to insert extraneous elements that cause an application to throw an exception while parsing a JSON document or request. In a more serious case, such as ones that involves JSON injection, an attacker may be able to insert extraneous elements that allow for the predictable manipulation of business critical values within a JSON document or request. In some cases, JSON injection can lead to cross-site scripting or dynamic code evaluation.

Example 1: The following JavaScript code uses jQuery to parse JSON where a value comes from a URL:


var str = document.URL;
var url_check = str.indexOf('name=');
var name = null;
if (url_check > -1) {
name = decodeURIComponent(str.substring((url_check+5), str.length));
}

$(document).ready(function(){
if (name !== null){
var obj = jQuery.parseJSON('{"role": "user", "name" : "' + name + '"}');
...
}
...
});


Here the untrusted data in name will not be validated to escape JSON-related special characters. This allows a user to arbitrarily insert JSON keys, possibly changing the structure of the serialized JSON. In this example, if the non-privileged user mallory were to append ","role":"admin to the name parameter in the URL, the JSON would become:


{
"role":"user",
"username":"mallory",
"role":"admin"
}


This is parsed by jQuery.parseJSON() and set to a plain object, meaning that obj.role would now return "admin" instead of "user"
desc.dataflow.javascript.json_injection
Abstract
The method writes unvalidated input into JSON. This call could allow an attacker to inject arbitrary elements or attributes into the JSON entity.
Explanation
JSON injection occurs when:

1. Data enters a program from an untrusted source.


2. The data is written to a JSON stream.

Applications typically use JSON to store data or send messages. When used to store data, JSON is often treated like cached data and may potentially contain sensitive information. When used to send messages, JSON is often used in conjunction with a RESTful service and can be used to transmit sensitive information such as authentication credentials.

The semantics of JSON documents and messages can be altered if an application constructs JSON from unvalidated input. In a relatively benign case, an attacker may be able to insert extraneous elements that cause an application to throw an exception while parsing a JSON document or request. In a more serious case, such as ones that involves JSON injection, an attacker may be able to insert extraneous elements that allow for the predictable manipulation of business critical values within a JSON document or request. In some cases, JSON injection can lead to cross-site scripting or dynamic code evaluation.

Example 1: The following Objective-C code serializes user account authentication information for non-privileged users (those with a role of "default" as opposed to privileged users with a role of "admin") to JSON from user-controllable fields _usernameField and _passwordField:


...

NSString * const jsonString = [NSString stringWithFormat: @"{\"username\":\"%@\",\"password\":\"%@\",\"role\":\"default\"}" _usernameField.text, _passwordField.text];


Yet, because the JSON serialization is performed using NSString.stringWithFormat:, the untrusted data in _usernameField and _passwordField will not be validated to escape JSON-related special characters. This allows a user to arbitrarily insert JSON keys, possibly changing the structure of the serialized JSON. In this example, if the non-privileged user mallory with password Evil123! were to append ","role":"admin to her username when entering it into the _usernameField field, the resulting JSON would be:


{
"username":"mallory",
"role":"admin",
"password":"Evil123!",
"role":"default"
}


If this serialized JSON string were then deserialized to an NSDictionary object with NSJSONSerialization.JSONObjectWithData: as so:


NSError *error;
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];


The resulting values for username, password, and role in the NSDictionary object would be mallory, Evil123!, and admin respectively. Without further verification that the deserialized JSON values are valid, the application will incorrectly assign user mallory "admin" privileges.
desc.dataflow.objc.json_injection
Abstract
The method writes unvalidated input into JSON. This call could allow an attacker to inject arbitrary elements or attributes into the JSON entity.
Explanation
JSON injection occurs when:

1. Data enters a program from an untrusted source.


2. The data is written to a JSON stream.

Applications typically use JSON to store data or send messages. When used to store data, JSON is often treated like cached data and may potentially contain sensitive information. When used to send messages, JSON is often used in conjunction with a RESTful service and can be used to transmit sensitive information such as authentication credentials.

The semantics of JSON documents and messages can be altered if an application constructs JSON from unvalidated input. In a relatively benign case, an attacker may be able to insert extraneous elements that cause an application to throw an exception while parsing a JSON document or request. In a more serious case, such as ones that involves JSON injection, an attacker may be able to insert extraneous elements that allow for the predictable manipulation of business critical values within a JSON document or request. In some cases, JSON injection can lead to cross-site scripting or dynamic code evaluation.

Example : The following python code update a json file with an untrusted value comes from a URL:


import json
import requests
from urllib.parse import urlparse
from urllib.parse import parse_qs

url = 'https://www.example.com/some_path?name=some_value'
parsed_url = urlparse(url)
untrusted_values = parse_qs(parsed_url.query)['name'][0]

with open('data.json', 'r') as json_File:
data = json.load(json_File)

data['name']= untrusted_values

with open('data.json', 'w') as json_File:
json.dump(data, json_File)

...


Here the untrusted data in name will not be validated to escape JSON-related special characters. This allows a user to arbitrarily insert JSON keys, possibly changing the structure of the serialized JSON. In this example, if the non-privileged user mallory were to append ","role":"admin to the name parameter in the URL, the JSON would become:


{
"role":"user",
"username":"mallory",
"role":"admin"
}

The JSON file is now tampered with malicious data and the user has a privileged access of "admin" instead of "user"
desc.dataflow.python.json_injection
Abstract
The method writes unvalidated input into JSON. This call could allow an attacker to inject arbitrary elements or attributes into the JSON entity.
Explanation
JSON injection occurs when:

1. Data enters a program from an untrusted source.


2. The data is written to a JSON stream.

Applications typically use JSON to store data or send messages. When used to store data, JSON is often treated like cached data and may potentially contain sensitive information. When used to send messages, JSON is often used in conjunction with a RESTful service and can be used to transmit sensitive information such as authentication credentials.

The semantics of JSON documents and messages can be altered if an application constructs JSON from unvalidated input. In a relatively benign case, an attacker may be able to insert extraneous elements that cause an application to throw an exception while parsing a JSON document or request. In a more serious case, such as ones that involves JSON injection, an attacker may be able to insert extraneous elements that allow for the predictable manipulation of business critical values within a JSON document or request. In some cases, JSON injection can lead to cross-site scripting or dynamic code evaluation.
desc.dataflow.scala.json_injection
Abstract
The method writes unvalidated input into JSON. This call could allow an attacker to inject arbitrary elements or attributes into the JSON entity.
Explanation
JSON injection occurs when:

1. Data enters a program from an untrusted source.


2. The data is written to a JSON stream.

Applications typically use JSON to store data or send messages. When used to store data, JSON is often treated like cached data and may potentially contain sensitive information. When used to send messages, JSON is often used in conjunction with a RESTful service and can be used to transmit sensitive information such as authentication credentials.

The semantics of JSON documents and messages can be altered if an application constructs JSON from unvalidated input. In a relatively benign case, an attacker may be able to insert extraneous elements that cause an application to throw an exception while parsing a JSON document or request. In a more serious case, such as ones that involves JSON injection, an attacker may be able to insert extraneous elements that allow for the predictable manipulation of business critical values within a JSON document or request. In some cases, JSON injection can lead to cross-site scripting or dynamic code evaluation.

Example 1: The following Swift code serializes user account authentication information for non-privileged users (those with a role of "default" as opposed to privileged users with a role of "admin") to JSON from user-controllable fields usernameField and passwordField:


...
let jsonString : String = "{\"username\":\"\(usernameField.text)\",\"password\":\"\(passwordField.text)\",\"role\":\"default\"}"


Yet, because the JSON serialization is performed using string interpolation, the untrusted data in usernameField and passwordField will not be validated to escape JSON-related special characters. This allows a user to arbitrarily insert JSON keys, possibly changing the structure of the serialized JSON. In this example, if the non-privileged user mallory with password Evil123! were to append ","role":"admin to her username when entering it into the usernameField field, the resulting JSON would be:


{
"username":"mallory",
"role":"admin",
"password":"Evil123!",
"role":"default"
}


If this serialized JSON string were then deserialized to an NSDictionary object with NSJSONSerialization.JSONObjectWithData: as so:


var error: NSError?
var jsonData : NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding), options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary


The resulting values for username, password, and role in the NSDictionary object would be mallory, Evil123!, and admin respectively. Without further verification that the deserialized JSON values are valid, the application will incorrectly assign user mallory "admin" privileges.
desc.dataflow.swift.json_injection