Data validation¶
Name¶
Data validation
Summary¶
Ensure that a system only receives and processes data elements that conform to its specification. If necessary, sanitise disallowed or insecure parts of any received data, or reject data that does not conform and thus cannot be processed by the system. For example, it should be verified that the data is of the correct type and contains all required fields, while removing any superfluous fields.
Parent¶
None
Problem¶
- Prevent that unexpected data is accepted and processed by the system
Solution¶
Each data element received from an uncontrolled entity, or via an uncontrolled channel, should be validated against some appropriate specification before processing that data element in any other way. The specification describes the requirements data elements must satisfy in order to be safely processable by the system, and may include syntactical as well as semantic rules. An example of a syntactical rule is that strings representing a date should be formatted as YYYY-MM-DD for the system to accept them. If such a string represents a birth date, an example of a semantic rule could be that it may not lie in the future and is not more than, for instance, 120 years in the past. Any superfluous characters preceding or trailing such a date string can be automatically removed. Another example of a syntactical validation is removing all disallowed fields from complex data structures, e.g. remove all tags but the allowed XML tags in a SOAP messages.
Roles¶
- Entity (: Entity) provides input data, possibly as part of an action request, to the
System - Enforcer (: Enforcement point) ensures that all incoming data is validated before any further processing by the
System - Validator (: Decision point) decides whether the received
datashould be allowed or not by validating it against some specification - Specification provider (: Information point) manages the specification(s) describing what data the system can process
- System (: Entity) processes the received data
Actions¶
- validate (: Action) the data received from
Entityagainst the appropriate specification - action (: Action) requested by the
Entityto which inputdatais provided as argument (optional) - get_specification (: Action) retrieve the specification against which the data at hand should be validated
Data elements¶
- data (: Data) the input as provided by the
Entity - canon_data (: Data) the validated input data transformed into canonical form
- Tags: Untampered
- type (: Data) identifies the type of specification required if multiple specifications exist within the system (optional)
- Tags: Untampered
- specification (: Data) describes what kind of data is allowed to be sent to the
System. For example, a set of rules such as allowed types and values ranges.- Tags: Untampered
- error (: Data) a message indicating why the input data failed validation which can be returned to the
Entity
Behaviour¶
- The
Entitytransmits data, possibly as part of an action request, to the system. - The
Enforcerintercepts the input from theEntityand forwards this to theValidatorfor validation before any further processing happens. - The
Validatorrequests the appropriate specification from theSpecification provider - Upon receiving the requested specification, the
Validatortransforms the received data into canonical form, possibly removing disallowed elements, and validates it against the appropriate specification. - If the data is valid, the
Validatorsends it, in its canonical form, to theEnforcerinforming it of this decision. Otherwise, theValidatorinforms theEnforcerto block the original request along with an error message describing how this data violated the specification. - If validated, the
Enforcerforwards the original request, now with the data in canonical form, to theSystem. Otherwise, it blocks the request and informs theEntityits provided data was invalid.

