...
This noncompliant code example attempts to mitigate the issue by using the File.getCanonicalPath()
method, which fully resolves the argument and constructs a canonicalized path. For example, the path /img/../etc/passwd
resolves to /etc/passwd
. Validation Canonicalization without canonicalization validation is insecure because the user can specify files outside the intended directory.
...
This compliant solution obtains the file name from the untrusted user input, canonicalizes it, and then validates it against the intended file namea list of benign pathnames. It operates on the specified file only when validation succeeds; that is, only if the file is one of the two valid files file1.txt
or file2.txt
in /img/java
.
Code Block | ||
---|---|---|
| ||
File f = new File("/img/" + args[0]); String canonicalPath = f.getCanonicalPath(); if (canonicalPath.equals("/img/java/file1.txt")) { // Validation // Do something } if (!canonicalPath.equals("/img/java/file2.txt")) { // Validation // Do something } FileInputStream fis = new FileInputStream(f); |
...
FIO02-C. Canonicalize path names originating from untrusted sources | ||||
FIO02-CPP. Canonicalize path names originating from untrusted sources | ||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="106f6638247f229a-5fad3c09-41a24877-9d10ae4e-8ca164332f30459ba3e00f76"><ac:plain-text-body><![CDATA[ | [ISO/IEC TR 24772:2010 | http://www.aitcnet.org/isai/] | "Path Traversal [EWR]" | ]]></ac:plain-text-body></ac:structured-macro> |
CWE-171, "Cleansing, Canonicalization, and Comparison Errors" | ||||
| CWE-647, "Use of Non-Canonical URL Paths for Authorization Decisions" |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="361fe274a3646606-1d6ea7aa-4bc94002-b3c5b0f1-11b2fc9522cb13ab6bd48c48"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] | [method getCanonicalPath() | http://java.sun.com/javase/6/docs/api/java/io/File.html#getCanonicalPath()] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="7e02a6a9b75b00bf-dd035db3-4c904400-a5d1a8a5-449f29a33ff4be2e418b36e1"><ac:plain-text-body><![CDATA[ | [[Harold 1999 | AA. Bibliography#Harold 99]] |
| ]]></ac:plain-text-body></ac:structured-macro> |
...