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

Compare with Current View Page History

« Previous Version 22 Next »

Portability is a concern when using the fread() and fwrite() functions across multiple, heterogeneous systems. In particular, it is never guaranteed that reading or writing of scalar data types such as integers, let alone aggregate types such as arrays or structures, will preserve the representation or value of the data. Different compilers use different amounts of padding. Different machines use various floating point models and may use a different number of bits per byte. In addition, there is always the issue of endianness.

Noncompliant Code Example

The following noncompliant code reads data from a file stream into a data structure.

struct myData {
  char c;
  float f;
};

/* ... */

FILE *file;
struct myData data;

/* initialize file */

if (fread(&data, sizeof(struct myData), 1, file) < sizeof(struct myData)) {
  /* handle error */
}

However, the code makes assumptions about the layout of myData, which may be represented differently on a different platform.

Compliant Solution

The best solution is to use either a text representation or a special library that will ensure the integrity of data.

struct myData {
  char c;
  float f;
};

/* ... */

FILE *file;
struct myData data;

/* initialize file */

if (fscanf(file, "%c %f\n", &data.c, &data.f) != 2) {
  /* handle error */
}

Please note that this solution violates INT05-C. Do not use input functions to convert character data if they cannot handle all possible inputs since an attacker could potentially supply an input file with an unrepresentable floating point number, leading to undefined behavior.

Risk Assessment

Reading binary data that has a different format than expected may result in unintended program behavior.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

FIO09-C

medium

probable

high

P4

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

[[Summit 95]], 20.5 on C-FAQ


      09. Input Output (FIO)      

  • No labels