Role considerations¶
Separate data and action flow (Enforcer, System)¶
It is important to keep a clear separation between the data and action flow within a system.2
More precisely, it should be ensured that any received data is not interpreted by the System, or its entities, as being possible actions.
Attackers may exploit lack of such clear separation to inject additional actions to be executed.
For instance, if a system that consumes a user provided string as a, for example, SQL query this can lead to injection vulnerabilities through which attackers may obtain data they should not have access to.
For this example, a better option would be use prepared statements in which the input string provided by the user (or attacker) is, after correctly escaping it, strictly used as parameter in a pre-defined query, i.e. interpreted as data and not an action request.3 4
A system should only process action requests that concern actions that are explicitly provided by the system through some API.2
In other words, functions such as eval that allow to interpret strings at runtime should be avoided as they open up a system to a range of possible vulnerabilities.
Enforce validation on all incoming data (Enforcer)¶
Data can arrive at the System via many different channels from a wide range of (un)controlled entities.
The data validation strategy must ensure all incoming data is properly validated before any further processing takes place.2
In general it is easier to validate simpler or more structured data elements, compared to complex or data elements with little or no structure.
Therefore, it is advised to consider the need for validation when defining the necessary data types.
Two possible exceptions could be excluded from validation. First, any data that does not influence the control flow, e.g. data that is merely copied between entities before being stored and/or displayed in a UI. In this case, one must make sure that the system never interprets the data as instructions. Second, data that is exclusively operated on by controlled entities and is transmitted only over controlled channels. In either of these cases it should be clearly documented that the data at hand is not validated, and for any future changes to the system it should be re-evaluated whether these conditions still apply.
Use canonical data internally (Validator, System)¶
One way to ensure data validation cannot be bypassed is by designing the System such that it processes only data elements that conform to canonical form.2
Doing so forces incoming data to be transformed before the System can actually process it, providing a clear and convenient place to validate that data.
For example, an incoming string can be transformed to an instance of the date type it actually represents, thereby limiting the possibility of (accidental) incorrect changes when it is further processed.
Similarly, more complex data such as JSON should be transformed to a canonical form which contains only the expected fields, and ensures their values are within the allowed ranges.
Any superfluous fields in the Entity's original request can be discarded.
Validate in the back end (Entity, Validator)¶
While data validation at the client side, i.e. Entity, might be beneficial for performance or usability reasons, one should never rely on such validation for security decisions.
An attacker can typically bypass any client-side checks by, for example, using a modified client or changing the transmitted data between the client-side checks and its arrival at the system.1
Use existing libraries (Validator)¶
The Validator must process the, potentially unsafe, received data, as it is responsible to validate the data so that the System can safely process it afterwards.
Consequently, the Validator must be able to cope with any malicious or malformed data in a correct and secure manner.
Whenever possible one should use appropriate, existing libraries to validate data and avoid designing your own validation logic.1 2
For instance use the facilities provided by the used programming languages to ensure dates or URLs are correctly formatted.
Similarly, when parsing more complex data structures, e.g. XML documents, one should rely on existing parsers.
The References section contains some pointers to libraries that can be used in addition to, or in instead of, the data validation support offered by the programming language at hand.
While such libraries should allow to design a more robust Validator, they should be considered as uncontrolled entities themselves.
For each used library care should be taken to adhere to any assumptions it makes on its inputs or any constraints it imposes.
Serialised data (Validator)¶
When dealing with serialised data elements some additional issues should be considered. When receiving serialised data, its integrity should be verified before it is deserialised, e.g. using digital signatures.6 Furthermore, it is advised to use data formats such as JSON and XML instead of native language features.6 Finally, one should avoid to serialise sensitive data.7
Resource usage (Validator)¶
As the Validator needs to validate all incoming data it becomes a possible bottleneck for the performance of the system at hand.
Therefore, one should make sure that no single Entity (or group of entities) can absorb excessive resources that would result in requests from other entities not being processed (in a timely manner).
Log validation failures (Validator)¶
In order to detect and assess possible attacks it is advised to log data validation failures and, if necessary, notify system administrators, e.g. in case of a high number of failed validations in a short period.5 Care should be taken to not include sensitive data in the log entries and that the integrity of the logs is preserved while stored.
Authentication and Authorisation (System)¶
Data validation, as described in this pattern, aims to ensure that the System can process any data elements passed on to it without any undesired side-effects, e.g. part of the system crashing due to data in an unexpected format.
As such data validation does not provide any guarantees on whether the Entity should be allowed to request processing such data or, if applicable, should be allowed to request the action for which the data was an argument.
For example, while a request for certain account information (e.g. email address and payment details) may be properly formatted, this does not mean that the Entity should be allowed to query such information from another user's account.
To prevent such security issues this pattern should be combined with the measures necessary to deal with action requests from uncontrolled entities.
Re-validate data (System)¶
It is advised to explicitly re-validate data "nearby" code that relies on it.2 Such an additional validation provides an additional layer of security and can protect against any vulnerabilities present in the initial data validation or that arise from combining data obtained via different flows. Furthermore, it can help uncovering vulnerabilities that allow an attacker to tamper with data after if was validated (cf. canon_data).
Data considerations¶
Specification¶
Block and sanitise by default¶
Data validation should be based on an allowlisting approach, rather than blocklisting.2 1 The specification should thus only describe what (kinds of) data are allowed, instead of describing all the (kinds of) data which are not allowed. All data that does not conform to the allowlist should be automatically blocked or sanitised such that it does conform. An allowlist approach ensures that all inputs that are not explicitly covered are blocked or sanitised, thereby avoiding that the attacker can exploit any missed (corner) cases.
This may come with a cost with respect to usability or compatibility if the allowlist is too restrictive. But, in contrast, a blocklist approach would require exhaustively describing all data that should be blocked, a very difficult to even impossible task depending on the complexity of the expected data. Each faulty input data that is not covered by the blocklist, and is thus incorrectly passed on for processing, presents a possible vulnerability that an attacker may exploit.
Escape special characters¶
In most scenarios it will not be possible to block all special characters that attackers might exploit to trigger the execution of interpretation of data. In this case it should be ensured that all remaining special characters should be properly escaped following the escape syntax of the language or framework at hand. Note, that escaping is an additional security measure that should be applied in addition to sanitisation and validation, not as a sole defence measure.3
Enforce data size limits¶
In order to avoid resource exhaustion one should enforce an appropriate upper limit on the size of the incoming data.2 For example, if entities can upload files, the system should enforce a maximum file size and discard files exceeding this limit, without further processing. For simpler, data attributes such as strings a maximum number of characters should be defined as well as the set of allowed characters, whereas for numerical input (e.g. dates) the allowed ranges should be defined.1
Integrity¶
If an attacker can modify the specification used to validate input data the attacker might subsequently be able to get data validated that the System cannot correctly process.
Therefore, the specification should be protected against any unauthorised tampering when transmitted over an uncontrolled channel and in the Specification provider in case it persistently stores the specification.
type¶
The Validator may request a specific type of specification from the Specification provider to conduct its validation.
In this case care should be taken that an attacker cannot tamper with the requested type as this can influence the results of the validation.
If the Validator requests the specification via an uncontrolled channel additional measures to protect the type against tampering may be necessary.
canon_data¶
An attacker should not be able to modify canonical data after it was validated, as this could result in canonical data no longer conforming its specification.
If the canonical data is transmitted over uncontrolled channels or if it is stored by the System additional measures to protect it against unauthorised tampering may be needed.
Implementations¶
None
References¶
-
OWASP, ‘Input Validation Cheat Sheet’, OWASP Cheat Sheet Series. https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html ↩↩↩↩
-
I. Arce et al., ‘Avoiding the Top 10 Software Security Design Flaws’, IEEE, 2014. [Online]. Available: https://cybersecurity.ieee.org/blog/2015/11/13/avoiding-the-top-10-security-flaws/ ↩↩↩↩↩↩↩↩
-
OWASP, ‘Injection Prevention Cheat Sheet’. https://cheatsheetseries.owasp.org/cheatsheets/Injection_Prevention_Cheat_Sheet.html ↩↩
-
OWASP, ‘SQL Injection Prevention Cheat Sheet’. https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html ↩
-
P. Silva, ‘OWASP API Security Top 10 2019 - The Ten Most Critical API Security Risks’. [Online]. Available: https://owasp.org/www-project-api-security/ ↩
-
OWASP, ‘Deserialization Cheat Sheet’. https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html ↩↩
-
A. van der Stock, B. Glas, N. Smithline, and T. Gigler, ‘OWASP Top 10 - 2017: The Ten Most Critical Web Application Security Risks’, OWASP, 2017. [Online]. Available: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_2017_Project ↩