SPB Git

Repository Public

ssrf.ts 8.4 KB 149 lines typescript

1import net from "node:net";2import dns from "node:dns";3import { Agent, fetch as ufetch, type Response } from "undici";4import { env } from "./env";56// SSRF guard for every server-side request to a user- or playlist-supplied URL (source import, stream checks, XMLTV).7// 1. only http/https, no credentials; 2. literal IPs are checked directly; 3. host names are checked at connection time8// (the guarded lookup below is the one the socket uses, so a DNS answer cannot change between check and connect);9// 4. redirects are followed by hand and every hop goes through the same checks.10const blocked = new net.BlockList();11for (const [a, p] of [12  ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16], ["172.16.0.0", 12],13  ["192.0.0.0", 24], ["192.0.2.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24],14  ["224.0.0.0", 4], ["240.0.0.0", 4],15] as const) blocked.addSubnet(a, p, "ipv4");16for (const [a, p] of [["::", 128], ["::1", 128], ["fc00::", 7], ["fe80::", 10], ["ff00::", 8], ["2001:db8::", 32], ["64:ff9b::", 96]] as const) blocked.addSubnet(a, p, "ipv6");1718export function isBlockedIp(ip: string): boolean {19  if (env.allowPrivateHosts) return false;20  const v = net.isIP(ip);21  if (v === 4) return blocked.check(ip, "ipv4");22  if (v === 6) {23    const m = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(ip);24    if (m) return blocked.check(m[1], "ipv4");25    return blocked.check(ip, "ipv6");26  }27  return true;28}2930export class UrlRejected extends Error {}3132export function assertPublicUrl(raw: string): URL {33  let u: URL;34  try { u = new URL(raw); } catch { throw new UrlRejected("URL invalide"); }35  if (u.protocol !== "http:" && u.protocol !== "https:") throw new UrlRejected(`Protocole non autorisé : ${u.protocol.replace(":", "")}`);36  if (u.username || u.password) throw new UrlRejected("Les identifiants dans l'URL ne sont pas autorisés");37  const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();38  if (!host) throw new UrlRejected("Hôte manquant");39  if (!env.allowPrivateHosts && (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".lan")))40    throw new UrlRejected("Hôte interne refusé");41  if (net.isIP(host) && isBlockedIp(host)) throw new UrlRejected("Adresse privée ou réservée refusée");42  return u;43}4445const guardedLookup: net.LookupFunction = (hostname, options, cb) => {46  dns.lookup(hostname, { ...(options as dns.LookupOptions), all: true }, (err, addresses) => {47    if (err) return cb(err, "", 0);48    const list = addresses as dns.LookupAddress[];49    if (!list.length || list.some((a) => isBlockedIp(a.address))) {50      const e = Object.assign(new Error(`Résolution vers une adresse privée refusée (${hostname})`), { code: "ESSRF" });51      return cb(e, "", 0);52    }53    if ((options as dns.LookupOptions).all) return (cb as unknown as (e: null, a: dns.LookupAddress[]) => void)(null, list);54    cb(null, list[0].address, list[0].family);55  });56};5758const agent = new Agent({ connect: { lookup: guardedLookup, timeout: 8000, rejectUnauthorized: true }, headersTimeout: 150_000, bodyTimeout: 150_000 });5960export interface SafeFetchOptions { headers?: Record<string, string>; timeoutMs?: number; maxRedirects?: number; method?: "GET" | "HEAD" }6162/** Fetch a public URL; throws UrlRejected for anything that points inside. The caller owns the response body. */63export async function safeFetch(raw: string, opts: SafeFetchOptions = {}): Promise<{ res: Response; finalUrl: string; signal: AbortController }> {64  const ctl = new AbortController();65  const timer = setTimeout(() => ctl.abort(new Error("Délai dépassé")), opts.timeoutMs ?? 20_000);66  let url = assertPublicUrl(raw);67  try {68    for (let hop = 0; ; hop++) {69      const res = await ufetch(url, { method: opts.method ?? "GET", headers: opts.headers, redirect: "manual", dispatcher: agent, signal: ctl.signal });70      if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {71        await res.body?.cancel().catch(() => {});72        if (hop >= (opts.maxRedirects ?? 5)) throw new Error("Trop de redirections");73        url = assertPublicUrl(new URL(res.headers.get("location")!, url).toString());74        continue;75      }76      // The timer keeps running: it also bounds the body read. Callers call signal.abort() or let it fire.77      res.body && ctl.signal.addEventListener("abort", () => clearTimeout(timer));78      return { res, finalUrl: url.toString(), signal: ctl };79    }80  } catch (e) { clearTimeout(timer); throw e; }81}8283/** Read at most `limit` bytes of a text body, then stop the download. */84export async function readText(res: Response, limit: number, ctl?: AbortController): Promise<string> {85  if (!res.body) return "";86  const reader = res.body.getReader();87  const chunks: Uint8Array[] = []; let size = 0;88  try {89    while (size < limit) {90      const { done, value } = await reader.read();91      if (done) break;92      chunks.push(value); size += value.byteLength;93    }94  } finally { reader.cancel().catch(() => {}); ctl?.abort(); }95  return Buffer.concat(chunks).subarray(0, limit).toString("utf8");96}9798/** Network hiccups (reset, DNS blip, timeout) are retried; a refused URL or an HTTP error status is not. */99async function retrying<T>(fn: () => Promise<T>, attempts = 3): Promise<T> {100  for (let i = 1; ; i++) {101    try { return await fn(); }102    catch (e) {103      const m = (e as Error).message;104      if (i >= attempts || e instanceof UrlRejected || /^HTTP \d|trop volumineuse/.test(m)) throw e;105      await new Promise((r) => setTimeout(r, 2000 * i * i));106    }107  }108}109export const fetchText = (url: string, limitBytes: number, timeoutMs = 60_000) => retrying(() => fetchTextOnce(url, limitBytes, timeoutMs));110async function fetchTextOnce(url: string, limitBytes: number, timeoutMs: number): Promise<string> {111  const { res, signal } = await safeFetch(url, { timeoutMs, headers: { "user-agent": "SP-TV/1.0 (personal catalogue sync)", accept: "*/*" } });112  if (!res.ok) { signal.abort(); throw new Error(`HTTP ${res.status}`); }113  const len = Number(res.headers.get("content-length") || 0);114  if (len > limitBytes) { signal.abort(); throw new Error(`Réponse trop volumineuse (${len} octets)`); }115  const text = await readText(res, limitBytes + 1, signal);116  if (Buffer.byteLength(text) > limitBytes) throw new Error("Réponse trop volumineuse");117  return text;118}119120export const fetchBuffer = (url: string, limitBytes: number, timeoutMs = 120_000) => retrying(() => fetchBufferOnce(url, limitBytes, timeoutMs));121async function fetchBufferOnce(url: string, limitBytes: number, timeoutMs: number): Promise<Buffer> {122  const { res, signal } = await safeFetch(url, { timeoutMs, headers: { "user-agent": "SP-TV/1.0 (personal catalogue sync)", accept: "*/*" } });123  if (!res.ok) { signal.abort(); throw new Error(`HTTP ${res.status}`); }124  const reader = res.body!.getReader();125  const chunks: Uint8Array[] = []; let size = 0;126  try {127    for (;;) {128      const { done, value } = await reader.read();129      if (done) break;130      size += value.byteLength;131      if (size > limitBytes) throw new Error("Réponse trop volumineuse");132      chunks.push(value);133    }134  } finally { reader.cancel().catch(() => {}); signal.abort(); }135  return Buffer.concat(chunks);136}137138// Sources the administrator declares on purpose inside the home network (a Jellyfin server): same timeouts and size139// limits, but private addresses are accepted. Never used for anything a playlist or a catalogue supplies.140const lanAgent = new Agent({ connect: { timeout: 8000 }, headersTimeout: 60_000, bodyTimeout: 60_000 });141export async function lanJson<T>(url: string, init: { method?: "GET" | "POST"; headers?: Record<string, string>; body?: unknown; timeoutMs?: number } = {}): Promise<T> {142  const u = new URL(url); if (u.protocol !== "http:" && u.protocol !== "https:") throw new UrlRejected("Protocole non autorisé");143  const res = await ufetch(u, { method: init.method ?? "GET", dispatcher: lanAgent, signal: AbortSignal.timeout(init.timeoutMs ?? 30_000), redirect: "error",144    headers: { accept: "application/json", ...(init.body ? { "content-type": "application/json" } : {}), ...init.headers }, body: init.body ? JSON.stringify(init.body) : undefined });145  if (!res.ok) { await res.body?.cancel().catch(() => {}); throw new Error(`HTTP ${res.status}`); }146  const text = await res.text(); if (text.length > 60 * 1024 * 1024) throw new Error("Réponse trop volumineuse");147  return JSON.parse(text) as T;148}149
Files main
Menu

Theme