Versions Compared

Key

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

Proper understanding of the difference between text mode and binary mode is important when using functions that operate on file streams. (see See recommendation FIO14-C. Understand the difference between text mode and binary mode with file streams for more information.).

Wiki Markup
Section 7.19.9.2 of \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] states the following specific behavior for {{fseek()}} when opening a binary file in binary mode: 

...

Seeking to the end of a binary stream in binary mode with fseek() is not meaningfully supported and, and as a result, not a recommended method for computing the size of a file.

...

However, setting the file position indicator to the end of the file using fseek() has undefined behavior for a binary stream and, consequently, the amount of memory allocated may be incorrect, leading to a potential vulnerability.

...

Code Block
bgColor#CCCCFF
FILE *fp;
long file_size;
char *buffer;
struct stat stbuf;
int fd;

fd = open("foo.txt", O_RDONLY);
if (fd == -1) {
  /* Handle Error */
}

fp = fdopen(fd, "r");
if (fp == NULL) {
  /* Handle Error */
}

if (fstat(fd, &stbuf) == -1) {
  /* Handle Error */
}
file_size = stbuf.st_size;

buffer = (char*)malloc(file_size);
if (buffer == NULL) {
  /* Handle Error */
}

/* ... */ 

Implementation Details

[MSDN] has the following to say about ftell():

...

Code Block
offset = 0

However, 0 is incorrect and ; the correct value should be 10 as evident when the file is opened in binary mode rather than text mode.

...

Understanding the difference between text mode and binary mode with file streams is critical when working with functions that operate on them. Setting the file position indicator to end-of-file with fseek() has undefined behavior for a binary stream. In addition, the return value of ftell() for streams opened in text mode is useful only in calls to fseek(), and not to determine file sizes or for any other use. As such, fstat(), or other platform-equivalent functions, should be used to determine the size of a file.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

FIO19-C

low

unlikely

medium

P2

L3

Bibliography

Related Guidelines

Wiki Markup\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 7.19.9.2, "The fseek function", Section 7.19.3, footnote 234, "Files", Section 7.19.9.4, "The ftell function" [MSDN|AA. Bibliography#MSDN]

Bibliography

MSDN "ftell"

...

      09. Input Output (FIO)      FIO00-C. Take care when creating format strings