Repository Public
1import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";2import { tmpdir } from "node:os";3import { join } from "node:path";4import { deflateRawSync, gzipSync } from "node:zlib";5import { afterAll, beforeAll, describe, expect, it } from "vitest";6import { ArchiveError, DEFAULT_LIMITS, TAR_END, extractArchive, tarEntry } from "@/server/archive";78/** A minimal ZIP writer, so that the tests can forge exactly the entries a hostile archive would carry. */9interface Entry { name: string; data?: Buffer; store?: boolean; mode?: number; flags?: number; claimSize?: number }10function crc32(buf: Buffer): number { let c = ~0; for (const b of buf) { c ^= b; for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xedb88320 & -(c & 1)); } return ~c >>> 0; }11function zip(entries: Entry[]): Buffer {12 const locals: Buffer[] = [], central: Buffer[] = [];13 let offset = 0;14 for (const e of entries) {15 const data = e.data ?? Buffer.alloc(0), body = e.store ? data : deflateRawSync(data), name = Buffer.from(e.name), size = e.claimSize ?? data.length;16 const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(e.flags ?? 0, 6); local.writeUInt16LE(e.store ? 0 : 8, 8); local.writeUInt32LE(crc32(data), 14); local.writeUInt32LE(body.length, 18); local.writeUInt32LE(size, 22); local.writeUInt16LE(name.length, 26);17 const cd = Buffer.alloc(46); cd.writeUInt32LE(0x02014b50, 0); cd.writeUInt16LE((3 << 8) | 20, 4); cd.writeUInt16LE(20, 6); cd.writeUInt16LE(e.flags ?? 0, 8); cd.writeUInt16LE(e.store ? 0 : 8, 10); cd.writeUInt32LE(crc32(data), 16); cd.writeUInt32LE(body.length, 20); cd.writeUInt32LE(size, 24); cd.writeUInt16LE(name.length, 28); cd.writeUInt32LE(((e.mode ?? 0o100644) << 16) >>> 0, 38); cd.writeUInt32LE(offset, 42);18 locals.push(local, name, body); central.push(cd, name);19 offset += 30 + name.length + body.length;20 }21 const cdBuf = Buffer.concat(central), end = Buffer.alloc(22);22 end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(entries.length, 8); end.writeUInt16LE(entries.length, 10); end.writeUInt32LE(cdBuf.length, 12); end.writeUInt32LE(offset, 16);23 return Buffer.concat([...locals, cdBuf, end]);24}25/** A tar header for an entry that is not a regular file (symlink "2", hard link "1", device "3"…). */26function tarSpecial(name: string, type: string, linkname = ""): Buffer {27 const h = tarEntry(name, Buffer.alloc(0)).subarray(0, 512);28 h.write(type, 156); h.write(linkname, 157, 100); h.write(" ", 148);29 h.write(`${h.reduce((a, b) => a + b, 0).toString(8).padStart(6, "0")}\0 `, 148);30 return h;31}32const targz = (...parts: Buffer[]) => gzipSync(Buffer.concat([...parts, TAR_END]));3334let dir: string, n = 0;35const put = async (name: string, data: Buffer) => { const f = join(dir, `${++n}-${name}`); await writeFile(f, data); return f; };36const dest = () => join(dir, `out-${++n}`);37const tree = async (d: string, base = d): Promise<string[]> => (await Promise.all((await readdir(d, { withFileTypes: true })).map(async (e) => (e.isDirectory() ? tree(join(d, e.name), base) : [join(d, e.name).slice(base.length + 1)])))).flat().sort();3839beforeAll(async () => { dir = await mkdtemp(join(tmpdir(), "atlas-archive-")); });40afterAll(async () => { await rm(dir, { recursive: true, force: true }); });4142describe.each([43 ["zip", (files: [string, string][]) => zip(files.map(([name, text]) => ({ name, data: Buffer.from(text) }))), "a.zip"],44 ["tar.gz", (files: [string, string][]) => targz(...files.map(([name, text]) => tarEntry(name, Buffer.from(text)))), "a.tar.gz"],45] as const)("%s extraction", (kind, pack, filename) => {46 it("extracts regular files with plain names, and only those", async () => {47 const out = dest();48 const report = await extractArchive(await put(filename, pack([["course.yaml", "course: {}"], ["sessions/S01-x/metadata.yaml", "id: S01"], ["sessions/S01-x/notes d'été.md", "nom non sûr"], ["./README.md", "lisez-moi"]])), out);49 expect(await tree(out)).toEqual(["README.md", "course.yaml", "sessions/S01-x/metadata.yaml"]);50 expect(await readFile(join(out, "course.yaml"), "utf8")).toBe("course: {}");51 expect(report).toMatchObject({ files: 3, skipped: { unsafeNames: 1, links: 0 } });52 });5354 it.each([["../evasion.txt"], ["sessions/../../evasion.txt"], ["/etc/evasion.txt"], ["C:/evasion.txt"], ["a\\..\\evasion.txt"], ["ok/../../../evasion.txt"]])("refuses the whole archive for the traversal name %s", async (name) => {55 const out = dest();56 await expect(extractArchive(await put(filename, pack([["course.yaml", "ok"], [name, "évadé"]])), out)).rejects.toThrow(/chemin dangereux/);57 expect((await readdir(dir)).filter((f) => f.includes("evasion"))).toEqual([]);58 expect((await readdir(join(dir, ".."))).filter((f) => f === "evasion.txt")).toEqual([]);59 });6061 it("refuses an archive with too many entries, or whose content is too large once unpacked", async () => {62 const many: [string, string][] = Array.from({ length: 30 }, (_, i) => [`f${i}.txt`, "x"]);63 await expect(extractArchive(await put(filename, pack(many)), dest(), { ...DEFAULT_LIMITS, maxEntries: 20 })).rejects.toThrow(/plus de 20 entrées/);64 await expect(extractArchive(await put(filename, pack([["gros.txt", "x".repeat(5000)]])), dest(), { ...DEFAULT_LIMITS, maxFileBytes: 1000 })).rejects.toThrow(/dépasse/);65 await expect(extractArchive(await put(filename, pack([["a.txt", "x".repeat(600)], ["b.txt", "y".repeat(600)]])), dest(), { ...DEFAULT_LIMITS, maxTotalBytes: 1000 })).rejects.toThrow(/une fois décompressée/);66 });6768 it("refuses a decompression bomb by its ratio, counted on the bytes really produced", async () => {69 const bomb = pack([["bombe.txt", "\0".repeat(8_000_000)]]); // a few kilobytes packed, 8 MB unpacked70 expect(bomb.length).toBeLessThan(40_000);71 await expect(extractArchive(await put(filename, bomb), dest(), { ...DEFAULT_LIMITS, maxRatio: 100 })).rejects.toThrow(ArchiveError);72 });7374 it(`never overwrites a file (duplicate entries) — ${kind}`, async () => {75 await expect(extractArchive(await put(filename, pack([["a.txt", "premier"], ["a.txt", "second"]])), dest())).rejects.toThrow();76 });77});7879describe("links and special entries", () => {80 it("never creates a symbolic link from a ZIP: the entry is skipped and counted", async () => {81 const out = dest();82 const report = await extractArchive(await put("a.zip", zip([{ name: "course.yaml", data: Buffer.from("ok") }, { name: "lien", data: Buffer.from("/etc/passwd"), mode: 0o120777, store: true }, { name: "sessions/lien-dossier", data: Buffer.from("../.."), mode: 0o120777, store: true }])), out);83 expect(await tree(out)).toEqual(["course.yaml"]);84 expect(report.skipped.links).toBe(2);85 });8687 it("never creates symbolic links, hard links or devices from a tar", async () => {88 const out = dest();89 const report = await extractArchive(await put("a.tar.gz", targz(tarEntry("course.yaml", Buffer.from("ok")), tarSpecial("lien", "2", "/etc/passwd"), tarSpecial("dur", "1", "course.yaml"), tarSpecial("periph", "3"), tarEntry("apres.txt", Buffer.from("suite")))), out);90 expect(await tree(out)).toEqual(["apres.txt", "course.yaml"]);91 expect(report.skipped).toMatchObject({ links: 2, other: 1 });92 });9394 it("does not write through a link planted earlier in the same archive", async () => {95 // "sessions" arrives as a symlink to the outside, then a file is addressed « through » it.96 const out = dest();97 await extractArchive(await put("a.tar.gz", targz(tarSpecial("sessions", "2", "/tmp"), tarEntry("sessions/atlas-evasion-test.txt", Buffer.from("x")))), out);98 expect(await tree(out)).toEqual(["sessions/atlas-evasion-test.txt"]); // a real directory inside the destination, not /tmp99 });100});101102describe("format checks", () => {103 it("refuses encrypted entries, unknown compression methods and unknown formats", async () => {104 await expect(extractArchive(await put("a.zip", zip([{ name: "secret.txt", data: Buffer.from("x"), flags: 1 }])), dest())).rejects.toThrow(/chiffrée/);105 const z = zip([{ name: "a.txt", data: Buffer.from("x") }]); z.writeUInt16LE(99, z.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02])) + 10);106 await expect(extractArchive(await put("a.zip", z), dest())).rejects.toThrow(/non prise en charge/);107 await expect(extractArchive(await put("a.rar", Buffer.from("Rar!\x1a\x07\x00 pas pris en charge")), dest())).rejects.toThrow(/non reconnu/);108 await expect(extractArchive(await put("a.zip", Buffer.from("PK\x03\x04 tronqué")), dest())).rejects.toThrow(ArchiveError);109 await expect(extractArchive(await put("a.tar.gz", Buffer.concat([Buffer.from([0x1f, 0x8b]), Buffer.from("pas du gzip")])), dest())).rejects.toThrow(ArchiveError);110 });111112 it("does not trust the size a ZIP entry declares", async () => {113 // Declares 10 bytes, inflates to 100 000: the per-file limit is applied to what really comes out.114 const liar = zip([{ name: "menteur.txt", data: Buffer.from("x".repeat(100_000)), claimSize: 10 }]);115 await expect(extractArchive(await put("a.zip", liar), dest(), { ...DEFAULT_LIMITS, maxFileBytes: 50_000 })).rejects.toThrow(/dépasse/);116 });117118 it("reads long names written with pax headers, as git archive does", async () => {119 const long = `sessions/S01-${"a".repeat(60)}/${"b".repeat(70)}/metadata.yaml`;120 const pax = (path: string) => { const rec = ` path=${path}\n`; let len = rec.length + 2; len = String(len).length + rec.length; const body = Buffer.from(`${len}${rec}`); const h = tarEntry("PaxHeader", body).subarray(0, 512); h.write("x", 156); h.write(" ", 148); h.write(`${h.reduce((a, b) => a + b, 0).toString(8).padStart(6, "0")}\0 `, 148); return Buffer.concat([h, body, Buffer.alloc((512 - (body.length % 512)) % 512)]); };121 const out = dest();122 await extractArchive(await put("a.tar.gz", targz(pax(long), tarEntry("court", Buffer.from("id: S01")))), out);123 expect(await tree(out)).toEqual([long]);124 await expect(extractArchive(await put("a.tar.gz", targz(pax("../../evasion-pax.txt"), tarEntry("court", Buffer.from("x")))), dest())).rejects.toThrow(/chemin dangereux/);125 });126});127