...
Wiki Markup |
---|
As a result of the influence of MS-DOS, file names of the form {{xxxxxxxx.xxx}}, where x denotes an alphanumeric character, are generally supported by modern systems. On some platforms, file names are case sensitive; while on other platforms, they are case insensitive. VU#439395 is an example of a vulnerability resulting from a failure to deal appropriately with case sensitivity issues \[[VU#439395|AA. Bibliography#VU439395]\]. |
Noncompliant Code Example
...
In the following noncompliant code, unsafe characters are used as part of a file name.
...
An implementation is free to define its own mapping of the non-"safe" characters. For example, when tested on an Ubuntu Linux distribution, this noncompliant code example resulted in the following file name:
Code Block |
---|
A? |
Compliant Solution
...
Use a descriptive file name, containing only the subset of ASCII previously described.
Code Block | ||
---|---|---|
| ||
File f = new File("name.ext"); OutputStream out = new FileOutputStream(f); |
Noncompliant Code Example
...
This noncompliant code example is derived from rule FIO30-C. Exclude user input from format strings, except that a newline is removed on the assumption that fgets()
will include it.
Code Block | ||
---|---|---|
| ||
char myFilename[1000]; const char elimNewLn[] = "\n"; fgets(myFilename, sizeof(myFilename)-1, stdin); myFilename[sizeof(myFilename)-1] = '\0'; myFilename[strcspn(myFilename, elimNewLn)] = '\0'; public static void main(String[] args) throws Exception { if (args.length < 1) { // handle error } File f = new File(args[0]); OutputStream out = new FileOutputStream(f); // ... } |
No checks are performed on the file name to prevent troublesome characters. If an attacker knew this code was in a program used to create or rename files that would later be used in a script or automated process of some sort, they could choose particular characters in the output file name to confuse the later process for malicious purposes.
Compliant Solution
...
In this compliant solution, the program rejects file names that violate the guidelines for selecting safe characters.
Code Block | ||
---|---|---|
| ||
char myFilename[1000]; const char elimNewln[] = "\n"; const char badChars[] = "-\n\r ,;'\\<\""; do { fgets(myFilename, sizeof(myFilename)-1, stdin); myFilename[sizeof(myFilename)-1] ='\0'; myFilename[strcspn(myFilename, elimNewln)]='\0'; } while ( (strcspn(myFilename, badChars)) < (strlen(myFilename)));public static void main(String[] args) throws Exception { if (args.length < 1) { // handle error } String filename = args[0]; Pattern pattern = Pattern.compile("[A-Za-z0-9%&+,.:=_]"); Matcher matcher = pattern.matcher(filename); if (matcher.find()) { // filename contains bad chars, handle error } File f = new File(filename); OutputStream out = new FileOutputStream(f); // ... } |
Similarly, you must validate all file names originating from untrusted sources to ensure they contain only safe characters.
...