Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 47 additions & 26 deletions src/server/security/file-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,52 +3,73 @@
* @description File security hardening: magic byte inspection, ZIP bomb detection, path traversal defense.
*/

// Magic byte signatures
const MAGIC_SIGNATURES: Record<string, number[][]> = {
"image/png": [[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]],
"image/jpeg": [[0xff, 0xd8, 0xff]],
interface MagicSegment {
offset: number;
bytes: number[];
}

// Magic byte signatures (each variant is a list of required offset+bytes segments)
const MAGIC_SIGNATURES: Record<string, MagicSegment[][]> = {
"image/png": [[{ offset: 0, bytes: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] }]],
"image/jpeg": [[{ offset: 0, bytes: [0xff, 0xd8, 0xff] }]],
"image/gif": [
[0x47, 0x49, 0x46, 0x38, 0x37, 0x61],
[0x47, 0x49, 0x46, 0x38, 0x39, 0x61],
[{ offset: 0, bytes: [0x47, 0x49, 0x46, 0x38, 0x37, 0x61] }],
[{ offset: 0, bytes: [0x47, 0x49, 0x46, 0x38, 0x39, 0x61] }],
],
"image/webp": [
[
{ offset: 0, bytes: [0x52, 0x49, 0x46, 0x46] }, // 'RIFF'
{ offset: 8, bytes: [0x57, 0x45, 0x42, 0x50] }, // 'WEBP'
],
],
"image/webp": [[0x52, 0x49, 0x46, 0x46]], // Bytes 0-3: 'RIFF', byte 8-11: 'WEBP'
"application/pdf": [[0x25, 0x50, 0x44, 0x46]], // '%PDF'
"application/pdf": [[{ offset: 0, bytes: [0x25, 0x50, 0x44, 0x46] }]], // '%PDF'
"application/zip": [
[0x50, 0x4b, 0x03, 0x04],
[0x50, 0x4b, 0x05, 0x06],
[{ offset: 0, bytes: [0x50, 0x4b, 0x03, 0x04] }],
[{ offset: 0, bytes: [0x50, 0x4b, 0x05, 0x06] }],
],
};

