Skip to content
Tech News
← Back to articles

How Hard Is It to Open a File?

read original get File Opening Toolkit → more articles
Why This Matters

This article highlights the complexities and security considerations involved in opening files within applications, especially when dealing with security boundaries and filesystem manipulations. It underscores that, while simple in straightforward cases, handling file access securely requires careful path normalization and symlink resolution to prevent vulnerabilities. This understanding is crucial for developers and security professionals aiming to protect sensitive data and maintain robust security practices.

Key Takeaways

It’s a question I had to ask myself multiple times over the last few months. Depending on the context the answer can be:

very simple, just call the standard library function

extremely hard, don’t trust anything

If you are an app developer, you’re lucky and it’s almost always the first answer. If you develop something with a security boundary which involves files in any way, the correct answer is very likely the second one.

Opening a File, the Hard Way

Like so often, the details depend on the specifics, but in the worst-case scenario, there is a process on either side of the security boundary, which operate on a filesystem tree which is shared by both processes.

Let’s say that the process with more privileges operates on a file on behalf of the process with less privileges. You might want to restrict this to files in a certain directory, to prevent the less privileged process from, for example, stealing your SSH key, and thus take a subpath that is relative to that directory.

The first obvious problem is that the subpath can refer to files outside of the directory if it contains .. . If the privileged process gets called with a subpath of ../.ssh/id_ed25519 , you are in trouble. Easy fix: normalize the path, and if we ever go outside of the directory, fail.

The next issue is that every component of the path might be a symlink. If the privileged process gets called with a subpath of link , and link is a symlink to ../.ssh/id_ed25519 , you might be in trouble. If the process with less privileges cannot create files in that part of the tree, it cannot create a malicious symlink, and everything is fine. In all other scenarios, nothing is fine. Easy fix: resolve the symlinks, expand the path, then normalize it.

This is usually where most people think we’re done, opening a file is not that hard after all, we can all do more fun things now. Really, this is where the fun begins.

... continue reading