You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 66 Next »

Many file related security vulnerabilities result from a program accessing a file object different from the one intended. In the C programming language, character-based filenames are bound to underlying file objects in name only. Filenames provide no information regarding the nature of the file object itself. Furthermore, the binding of a filename to a file object is reasserted every time the filename is used in an operation. File descriptors are bound to underlying file objects by the operating system. Operating on files via file descriptors instead of filenames provides a greater level of certainty with regard to the object that is actually acted on. Thus, it is recommended that files are accessed through file descriptors, not filenames.

Non-Compliant Example 1

In this example, the function chmod() is called to set the permissions of a file. However, it is not clear whether the file object referred to by file_name refers to the same object in the call to fopen() and in the call to chmod().

...
FILE * f_ptr = fopen(file_name,"w");

f_ptr = fopen(file_name,"w");
if (!f_ptr)  {
  /* Handle fopen() Error */
}
...
if (chmod(file_name, new_mode) == -1) {
  /* Handle chmod() Error */
}
/* Process file */

Compliant Solution 1

Using functions similar to those above but that operate on file descriptors rather than filenames provides a greater level of certainty that the file opened is the same file that is operated on.

fd = open(file_name, O_WRONLY | O_CREAT, 0600);
if (fd == -1) {
  /* Handle open() error */
}
...
if (fchmod(fd, new_mode) == -1) {
  /* Handle chmod() Error */
}
/* Process file */

Priority: Level:

References

  • No labels