/**
* Validates file buffer against expected MIME type using magic bytes
*/
export function validateMagicBytes(buffer: Uint8Array, expectedMime: string): boolean {
const signatures = MAGIC_SIGNATURES[expectedMime];
if (!signatures) {
const variants = MAGIC_SIGNATURES[expectedMime];
if (!variants) {
// If unknown mime, permit text formats or defer
return true;
}

return signatures.some((sig) => {
if (buffer.length < sig.length) return false;
for (let i = 0; i < sig.length; i++) {
if (buffer[i] !== sig[i]) return false;
}
return true;
});
return variants.some((segments) =>
segments.every(({ offset, bytes }) => {
if (buffer.length < offset + bytes.length) return false;
for (let i = 0; i < bytes.length; i++) {
if (buffer[offset + i] !== bytes[i]) return false;
}
return true;
})
);
}

/**
* Sanitizes user-provided filenames against path traversal attacks (e.g. `../../etc/passwd`)
*/
export function sanitizeFileName(filename: string): string {
// 1. Strip null bytes
let clean = filename.replace(/\0/g, "");
// 2. Remove directory traversals
clean = clean.replace(/(\.\.[\/\\])+/g, "");
// 3. Remove leading slashes and drive letters
clean = clean.replace(/^[a-zA-Z]:[\/\\]+/, "").replace(/^[\/\\]+/, "");
// 4. Fallback if empty
// 1. Strip null bytes and ASCII control characters
let clean = filename.replace(/[\0-\x1f\x7f]/g, "");
// 2. Iteratively remove drive letters, leading slashes, and dot-traversal segments
// so nested sequences like `....//` or trailing `..` cannot survive a single pass.
let prev: string;
do {
prev = clean;
clean = clean
.replace(/^[a-zA-Z]:[\/\\]*/, "")
.replace(/^[\/\\]+/, "")
.replace(/[\/\\]+\.{2,}$/g, "")
.replace(/(^|[\/\\])\.{2,}([\/\\]+|$)/g, "$1")
.replace(/^[\/\\]+/, "");
} while (clean !== prev);

// 3. Fallback if empty
if (!clean.trim()) {
clean = "unnamed_file";
}
Expand Down
137 changes: 117 additions & 20 deletions src/server/security/ssrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,83 @@ const BLOCKED_HOSTNAMES = new Set([
"169.254.169.254", // AWS/GCP/Azure link-local metadata
]);

function normalizeHost(hostname: string): string {
// Strip IPv6 brackets (`[::1]` -> `::1`), zone IDs, and trailing DNS root dots
return hostname
.toLowerCase()
.replace(/^\[(.*)\]$/, "$1")
.split("%")[0]
.replace(/\.+$/, "");
}

function isPrivateIpv4(ip: string): boolean {
const parts = ip.split(".").map(Number);
if (parts.length !== 4 || parts.some((p) => Number.isNaN(p) || p < 0 || p > 255)) {
return false;
}
// 10.0.0.0/8
if (parts[0] === 10) return true;
// 172.16.0.0/12
if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
// 192.168.0.0/16
if (parts[0] === 192 && parts[1] === 168) return true;
// 127.0.0.0/8 (Loopback)
if (parts[0] === 127) return true;
// 169.254.0.0/16 (Link-local / Cloud metadata)
if (parts[0] === 169 && parts[1] === 254) return true;
// 0.0.0.0/8
if (parts[0] === 0) return true;
return false;
}

/**
* Validates if an IP address string belongs to a private/internal subnet
*/
function isPrivateIp(ip: string): boolean {
// IPv4 Private subnets
const parts = ip.split(".").map(Number);
if (parts.length === 4 && parts.every((p) => !isNaN(p) && p >= 0 && p <= 255)) {
// 10.0.0.0/8
if (parts[0] === 10) return true;
// 172.16.0.0/12
if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
// 192.168.0.0/16
if (parts[0] === 192 && parts[1] === 168) return true;
// 127.0.0.0/8 (Loopback)
if (parts[0] === 127) return true;
// 169.254.0.0/16 (Link-local)
if (parts[0] === 169 && parts[1] === 254) return true;
// 0.0.0.0/8
if (parts[0] === 0) return true;
function isPrivateIp(rawIp: string): boolean {
const ip = normalizeHost(rawIp);

if (isPrivateIpv4(ip)) {
return true;
}

// IPv6 loopback / private
if (ip === "::1" || ip.startsWith("fc00:") || ip.startsWith("fe80:")) {
// IPv4-mapped IPv6 (`::ffff:127.0.0.1` or URL-normalized `::ffff:7f00:1`)
if (ip.startsWith("::ffff:")) {
const suffix = ip.slice("::ffff:".length);
if (isPrivateIpv4(suffix)) {
return true;
}
const hexGroups = suffix.split(":");
if (hexGroups.length === 2) {
const hi = parseInt(hexGroups[0], 16);
const lo = parseInt(hexGroups[1], 16);
if (!Number.isNaN(hi) && !Number.isNaN(lo)) {
const ipv4 = `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`;
if (isPrivateIpv4(ipv4)) {
return true;
}
}
}
}

// IPv6 loopback / unspecified (`::1`, `::`, `0:0:0:0:0:0:0:1`, `0:0:0:0:0:0:0:0`)
if (
ip === "::1" ||
ip === "::" ||
/^0{1,4}(:0{1,4}){6}:0{0,3}[01]$/.test(ip)
) {
return true;
}

// IPv6 ULA (`fc00::/7`: `fc00..fdff`) and link-local (`fe80::/10`: `fe80..febf`)
const firstHextet = ip.split(":")[0];
if (firstHextet) {
const value = parseInt(firstHextet, 16);
if (!Number.isNaN(value)) {
if ((value & 0xfe00) === 0xfc00) return true;
if ((value & 0xffc0) === 0xfe80) return true;
}
}

return false;
}

Expand All @@ -67,7 +118,7 @@ export async function safeFetch(urlString: string, options: SafeFetchOptions = {
}

// 2. Hostname blocklist
const hostname = parsed.hostname.toLowerCase();
const hostname = normalizeHost(parsed.hostname);
if (BLOCKED_HOSTNAMES.has(hostname) || isPrivateIp(hostname)) {
throw new Error(`Access to private or local network host is forbidden: ${hostname}`);
}
Expand All @@ -80,16 +131,62 @@ export async function safeFetch(urlString: string, options: SafeFetchOptions = {

// 4. Timeout and payload limits
const timeoutMs = options.timeoutMs ?? 8000;
const maxBytes = options.maxResponseSizeBytes;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);

const { maxResponseSizeBytes: _max, timeoutMs: _timeout, ...fetchOptions } = options;

try {
const res = await fetch(parsed.toString(), {
...options,
...fetchOptions,
signal: controller.signal,
redirect: "manual", // Prevent open redirect SSRF bypasses!
});

if (maxBytes !== undefined) {
const contentLengthHeader = res.headers.get("content-length");
if (contentLengthHeader !== null) {
const contentLength = Number(contentLengthHeader);
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
await res.body?.cancel();
throw new Error(`Response size (${contentLength} bytes) exceeds limit of ${maxBytes} bytes.`);
}
}

if (res.body) {
const reader = res.body.getReader();
const chunks: Uint8Array[] = [];
let totalBytes = 0;

while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
totalBytes += value.byteLength;
if (totalBytes > maxBytes) {
await reader.cancel();
throw new Error(`Response size exceeds limit of ${maxBytes} bytes.`);
}
chunks.push(value);
}
}

const combined = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
combined.set(chunk, offset);
offset += chunk.byteLength;
}

return new Response(combined, {
status: res.status,
statusText: res.statusText,
headers: res.headers,
});
}
}

return res;
} finally {
clearTimeout(timeoutId);
Expand Down
17 changes: 17 additions & 0 deletions tests/security/file-validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,25 @@ describe("File Security & Decompression Guard", () => {
expect(validateMagicBytes(fakePng, "image/png")).toBe(false);
});

it("validates full RIFF+WEBP signature for WebP and rejects RIFF-WAV spoofing", () => {
const validWebp = new Uint8Array([
0x52, 0x49, 0x46, 0x46, 0x24, 0x00, 0x00, 0x00,
0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38, 0x20,
]);
expect(validateMagicBytes(validWebp, "image/webp")).toBe(true);

const wavSpoof = new Uint8Array([
0x52, 0x49, 0x46, 0x46, 0x24, 0x00, 0x00, 0x00,
0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20,
]);
expect(validateMagicBytes(wavSpoof, "image/webp")).toBe(false);
});

it("sanitizes malicious filenames against path traversal", () => {
expect(sanitizeFileName("../../../etc/passwd")).toBe("etc/passwd");
expect(sanitizeFileName("....//....//etc/passwd")).toBe("etc/passwd");
expect(sanitizeFileName("..")).toBe("unnamed_file");
expect(sanitizeFileName("dir/..")).toBe("dir");
expect(sanitizeFileName("..\\..\\windows\\system32\\cmd.exe")).toBe("windows\\system32\\cmd.exe");
expect(sanitizeFileName("valid-file.pdf")).toBe("valid-file.pdf");
expect(sanitizeFileName("")).toBe("unnamed_file");
Expand Down
32 changes: 32 additions & 0 deletions tests/security/ssrf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,38 @@ describe("SSRF Protection Engine", () => {
expect(safeFetch("http://172.16.0.5/internal")).rejects.toThrow("Access to private or local network host is forbidden");
});

it("blocks IPv6 loopback, ULA, link-local, and IPv4-mapped IPv6 bypasses", async () => {
await expect(safeFetch("http://[::1]:8080/admin")).rejects.toThrow("Access to private or local network host is forbidden");
await expect(safeFetch("http://[::]/")).rejects.toThrow("Access to private or local network host is forbidden");
await expect(safeFetch("http://[fe80::1]/")).rejects.toThrow("Access to private or local network host is forbidden");
await expect(safeFetch("http://[fc00::1]/")).rejects.toThrow("Access to private or local network host is forbidden");
await expect(safeFetch("http://[fd12:3456:789a::1]/")).rejects.toThrow("Access to private or local network host is forbidden");
await expect(safeFetch("http://[::ffff:127.0.0.1]/")).rejects.toThrow("Access to private or local network host is forbidden");
await expect(safeFetch("http://[::ffff:169.254.169.254]/latest/meta-data/")).rejects.toThrow("Access to private or local network host is forbidden");
await expect(safeFetch("http://localhost./api")).rejects.toThrow("Access to private or local network host is forbidden");
await expect(safeFetch("http://metadata.google.internal./")).rejects.toThrow("Access to private or local network host is forbidden");
});

it("enforces maxResponseSizeBytes when specified", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = (async () =>
new Response("0123456789abcdef", {
status: 200,
headers: { "content-length": "16" },
})) as unknown as typeof fetch;

try {
await expect(
safeFetch("https://example.com/large", { maxResponseSizeBytes: 8 })
).rejects.toThrow("exceeds limit");

const okRes = await safeFetch("https://example.com/small", { maxResponseSizeBytes: 32 });
expect(await okRes.text()).toBe("0123456789abcdef");
} finally {
globalThis.fetch = originalFetch;
}
});

it("blocks non-HTTP protocols", async () => {
expect(safeFetch("file:///etc/passwd")).rejects.toThrow("Forbidden protocol");
expect(safeFetch("gopher://evil.com/")).rejects.toThrow("Forbidden protocol");
Expand Down