Incorrect Behavior Order: Validate Before Canonicalize

The product validates input before it is canonicalized, which prevents the product from detecting data that becomes invalid after the canonicalization step.


Description

This can be used by an attacker to bypass the validation and launch attacks that expose weaknesses that would otherwise be prevented, such as injection.

Demonstrations

The following examples help to illustrate the nature of this weakness and describe methods or techniques which can be used to mitigate the risk.

Note that the examples here are by no means exhaustive and any given weakness may have many subtle varieties, each of which may require different detection methods or runtime controls.

Example One

The following code attempts to validate a given input path by checking it against an allowlist and then return the canonical path. In this specific case, the path is considered valid if it starts with the string "/safe_dir/".

String path = getInputPath();
if (path.startsWith("/safe_dir/"))
{
  File f = new File(path);
  return f.getCanonicalPath();
}

The problem with the above code is that the validation step occurs before canonicalization occurs. An attacker could provide an input path of "/safe_dir/../" that would pass the validation step. However, the canonicalization process sees the double dot as a traversal to the parent directory and hence when canonicized the path would become just "/".

To avoid this problem, validation should occur after canonicalization takes place. In this case canonicalization occurs during the initialization of the File object. The code below fixes the issue.

String path = getInputPath();
File f = new File(path);
if (f.getCanonicalPath().startsWith("/safe_dir/"))
{
  return f.getCanonicalPath();
}

See Also

Comprehensive Categorization: Insufficient Control Flow Management

Weaknesses in this category are related to insufficient control flow management.

SEI CERT Oracle Secure Coding Standard for Java - Guidelines 13. Input Output (FIO)

Weaknesses in this category are related to the rules and recommendations in the Input Output (FIO) section of the SEI CERT Oracle Secure Coding Standard for Java.

SEI CERT Oracle Secure Coding Standard for Java - Guidelines 00. Input Validation and Data Sanitization (IDS)

Weaknesses in this category are related to the rules and recommendations in the Input Validation and Data Sanitization (IDS) section of the SEI CERT Oracle Secure Codi...

Comprehensive CWE Dictionary

This view (slice) covers all the elements in CWE.

Weaknesses Introduced During Implementation

This view (slice) lists weaknesses that can be introduced during implementation.


Common Weakness Enumeration content on this website is copyright of The MITRE Corporation unless otherwise specified. Use of the Common Weakness Enumeration and the associated references on this website are subject to the Terms of Use as specified by The MITRE Corporation.