Secure upload storage: reject path traversal and symlinks

Secure upload storage: reject path traversal and symlinks

Secure upload storage: reject path traversal and symlinks

When a store admin backend accepts product images or an ERP system imports attachments, appending the uploaded filename to a destination directory and calling open() can turn an ordinary upload into an arbitrary file overwrite. The risk has nothing to do with how much memory a dedicated server has; it lies at the boundary between path resolution and file creation. This article builds a private upload inbox on Linux and uses repeatable rejection tests to check path traversal, name collisions, and symbolic links without touching business data.

Define the trust boundary

The examples use the Python 3 standard library on Debian 12 or Ubuntu Server 24.04 LTS. Run them over SSH. For HtmlAmd servers, retrieve the credentials from the console after payment; if the server has multiple addresses, connect using the first one.

Start with the threat model: the requester can supply file contents and an original filename but cannot control the service account, the destination directory, or its trusted parent directories. If other tasks share the upload service's system account, directory permissions cannot isolate them. Separate the accounts first.

Treat the client-supplied filename as display information and a server-generated object name as the storage identifier. This example accepts only a single ASCII name component, with no subdirectories. In production, you can generate a random identifier and store the original name in a database. A database record must not, in turn, become an unchecked file path.

Calling exists() or is_symlink() before opening a file does not guarantee safety. The directory entry can change between the two operations. Rejection conditions must be enforced by the system call that actually creates the file.

Create a private inbox

Use an ordinary account to create an isolated lab directory. Do not reuse an existing upload directory or recursively change permissions on business data paths:

umask 077
LAB=$(mktemp -d)
mkdir -m 700 "$LAB/inbox"
printf 'keep\n' > "$LAB/protected"
export LAB

A directory with mode 0700 allows only its owning account to enter it; use mode 0600 when creating files. In production, assign ownership of the inbox to a dedicated service account and leave its parent directories under trusted administrator control. Do not let a web server serve static files directly from this location.

A private inbox is not a public download directory. After a file has been written successfully, separate checks for size, type, malicious content, and business authorization are still required before deciding whether to publish it. This article validates only the path boundary; checking an extension is not a substitute for checking content.

Set explicit capacity budgets as well: limit the total volume of requests, individual file size, and the number of concurrent writes separately. Path safety cannot stop files with valid names from filling the disk, nor can it replace authentication on the upload endpoint.

Tighten file creation

Save the following program as upload_guard.py in the lab directory. It accepts only a single name component and resolves it relative to a directory file descriptor. O_EXCL rejects existing entries, so a file with the same name cannot be overwritten. Error output includes only the exception class to avoid returning server paths to the requester.

import os
import re
import sys

VALID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}\.bin", re.ASCII)

def store(root, name, payload):
    if VALID.fullmatch(name) is None:
        raise ValueError("invalid storage name")

    directory = os.open(
        root,
        os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC,
    )
    try:
        fd = os.open(
            name,
            os.O_WRONLY | os.O_CREAT | os.O_EXCL
            | os.O_NOFOLLOW | os.O_CLOEXEC,
            0o600,
            dir_fd=directory,
        )
        try:
            with os.fdopen(fd, "wb") as stream:
                stream.write(payload)
                stream.flush()
                os.fsync(stream.fileno())
        except BaseException:
            os.unlink(name, dir_fd=directory)
            raise
    finally:
        os.close(directory)

if __name__ == "__main__":
    try:
        store(sys.argv[1], sys.argv[2], b"sample\n")
    except (OSError, ValueError) as exc:
        print(type(exc).__name__, file=sys.stderr)
        raise SystemExit(1)

Understand the constraints

dir_fd anchors file creation to an already-open directory instead of reconstructing a full path for each operation. O_NOFOLLOW generally applies only to the final path component, so the name is also prohibited from containing any directory hierarchy.

Opening the inbox also rejects a symbolic link in the final component, but this does not guarantee that parent paths contain no links or replaceable components. Trusted parent directories are a prerequisite for this approach. Do not present this code as a complete sandbox for arbitrary paths.

Together, O_EXCL and O_CREAT provide “create a new entry only” semantics. Creation should fail for an existing regular file, hard link, or symbolic link. Do not handle collisions by deleting the existing entry and then creating a new one; that would reintroduce the risk of overwriting files.

Run rejection tests

First verify normal creation, then submit the same name again. Run all of the following commands in the same shell:

python3 "$LAB/upload_guard.py" "$LAB/inbox" order-001.bin
test "$(cat "$LAB/inbox/order-001.bin")" = sample

if python3 "$LAB/upload_guard.py" "$LAB/inbox" order-001.bin; then
    exit 1
fi

for name in '../escape.bin' '/tmp/escape.bin' \
    'sub/item.bin' '..%2fescape.bin' '商品.bin'
do
    if python3 "$LAB/upload_guard.py" "$LAB/inbox" "$name"; then
        exit 1
    fi
done

ln -s "$LAB/protected" "$LAB/inbox/link.bin"
if python3 "$LAB/upload_guard.py" "$LAB/inbox" link.bin; then
    exit 1
fi

test "$(cat "$LAB/protected")" = keep
test "$(cat "$LAB/inbox/order-001.bin")" = sample
test ! -e "$LAB/escape.bin"

Acceptance testing must go beyond checking that the program reports failure. Confirm that the protected file is unchanged, that the duplicate request did not rewrite the first upload, and that no new file appeared outside the inbox. A symbolic-link collision may produce FileExistsError; do not treat one particular exception name as a fixed cross-platform contract.

Run the encoded test cases through the real endpoint as well. An upstream framework may decode request parameters first, so name validation must examine the final string passed to the storage function. No further decoding may occur after validation. Other backend tasks must not reuse the original filename to construct paths either.

Integrate and retest

The example writes a fixed byte sequence. When integrating a streaming request, count the actual bytes as they are read. Stop immediately if the limit is exceeded and remove the file created for that upload. Do not trust only the length in the request headers, and do not read an entire attachment into memory at once.

This approach creates a directory entry as soon as file creation begins. It does not provide a publication guarantee that other processes can see only complete files. A scanner must not treat the inbox itself as a queue of completed uploads. Instead, notify downstream tasks through an explicit status after writing and validation have succeeded. Calling fsync() on the file also does not provide a complete guarantee that the directory entry will survive a power loss.

If the process is forcibly terminated, exception cleanup code may never run. For each upload, record the server-generated identifier, the started state, and the completed state. Cleanup tasks should handle only incomplete objects confirmed to have no remaining writer, rather than deleting files solely based on their age.

Retain four sets of evidence for production acceptance: the runtime account and directory permissions, content verification after a normal upload, exit statuses for every rejection test case, and before-and-after digests of the protected file. Rerun the same test cases whenever naming rules, decoding order, or storage paths change, so an endpoint change cannot silently expand where files can be written.

Frequently asked questions

Is checking that a path starts with the upload directory sufficient?

No. Another directory can share that string prefix, and a path can change between checking and opening. Accept a single filename component, anchor creation to an open directory descriptor and reject existing entries with exclusive creation.

Does O_NOFOLLOW block every symlink in a path?

No. It generally applies only to the final path component. The example disallows directory components in filenames, opens the inbox itself with O_NOFOLLOW and requires trusted administrative control of its parent path.

AMD EPYC 7543P Dedicated Server

From $461.7/month

Review server specifications and access

Choose a configuration to match deployment requirements. After delivery, view the login credentials in the console.