...
In the following noncompliant code, unsafe characters are used as part of a file name.:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <fcntl.h> #include <sys/stat.h> int main(void) { char *file_name = "»£???«"; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; int fd = open(file_name, O_CREAT | O_EXCL | O_WRONLY, mode); if (fd == -1) { /* Handle error */ } } |
...
Use a descriptive file name containing only the subset of ASCII previously described.:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <fcntl.h> #include <sys/stat.h> int main(void) { char *file_name = "name.ext"; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; int fd = open(file_name, O_CREAT | O_EXCL | O_WRONLY, mode); if (fd == -1) { /* Handle error */ } } |
...
This noncompliant code example is derived from 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'; |
...
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))); |
...
CERT C++ Secure Coding Standard | MSC09-CPP. Character encoding: Use subset of ASCII for safety |
CERT Oracle Secure Coding Standard for Java | IDS05-J. Use a subset of ASCII for file and path names |
MISRA - C:2012 | Directive 1.1 (required)Rule 3.2 Rule 4.1 (required) |
MITRE CWE | CWE-116, Improper encoding or escaping of output |
...