Path Traversal

Filesystem path traversal in C/C++

Description

When external input becomes a filesystem API's path argument, an attacker can use .. components or absolute paths to select files outside the intended base directory. Windows also requires consideration of \ and /, drive paths, UNC paths, and device paths. Symbolic links or Windows reparse points may redirect path resolution, so a path checked only as a string can still reach outside the base directory.

basename() and C++'s std::filesystem::path::filename() only return the last path component. They are not general path sanitizers: input may be . or .., and the returned name may select an arbitrary local file or link. lexically_normal() transforms text without consulting the filesystem. canonical() and weakly_canonical() do not themselves establish containment in a trusted base directory or make checking and use atomic. A string-prefix check may wrongly accept /var/app/data-escape as inside /var/app/data, and cannot prevent paths changing before they are opened.

Potential impact

  • Reading, creating, replacing, renaming, or deleting files with the process's privileges
  • Exposure or modification of configuration, credentials, keys, or source code
  • Privilege escalation, code execution, or service disruption when the process has elevated privileges

Remediation

Where possible, let the caller choose an identifier such as profile. Map each allowed identifier to a fixed, server-managed path and reject other values.

If users need to supply part of the path, fix the base directory in code or protected configuration. Reject absolute paths, empty components, . and ...

Normalize the path using the target operating system’s rules. Compare path components. Accept the base itself or a descendant whose leading components match the entire base. In a string comparison, the full base must match and a directory separator must separate it from any remaining components. A simple strncmp() prefix comparison can accept a different directory. Open files relative to a trusted directory handle or descriptor where possible. Account for symbolic links, hard links, mount points, Windows reparse points, and changes between checking and opening.

  • On Linux 5.6 or later, pass a trusted directory descriptor to openat2() with RESOLVE_BENEATH or RESOLVE_IN_ROOT. Add RESOLVE_NO_MAGICLINKS to block magic links or RESOLVE_NO_SYMLINKS to block all symbolic links. Handle every error.
  • On POSIX systems without openat2(), openat() alone permits .. to leave the base. Validate each component against a strict allowed format and consider opening one component at a time from a trusted directory descriptor with O_NOFOLLOW.
  • On Windows, account for reparse points when using CreateFile(). To read an existing file, open it with the minimum access needed, without creating or truncating it. Before reading, use GetFinalPathNameByHandle() to check the volume and path components against the base, using consistent volume representations. For creation or replacement, use a fixed mapping or a platform-specific method that validates the target before a destructive open.

Grant only the permissions required for the operation. Reject unexpected file types, owners, or permissions.

realpath() resolves ., .., and symbolic links in existing paths. You still need to verify containment and handle changes between checking and opening. For a new file, handle the parent directory and final component separately.

Examples

C examples

Before

c
#include <stdio.h>

int main(int argc, char **argv) {
    if (argc != 2) {
        return 2;
    }

    FILE *file = fopen(argv[1], "rb");
    if (file == NULL) {
        return 1;
    }
    return fclose(file);
}

After

c
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
    if (argc != 2) {
        return 2;
    }

    const char *path = NULL;
    if (strcmp(argv[1], "profile") == 0) {
        path = "/var/app/data/profile.json";
    } else if (strcmp(argv[1], "settings") == 0) {
        path = "/var/app/data/settings.json";
    } else {
        return 2;
    }

    FILE *file = fopen(path, "rb");
    if (file == NULL) {
        return 1;
    }
    return fclose(file);
}

Only profile and settings select a file. fopen() receives the fixed server path for the selected key.

C++ examples

Before

cpp
#include <fstream>

int main(int argc, char **argv) {
    if (argc != 2) {
        return 2;
    }

    std::ifstream file{argv[1]};
    return file ? 0 : 1;
}

After

cpp
#include <fstream>
#include <string_view>

int main(int argc, char **argv) {
    if (argc != 2) {
        return 2;
    }

    const char *path = nullptr;
    const std::string_view key{argv[1]};
    if (key == "profile") {
        path = "/var/app/data/profile.json";
    } else if (key == "settings") {
        path = "/var/app/data/settings.json";
    } else {
        return 2;
    }

    std::ifstream file{path};
    return file ? 0 : 1;
}

The C++ example rejects unrecognized keys before opening a file. std::ifstream receives one of the two fixed paths.

References