The file system is not synchronized to your program

Application developers make a lot of assumptions about the state of the file system. In contrast to in-memory objects for which the programming system can offer guarantees of correctness by construction, the contents of a file or the meaning of a path string typically cannot be constrained in any way at design time. For example, you can know (modulo “unsafe code”) that any given instance of a certain type will satisfy some invariant that’s checked by the compiler. You can know that a statically typed object has a certain method, that it’s convertible to a certain type, etc. But given a file path, you can’t discover or even practically assume

  • whether it refers to a file that exists
  • whether you have permission to access it
  • what the file’s content is

until runtime. In most systems, there is no way around this. Programmers are used to this, and it’s why we accept that file system APIs are allowed to fail. Accordingly, we wrap most file system operations in try blocks or some other appropriate error-handling construct. However, there are still a few ways in which programmers go too far in their assumptions about the file system. Most mistakes of this kind, like assuming file content has a certain format, manifest as programs that are overly simplistic and lack validation capabilities. In security circles, plenty of ink has already been spilled about the need for input validation1. In this post, I want to draw attention to a different kind of mistake, in which programs are too long and attempt validation in a way that is improper and pointless.

The file system is a shared resource

Some file system APIs offer a way to get exclusive access to a file, but not all file systems or OSes support it. Even when you can get exclusive access to a file, most file systems neglect to offer a way to link multiple operations into an atomic transaction. This means operations like the following all have race conditions:

  • Closing a file and then opening it again in a different mode
  • Listing the contents of a directory and then deleting the directory
  • Checking whether a file exists and then opening it

Since concurrent modifications are possible, the accuracy of queries on the file system is to be considered merely best-effort. Individual operations like open, read, write, flush, etc. use synchronization internally as required to avoid corrupting the backing store and to avoid showing the caller something it shouldn’t see (e.g. reading data from a nonexistent file, or from a file it shouldn’t have access to), but outside of this, the file system is TOCTOU galore.

static void Main() {
  WriteGreeting("foo.txt");
}

static void WriteGreeting(string path) {
  using (var writer = new StreamWriter(path)) {
    path.WriteLine("Hello, World!");
  } // Close file
  logger.Info("Wrote greeting to \"{0}\"", path);
}

Does that mean the log message above is wrong or unreliable? No, the function really did write “Hello, World!” to foo.txt by the time it writes the log. However, it would risk being wrong if it said “foo.txt contains a greeting”. That is because when the message is logged, the program doesn’t know what the contents of the file it just wrote to are, or whether that file even exists. The file may have been modified, moved, or deleted. Nevertheless, we do know that the program wrote a greeting to that file, because if any of the foregoing I/O operations had failed, the logging call would not have been reached (control flow would have been diverted by an exception).

This distinction may seem negligible, but whether that is the case depends on the application and how much risk the user is willing to accept. Moreover, a decision to ignore the distinction would be made at high levels of abstraction, not at the unit level of this function. Never let your low-level components be the source of needless errors and imprecision, even if errors and imprecision are deemed tolerable at the upper levels of integration.

TOCTOU galore

Now for the example that really motivated this post.

Data LoadData(string path) {
  if (!File.Exists(path)) {
    logger.Error("File not found for data: \"{0}\"", path);
    throw new LoadDataException($"Could not find file \"{path}\"");
  }
  using var reader = new StreamReader(path);
  Data data = /* populate using reader */
  return data;
}

The discussion in the previous section hints at the problem in the above code, namely that we have a race condition between the existence check and the open. Before declaring the File.Exists call pointless, our intuition should be demanding two conditions:

  1. Opening a file for reading will entail checking whether it exists. This is obviously true, since opening it must fail if the file doesn’t exist. This means we don’t gain anything of positive value by having the separate existence check.
  2. Attempting to open a nonexistent file will not be significantly more expensive (e.g. slower) than checking whether it exists as a standalone operation. This is something common sense tells you to expect, and it turns out to be true in practical settings. This means we don’t avoid anything of negative value by having the separate existence check.

Because we have both the above conditions, we can conclude that checking whether a file exists shortly before you open it is pointless at best. Code like the above should be improved by removing the if (!File.Exists(path)) block. If a programmer objects to deleting that code because he wants some special thing to happen in the case of the file’s nonexistence, then his code is running afoul of the race condition. Whatever code intended to run if the file doesn’t exist belongs in a catch block that gets hit when the file open throws2.

Data LoadData(string path) {
  StreamReader reader;
  try {
    reader = new StreamReader(path);
  } catch (FileNotFoundException ex) {
    logger.Error($"File not found for data: \"{0}\"", path);
    throw new LoadDataException(ex);
  }
  Data data = /* populate using reader */
  return data;
}

Aside: Don’t guess at the reason for a failure

The above example handles file nonexistence as a failure reason, but callers of file system APIs should remember there are many other possible reasons that opening a file can fail, such as:

  • Tried to open a directory as if it were a file
  • Out of memory
  • Quota exceeded
  • Timed out

One Linux manpage lists 43 different reasons the open system call can fail, corresponding to 26 different return codes. Microsoft doesn’t even list the reasons CreateFileW can fail, instead simply telling us to call GetLastError. High-level libraries may roll these errors up into a small list of more generic reasons for failure, but programmers must avoid confusing these generic errors with specific ones.

FILE* file = fopen(path, "r");
if (file == NULL) {
  printf("File not found\n");
}

Inexperienced programmers often write code like the above. Instead, read the documentation of the functions you’re calling, and then program accordingly. In the case of fopen, it’s documented as failing by returning NULL and setting errno to indicate the reason. Taking that into account results in the following improvement to the above snippet.

FILE* file = fopen(path, "r");
if (file == NULL) {
  perror("Error opening file");
}

Hope considered harmful

The upshot is that it usually makes no sense to use a file system API to predict the future, such as about whether a future API call will succeed. Information returned from a file system API is best thought of as presenting a strictly historical view of the world, free of any promises about the time after it returns, unless the API documentation makes such promises. You can hope, for instance, that if a file was found to exist on line 1, that it will still exist by the time you try opening it on line 2, but your code must not assume it. Always be prepared for any I/O operation to fail in any way that its documentation says it can fail.


  1. For example: https://cwe.mitre.org/data/definitions/20.html ↩︎
  2. The same applies to languages without exceptions. Handle your return values! ↩︎

Posted

in

by

Tags: