Zennoxa Shield
Rules / C/C++
SHIELD-CPP-017

File open with untrusted path

mediumC/C++CWE-22CVSS 6.5

What it detects

fopen or open with a variable path may allow path traversal to unintended files.

How to fix

Canonicalize the path with realpath and confirm it stays inside an allowed directory.

Vulnerable — Shield flags thisupload_reader.c
#include <stdio.h>

long read_upload(const char *filename, char *buf, long cap) {
    /* filename comes straight from the request: ../../etc/passwd */
    FILE *f = fopen(filename, "rb");
    if (f == NULL)
        return -1;
    long n = (long)fread(buf, 1, (size_t)cap, f);
    fclose(f);
    return n;
}
Fixed — scans cleanupload_reader.c
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>

int open_upload(const char *filename) {
    char full[PATH_MAX];
    if (realpath(filename, full) == NULL)
        return -1;
    if (strncmp(full, "/srv/uploads/", 13) != 0)
        return -1;                   /* stays inside the allowed dir */
    int dir = openat(AT_FDCWD, "/srv/uploads", O_RDONLY | O_DIRECTORY);
    if (dir < 0)
        return -1;
    return openat(dir, full + 13, O_RDONLY | O_NOFOLLOW);
}

Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CPP-017, the fixed one does not.

SHIELD-CPP-017: File open with untrusted path — Zennoxa Shield