Versions Compared

Key

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

Subclause The C Standard, 7.21.9.3 of the C Standard  [ISO/IEC 9899:2011], defines the following behavior for fsetpos():

The fsetpos function sets the mbstate_t object (if any) and file position indicator for the stream pointed to by stream according to the value of the object pointed to by pos, which shall be a value obtained from an earlier successful call to the fgetpos function on a stream associated with the same file.

Consequently, using Invoking the fsetpos() function with any other values for pos results in is undefined behavior.

Noncompliant Code Example

This noncompliant code example attempts to read three values from a file and then set the cursor file position pointer back to the beginning of the file:

Code Block
bgColor#FFCCCC
langc
#include <stdio.h>
#include <string.h>
 
enum { NO_FILE_POS_VALUES = 3 };

int opener(FILE *file) {
  int rc;
  fpos_t offset;

  memset(&offset, 0, sizeof(offset));

  if (file == NULL) { 
    return -1;
  }

  /* Read in data from file */

  rc = fsetpos(file, &offset);
  if (rc != 0 ) {
    return rc;
  }

  return 0;
}

However, only Only the return value of an fgetpos() call is a valid argument to fsetpos(); passing an a value of type fpos_t value that was created in any other way is undefined behavior.

Compliant Solution

In this compliant solution, the initial file position indicator is stored by first calling fgetpos(), which is used to restore the state to the beginning of the file in the later call to fsetpos():

Code Block
bgColor#CCCCFF
langc
#include <stdio.h>
#include <string.h>
 
enum { NO_FILE_POS_VALUES = 3 };

int opener(FILE *file) {
  int rc;
  fpos_t offset;

  if (file == NULL) {
 return   return -1;
  }

  rc = fgetpos(file, &offset);
  if (rc != 0 ) {
 return   return rc;
  }

  /* Read in data from file */

  rc = fsetpos(file, &offset);
  if (rc != 0 ) {
 return   return rc;
  }

  return 0;
}

Risk Assessment

Misuse of the fsetpos() function can position a file stream read position indicator to a an unintended location in the file. If this location holds data provided by an attacker, the misuse of this function could be exploited to overwrite the values of objects being read from the file.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO44-C

Medium

Unlikely

Medium

P4

L3

...

Bibliography

[ISO/IEC 9899:2011]Subclause 7.21.9.3, "The fsetpos Function"

...