CSE Roadmap

Core tier · about 4 hours · 13 parts

Part 2 of 13 · 2 min read

Resolve the path first; checking the unresolved string lets symlinks and prefixes through

A check that compares text instead of the thing the text actually points to can be fooled by anything that changes what the text resolves to.

Think of a bouncer checking whether a wristband's printed venue name matches tonight's venue. The bouncer never looks at which door the wristband actually opens. A forged band with the right printed name still gets someone through the wrong door.

path traversal is using .. or an absolute path to leave an allowed directory, and a symlink escape is a link that sits inside the allowed directory but points somewhere outside it. Both defeat a check that only compares path strings. That is because the string can look safely contained while the actual file it resolves to is not. That is why a confinement check has to resolve the real path first and only then compare it.

A worked example. Against 10 hand-written escape attempts, a naive startswith(root) check wrongly allows 8 of them (80%) -- it's fooled by a sibling directory named work-evil (whose path starts with the same prefix as work) and by a symlink planted inside the allowed root that points outside it. Normalising the path without resolving symlinks catches the .. traversal but still misses the symlink, cutting wrongly-allowed escapes to 3 of 10 (30%). Resolving with realpath and comparing with commonpath against the resolved root allows 0 of the 10 escapes, while still allowing all 6 legitimate paths.

The key lines. From code/mini-sandbox/sandbox.py:

# from code/mini-sandbox/sandbox.py
def confine(root, user_path):
    """Return the real path if it stays inside root after resolving symlinks and '..', else None."""
    if "\x00" in user_path:
        return None
    root_real = os.path.realpath(root)
    p = os.path.realpath(os.path.join(root_real, user_path))
    try:
        return p if os.path.commonpath([root_real, p]) == root_real else None
    except ValueError:
        return None

Read it as: os.path.realpath is called on both the root and the requested path before anything is compared. This is the entire fix in one function. A symlink inside the root that points outside gets resolved to its real target before the commonpath check runs. That means the comparison is between two fully-resolved locations, not two strings that merely look like they're in the same place.

Path traversal, symlink escape

Path traversal is using .. or absolute paths to leave an allowed directory. A symlink escape is a link inside the allowed directory pointing outside it.

Example: the work-evil sibling directory passing a naive startswith check is path traversal by prefix collision rather than by .. -- the string "looks" contained because it starts with the right letters, which is exactly the class of mistake resolving the real path eliminates.