Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
#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 */
   }
}

Non-Compliant Code Example

...

(File Name)

This non-compliant 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
bgColor#FFCCCC
char myFilename[1000];
char const elimNewLn[] = "\n";

fgets(myFilename, sizeof(myFilename)-1, stdin);
myFilename[sizeof(myFilename)-1] = '\0';
myFilename[strcspn(myFilename, elimNewLn)] = '\0';

This 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.  No checks are performed on the filename 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 filename to confuse the later process for malicious purposes.

Compliant Solution

...

(File Name)

In this compliant solution, the program rejects filenames that violate the guidelines for selecting safe characters.

Code Block
bgColor#ccccFF
char myFilename[1000];
char const elimNewln[] = "\n";
char const 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)));

In this solution, the program does not accept a filename that violates the guidelines above.  As the solution shows, you probably have to find each location in code by hand that a user is allowed to specify a filename and solve it with a similar check as aboveSimilarly, you must provide validate all filenames originating from untrusted sources to ensure they contain only safe characters.

Risk Assessment

Failing to use only the subset of ASCII guaranteed to work can result in misinterpreted data.

...