SPB Git

Repository Public

archive.ts 11.5 KB 166 lines typescript

1/**2 * Safe extraction of an uploaded snapshot of the course repository (.zip or .tar.gz), and a minimal tar3 * writer for exports. An archive is hostile until proven otherwise:4 *5 *   - path traversal: an entry that is absolute or contains "..", a backslash or a NUL refuses the whole archive;6 *   - links: symbolic and hard links are never created (skipped and counted);7 *   - bombs: limits on the number of entries, on each file and on the total, counted on the bytes actually8 *     inflated — never on the sizes the archive declares — and on the compression ratio;9 *   - nothing is executed, no permission bit is honoured, only regular files with plain names are written.10 */11import { createReadStream } from "node:fs";12import { mkdir, open, readFile, writeFile } from "node:fs/promises";13import { dirname, resolve, sep } from "node:path";14import { createGunzip, inflateRawSync } from "node:zlib";15import { isSafeRelPath } from "../modules/content-schema/schema";1617export interface ExtractLimits { maxEntries: number; maxFileBytes: number; maxTotalBytes: number; maxRatio: number }18export const DEFAULT_LIMITS: ExtractLimits = { maxEntries: 20_000, maxFileBytes: 50_000_000, maxTotalBytes: 600_000_000, maxRatio: 200 };19export interface ExtractReport { files: number; bytes: number; skipped: { links: number; unsafeNames: number; other: number } }20export class ArchiveError extends Error {}2122const hostile = (name: string) => name.includes("\0") || name.includes("\\") || name.startsWith("/") || /^[A-Za-z]:/.test(name) || name.split("/").includes("..");2324class Sink {25  readonly report: ExtractReport = { files: 0, bytes: 0, skipped: { links: 0, unsafeNames: 0, other: 0 } };26  private entries = 0;27  private readonly root: string;28  constructor(dest: string, private readonly limits: ExtractLimits, private readonly packedBytes: number) { this.root = resolve(dest); }29  /** Called for every entry before anything else: counts it and refuses a hostile name. Returns the clean relative path, or null to skip. */30  admit(rawName: string, kind: "file" | "dir" | "link" | "other"): string | null {31    if (++this.entries > this.limits.maxEntries) throw new ArchiveError(`Archive refusée : plus de ${this.limits.maxEntries} entrées.`);32    if (hostile(rawName)) throw new ArchiveError(`Archive refusée : chemin dangereux (« ${rawName.replace(/[^\x20-\x7e]/g, "?").slice(0, 80)} »).`);33    if (kind === "link") { this.report.skipped.links++; return null; }34    if (kind === "other") { this.report.skipped.other++; return null; }35    const name = rawName.replace(/^(\.\/)+/, "").replace(/\/+$/, "");36    if (kind === "dir" || !name) return null;37    if (!isSafeRelPath(name)) { this.report.skipped.unsafeNames++; return null; }38    return name;39  }40  grow(n: number, fileSoFar: number) {41    if (fileSoFar > this.limits.maxFileBytes) throw new ArchiveError(`Archive refusée : un fichier dépasse ${Math.round(this.limits.maxFileBytes / 1e6)} Mo une fois décompressé.`);42    this.report.bytes += n;43    if (this.report.bytes > this.limits.maxTotalBytes) throw new ArchiveError(`Archive refusée : plus de ${Math.round(this.limits.maxTotalBytes / 1e6)} Mo une fois décompressée.`);44    if (this.report.bytes > this.limits.maxRatio * Math.max(this.packedBytes, 1024)) throw new ArchiveError("Archive refusée : taux de compression anormal (bombe de décompression ?).");45  }46  async write(name: string, data: Buffer) {47    const target = resolve(this.root, name);48    if (!target.startsWith(this.root + sep)) throw new ArchiveError("Archive refusée : chemin hors du dossier d'extraction.");49    await mkdir(dirname(target), { recursive: true });50    await writeFile(target, data, { flag: "wx", mode: 0o600 }); // never overwrites, never follows a planted link51    this.report.files++;52  }53}5455/* ---- ZIP (central directory; stored and deflated entries; no encryption, no ZIP64) ---- */5657async function extractZip(file: string, sink: Sink, limits: ExtractLimits): Promise<void> {58  const buf = await readFile(file);59  let eocd = -1;60  for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65_535); i--) if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }61  if (eocd < 0) throw new ArchiveError("Archive ZIP illisible (répertoire central introuvable).");62  const total = buf.readUInt16LE(eocd + 10), cdSize = buf.readUInt32LE(eocd + 12), cdOffset = buf.readUInt32LE(eocd + 16);63  if (total === 0xffff || cdOffset === 0xffffffff) throw new ArchiveError("Archive ZIP64 non prise en charge : exportez le dépôt en .tar.gz.");64  if (cdOffset + cdSize > buf.length) throw new ArchiveError("Archive ZIP tronquée.");65  let p = cdOffset;66  for (let n = 0; n < total; n++) {67    if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) throw new ArchiveError("Archive ZIP corrompue (entrée du répertoire central).");68    const flags = buf.readUInt16LE(p + 8), method = buf.readUInt16LE(p + 10), packed = buf.readUInt32LE(p + 20), nameLen = buf.readUInt16LE(p + 28), extraLen = buf.readUInt16LE(p + 30), commentLen = buf.readUInt16LE(p + 32);69    const madeBy = buf.readUInt8(p + 5), attrs = buf.readUInt32LE(p + 38), local = buf.readUInt32LE(p + 42);70    const rawName = buf.toString("utf8", p + 46, p + 46 + nameLen);71    p += 46 + nameLen + extraLen + commentLen;72    const mode = madeBy === 3 ? (attrs >>> 16) & 0xf000 : 0;73    const kind = mode === 0xa000 ? "link" : rawName.endsWith("/") || mode === 0x4000 ? "dir" : mode !== 0 && mode !== 0x8000 ? "other" : "file";74    const name = sink.admit(rawName, kind);75    if (!name) continue;76    if (flags & 0x1) throw new ArchiveError("Archive chiffrée refusée.");77    if (method !== 0 && method !== 8) throw new ArchiveError(`Méthode de compression non prise en charge (${method}).`);78    if (local + 30 > buf.length || buf.readUInt32LE(local) !== 0x04034b50) throw new ArchiveError("Archive ZIP corrompue (en-tête local).");79    const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);80    if (start + packed > buf.length) throw new ArchiveError("Archive ZIP tronquée.");81    const raw = buf.subarray(start, start + packed);82    let data: Buffer;83    if (method === 0) data = raw;84    else {85      // The inflater stops by itself past the per-file limit: the declared size is never trusted.86      try { data = inflateRawSync(raw, { maxOutputLength: limits.maxFileBytes + 1 }); }87      catch (e) { throw new ArchiveError((e as NodeJS.ErrnoException).code === "ERR_BUFFER_TOO_LARGE" ? `Archive refusée : un fichier dépasse ${Math.round(limits.maxFileBytes / 1e6)} Mo une fois décompressé.` : "Archive ZIP corrompue (données compressées)."); }88    }89    sink.grow(data.length, data.length);90    await sink.write(name, data);91  }92}9394/* ---- tar.gz (ustar and pax as written by `git archive` and by tar) ---- */9596async function extractTarGz(file: string, sink: Sink): Promise<void> {97  const stream = createReadStream(file).pipe(createGunzip());98  let pending: Buffer = Buffer.alloc(0);99  let current: { name: string | null; left: number; pad: number; chunks: Buffer[]; size: number; pax: boolean } | null = null;100  let longName: string | null = null, zeros = 0;101  const str = (b: Buffer, a: number, n: number) => { const s = b.subarray(a, a + n); const z = s.indexOf(0); return s.toString("utf8", 0, z < 0 ? n : z); };102  const handle = async (chunk: Buffer) => {103    pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;104    for (;;) {105      if (current) {106        if (current.left > 0) {107          if (!pending.length) return;108          const take = pending.subarray(0, Math.min(current.left, pending.length));109          pending = pending.subarray(take.length); current.left -= take.length; current.size += take.length;110          if (current.name !== null || current.pax) { if (current.name !== null) sink.grow(take.length, current.size); else if (current.size > 1_000_000) throw new ArchiveError("Archive tar corrompue (en-tête étendu démesuré)."); current.chunks.push(take); }111          if (current.left > 0) return;112        }113        if (pending.length < current.pad) return;114        pending = pending.subarray(current.pad);115        const data = Buffer.concat(current.chunks);116        if (current.pax) { const m = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(data.toString("utf8")); if (m) longName = m[1]!; }117        else if (current.name !== null) await sink.write(current.name, data);118        current = null;119      }120      if (pending.length < 512) return;121      const h = pending.subarray(0, 512);122      pending = pending.subarray(512);123      if (h.every((b) => b === 0)) { if (++zeros >= 2) { pending = Buffer.alloc(0); return; } continue; }124      zeros = 0;125      const size = parseInt(str(h, 124, 12).trim() || "0", 8), type = String.fromCharCode(h[156] || 48);126      if (!Number.isFinite(size) || size < 0) throw new ArchiveError("Archive tar corrompue (taille invalide).");127      const pad = (512 - (size % 512)) % 512, prefix = str(h, 345, 155), rawName = longName ?? (prefix ? `${prefix}/${str(h, 0, 100)}` : str(h, 0, 100));128      if (type === "x" || type === "L") { current = { name: null, left: size, pad, chunks: [], size: 0, pax: true }; continue; } // name of the next entry129      if (type === "g") { current = { name: null, left: size, pad, chunks: [], size: 0, pax: false }; continue; }               // global pax header: ignored130      longName = null;131      const kind = type === "0" || type === "7" ? "file" : type === "5" ? "dir" : type === "1" || type === "2" ? "link" : "other";132      current = { name: sink.admit(rawName, kind), left: size, pad, chunks: [], size: 0, pax: false };133    }134  };135  try { for await (const chunk of stream) await handle(chunk as Buffer); }136  catch (e) { if (e instanceof ArchiveError) throw e; throw new ArchiveError("Archive .tar.gz illisible ou corrompue."); }137  finally { stream.destroy(); }138}139140/** Extracts `file` into the new, empty directory `dest`. Throws `ArchiveError` on anything suspicious. */141export async function extractArchive(file: string, dest: string, limits: ExtractLimits = DEFAULT_LIMITS): Promise<ExtractReport> {142  const fh = await open(file, "r");143  let head: Buffer, packed: number;144  try { head = Buffer.alloc(4); await fh.read(head, 0, 4, 0); packed = (await fh.stat()).size; } finally { await fh.close(); }145  await mkdir(dest, { recursive: true });146  const sink = new Sink(dest, limits, packed);147  if (head[0] === 0x50 && head[1] === 0x4b) await extractZip(file, sink, limits);148  else if (head[0] === 0x1f && head[1] === 0x8b) await extractTarGz(file, sink);149  else throw new ArchiveError("Format d'archive non reconnu : .zip ou .tar.gz attendu.");150  return sink.report;151}152153/** One file of a tar archive (ustar; names up to 255 bytes through the prefix field). */154export function tarEntry(name: string, data: Buffer, mtime = new Date()): Buffer {155  const h = Buffer.alloc(512);156  let base = name, prefix = "";157  if (Buffer.byteLength(base) > 100) { const cut = name.lastIndexOf("/", 154); prefix = name.slice(0, cut); base = name.slice(cut + 1); }158  if (Buffer.byteLength(base) > 100 || Buffer.byteLength(prefix) > 155) throw new Error(`nom trop long pour une archive tar : ${name}`);159  h.write(base, 0, 100, "utf8"); h.write("0000644\0", 100); h.write("0000000\0", 108); h.write("0000000\0", 116);160  h.write(`${data.length.toString(8).padStart(11, "0")}\0`, 124); h.write(`${Math.floor(mtime.getTime() / 1000).toString(8).padStart(11, "0")}\0`, 136);161  h.write("        ", 148); h.write("0", 156); h.write("ustar\0", 257); h.write("00", 263); h.write(prefix, 345, 155, "utf8");162  h.write(`${h.reduce((a, b) => a + b, 0).toString(8).padStart(6, "0")}\0 `, 148);163  return Buffer.concat([h, data, Buffer.alloc((512 - (data.length % 512)) % 512)]);164}165export const TAR_END = Buffer.alloc(1024);166
Files main
Menu

Theme