Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Auth: block DNS-rebound hosts on password-less installs; throttle instead of locking the shared sign-in key

Claude632b4f4bb1ae
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
index d297f443..99c7da90 100644
--- a/src/app/api/auth/login/route.ts
+++ b/src/app/api/auth/login/route.ts
@@ -14,7 +14,13 @@ export async function POST(request: Request) {
const key = LoginGuard.clientKey(request.headers);
const wait = guard.blockedFor(key);
if (wait > 0) {
- return Response.json({ error: "Too many attempts. Wait a minute and try again." }, { status: 429, headers: { "Retry-After": String(Math.ceil(wait / 1000)) } });
+ const secs = Math.ceil(wait / 1000);
+ // Without a trusted proxy every visitor shares one limit (the hint is for whoever runs the server).
+ const hint = key === LoginGuard.DIRECT ? " Behind a reverse proxy? Set FUOBE_TRUST_PROXY=1 so each visitor gets their own limit." : "";
+ return Response.json(
+ { error: `Too many wrong passwords. Try again in ${secs} second${secs === 1 ? "" : "s"}.${hint}` },
+ { status: 429, headers: { "Retry-After": String(secs) } },
+ );
}
const parsed = Body.safeParse(await request.json().catch(() => null));
if (!parsed.success || !checkPassword(parsed.data.password)) {
diff --git a/src/proxy.ts b/src/proxy.ts
index db0b6339..409cf48e 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -1,10 +1,19 @@
import { NextResponse, type NextRequest } from "next/server";
-import { authEnabled, crossSite, SESSION_COOKIE, validSession, validToken } from "@/server/auth";
+import { authEnabled, crossSite, hostAllowed, SESSION_COOKIE, validSession, validToken } from "@/server/auth";
/** Paths that work signed out: the login page and its API. */
const OPEN = new Set(["/login", "/api/auth/login"]);
export function proxy(request: NextRequest) {
+ // DNS rebinding: a page whose own name now points at this machine. Every method, reads too. With a
+ // password set the sign-in check below already stops it (the session cookie belongs to the real name).
+ if (!authEnabled() && !hostAllowed(request.headers.get("host") ?? request.nextUrl.host)) {
+ const host = request.headers.get("host") ?? request.nextUrl.host;
+ return NextResponse.json(
+ { error: `Blocked a request for ${host}, which isn't a local address. If that's how you reach Fuobe, add it to FUOBE_ALLOWED_ORIGINS (or set a password).` },
+ { status: 403 },
+ );
+ }
// Before the sign-in check: a password-less install needs this most.
if (crossSite(request, request.nextUrl.host)) {
return NextResponse.json({ error: "Blocked a request from another website. Use Fuobe from its own address (or add it to FUOBE_ALLOWED_ORIGINS)." }, { status: 403 });
diff --git a/src/server/auth.ts b/src/server/auth.ts
index 5fb7d04e..621b971d 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -8,6 +8,8 @@
*/
import crypto from "node:crypto";
import fs from "node:fs";
+import net from "node:net";
+import os from "node:os";
import path from "node:path";
const DATA_DIR = path.resolve(/*turbopackIgnore: true*/ process.env.FUOBE_DATA_DIR ?? path.join(process.cwd(), "data"));
@@ -126,7 +128,7 @@ export function validSession(value: string | undefined): boolean {
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
-/** Extra addresses this studio is reached at (FUOBE_ALLOWED_ORIGINS="https://fuobe.example.com,studio.lan:3000"). */
+/** Extra addresses this studio is reached at (FUOBE_ALLOWED_ORIGINS="https://fuobe.example.com,studio.lan:3000", or "*" for any). */
function allowedHosts(): string[] {
return (process.env.FUOBE_ALLOWED_ORIGINS ?? "")
.split(",")
@@ -162,28 +164,66 @@ export function crossSite(request: Request, ownHost: string): boolean {
return !own.includes(host);
}
+// ---------------------------------------------------------------------------
+// DNS rebinding
+
+/** Host header → lower-case name without port or trailing dot ("[::1]:3000" → "::1"). */
+function hostName(host: string): string {
+ const h = host.trim().toLowerCase();
+ if (h.startsWith("[")) return h.slice(1, h.indexOf("]") >>> 0);
+ const colon = h.indexOf(":");
+ return (colon >= 0 && colon === h.lastIndexOf(":") ? h.slice(0, colon) : h).replace(/\.$/, "");
+}
+
+/** Names nobody on the internet can point at this machine: this machine, the LAN, reserved suffixes. */
+const LOCAL_SUFFIXES = [".localhost", ".local", ".lan", ".home.arpa", ".internal", ".localdomain"];
+
+/**
+ * Is this a name the studio may be reached at without a password? A page on attacker.example can
+ * re-point its own DNS name at 127.0.0.1 (DNS rebinding); the browser then treats the local studio
+ * as attacker.example and lets the page read and change it. Such a request carries the attacker's
+ * name in Host, so only addresses that can't be rebound pass: IP literals, localhost, single-label
+ * and LAN names (.local, .lan, .home.arpa, .internal), this machine's hostname, and
+ * FUOBE_ALLOWED_ORIGINS. X-Forwarded-Host is not trusted here: a rebound page can set it.
+ */
+export function hostAllowed(host: string | null): boolean {
+ if (!host) return true; // HTTP/1.0 clients and tools; browsers always send Host
+ const name = hostName(host);
+ if (!name || net.isIP(name) || !name.includes(".") || LOCAL_SUFFIXES.some((s) => name.endsWith(s))) return true;
+ const self = os.hostname().toLowerCase();
+ if (name === self || name === self.split(".")[0]) return true;
+ return allowedHosts().some((a) => {
+ const entry = a.toLowerCase();
+ return entry === "*" || entry === host.trim().toLowerCase() || (!entry.includes(":") && entry === name);
+ });
+}
+
// ---------------------------------------------------------------------------
// Sign-in attempts
/**
- * Wrong-password lockout. Route handlers can't see the socket address, and Next keeps any
+ * Wrong-password limits. Route handlers can't see the socket address, and Next keeps any
* X-Forwarded-For a client sends, so that header only identifies a client behind a reverse proxy
- * you trust (FUOBE_TRUST_PROXY=1; the proxy's own entry is the last one). Otherwise every client
- * shares one budget. A global budget caps guesses even when the per-client key is spoofed.
+ * you trust (FUOBE_TRUST_PROXY=1; the proxy's own entry is the last one): such a client is locked
+ * out for a minute after 5 misses. Otherwise every client shares the "direct" key, and a lock
+ * would let anyone keep the owner out, so a spent budget slows sign-in down to one attempt every
+ * few seconds instead (about 15 guesses a minute). Past the global budget the same throttle
+ * applies to everyone, however the key is spoofed.
*/
export class LoginGuard {
+ static readonly DIRECT = "direct";
private failures = new Map<string, { n: number; first: number; until: number }>();
private recent: number[] = [];
constructor(
- private readonly o = { perClient: 5, global: 20, windowMs: 60_000, lockMs: 60_000, maxClients: 5000 },
+ private readonly o = { perClient: 5, global: 20, windowMs: 60_000, lockMs: 60_000, throttleMs: 4_000, maxClients: 5000 },
) {}
/** Who is signing in: the last X-Forwarded-For hop when a trusted proxy sets it, else one shared key. */
static clientKey(headers: Headers, trustProxy = process.env.FUOBE_TRUST_PROXY === "1"): string {
- if (!trustProxy) return "direct";
+ if (!trustProxy) return LoginGuard.DIRECT;
const hops = (headers.get("x-forwarded-for") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
- return hops.at(-1) ?? "direct";
+ return hops.at(-1) ?? LoginGuard.DIRECT;
}
/** Milliseconds until this client may try again (0 = now). */
@@ -191,8 +231,10 @@ export class LoginGuard {
this.recent = this.recent.filter((t) => now - t < this.o.windowMs);
const f = this.failures.get(key);
const own = f && f.until > now ? f.until - now : 0;
- const global = this.recent.length >= this.o.global ? this.o.windowMs - (now - this.recent[0]) : 0;
- return Math.max(own, global);
+ const shared = key === LoginGuard.DIRECT && !!f && now - f.first <= this.o.windowMs && f.n >= this.o.perClient;
+ const last = this.recent.at(-1);
+ const throttle = (shared || this.recent.length >= this.o.global) && last !== undefined ? Math.max(0, last + this.o.throttleMs - now) : 0;
+ return Math.max(own, throttle);
}
fail(key: string, now = Date.now()): void {
@@ -201,7 +243,9 @@ export class LoginGuard {
const fresh = !f || now - f.first > this.o.windowMs;
const n = fresh ? 1 : f.n + 1;
this.failures.delete(key);
- this.failures.set(key, { n, first: fresh ? now : f.first, until: n >= this.o.perClient ? now + this.o.lockMs : 0 });
+ // The shared key is throttled (blockedFor), never locked.
+ const locks = key !== LoginGuard.DIRECT && n >= this.o.perClient;
+ this.failures.set(key, { n, first: fresh ? now : f.first, until: locks ? now + this.o.lockMs : 0 });
// Forget old entries; never let the map grow without bound.
for (const [k, v] of this.failures) {
if (this.failures.size <= this.o.maxClients && now - v.first < this.o.windowMs * 10) break;
diff --git a/tests/runtime-auth.test.ts b/tests/runtime-auth.test.ts
index cf88dc84..6455d5cc 100644
--- a/tests/runtime-auth.test.ts
+++ b/tests/runtime-auth.test.ts
@@ -42,6 +42,49 @@ describe("cross-site requests (S8)", () => {
});
});
+describe("DNS rebinding", () => {
+ const ok = (r: Response) => r.headers.get("x-middleware-next") === "1";
+ const at = (host: string, init: { method?: string; headers?: Record<string, string> } = {}) =>
+ proxy(new NextRequest(`http://${host}/api/generations`, { method: init.method ?? "GET", headers: { host, ...init.headers }, ...(init.method === "POST" && { body: "{}" }) }));
+
+ it("refuses a name that was re-pointed at this machine, reads included, while no password is set", async () => {
+ expect(auth.authEnabled()).toBe(false);
+ // The attacker's page and its requests share one origin, so the Origin check alone lets them through.
+ const read = at("rebind.attacker.example:3000");
+ expect(read.status).toBe(403);
+ expect((await read.json()).error).toMatch(/FUOBE_ALLOWED_ORIGINS/);
+ expect(at("rebind.attacker.example:3000", { method: "POST", headers: { origin: "http://rebind.attacker.example:3000" } }).status).toBe(403);
+ // A forwarded host is no way around it (the page can set that header itself).
+ expect(at("rebind.attacker.example", { headers: { "x-forwarded-host": "localhost:3000" } }).status).toBe(403);
+ });
+
+ it("lets local addresses, LAN names, this machine and allow-listed names through", () => {
+ for (const host of ["localhost:3000", "127.0.0.1:3000", "[::1]:3000", "192.168.1.5:3000", "studio.localhost", "nas:3000", "studio.local", "box.lan:3000", "fuobe.home.arpa", `${os.hostname()}:3000`]) {
+ expect(ok(at(host)), host).toBe(true);
+ }
+ process.env.FUOBE_ALLOWED_ORIGINS = "https://fuobe.example.com,studio.example.org:8443";
+ try {
+ expect(ok(at("fuobe.example.com"))).toBe(true);
+ expect(ok(at("studio.example.org:8443"))).toBe(true);
+ expect(at("studio.example.org:9999").status).toBe(403);
+ expect(at("rebind.attacker.example").status).toBe(403);
+ } finally {
+ delete process.env.FUOBE_ALLOWED_ORIGINS;
+ }
+ expect(auth.hostAllowed(null)).toBe(true);
+ });
+
+ it("leaves it to the sign-in check once a password is set", () => {
+ auth.setPassword("correct horse battery");
+ try {
+ // Signed out: sent to sign in (the rebound page has no session cookie for its name).
+ expect(at("fuobe.example.com").status).toBe(401);
+ } finally {
+ auth.setPassword(null);
+ }
+ });
+});
+
describe("sign-in lockout (S10)", () => {
it("ignores spoofed X-Forwarded-For unless a trusted proxy sets it", () => {
const h = (xff: string) => new Headers({ "x-forwarded-for": xff });
@@ -49,22 +92,44 @@ describe("sign-in lockout (S10)", () => {
expect(auth.LoginGuard.clientKey(h("6.6.6.6, 1.2.3.4"), true)).toBe("1.2.3.4");
});
- it("locks a client after 5 misses, and everyone after too many misses overall", () => {
- const g = new auth.LoginGuard({ perClient: 5, global: 20, windowMs: 60_000, lockMs: 60_000, maxClients: 5000 });
+ const limits = { perClient: 5, global: 20, windowMs: 60_000, lockMs: 60_000, throttleMs: 4_000, maxClients: 5000 };
+
+ it("locks a client of its own after 5 misses, and slows everyone down after too many misses overall", () => {
+ const g = new auth.LoginGuard(limits);
const t = 1_000_000;
for (let i = 0; i < 4; i++) g.fail("a", t + i);
expect(g.blockedFor("a", t + 5)).toBe(0);
g.fail("a", t + 5);
expect(g.blockedFor("a", t + 6)).toBeGreaterThan(50_000);
expect(g.blockedFor("b", t + 6)).toBe(0);
- // Rotating the key doesn't help: the global budget runs out.
+ // Rotating the key doesn't help: past the global budget everyone gets one try every few seconds.
for (let i = 0; i < 15; i++) g.fail(`spoof-${i}`, t + 10 + i);
expect(g.blockedFor("fresh", t + 30)).toBeGreaterThan(0);
+ expect(g.blockedFor("fresh", t + 30)).toBeLessThanOrEqual(4_000);
+ expect(g.blockedFor("fresh", t + 24 + 4_000)).toBe(0);
expect(g.blockedFor("fresh", t + 120_000)).toBe(0);
});
+ it("never locks the shared key: the owner still gets in within seconds while guesses stay capped", () => {
+ const g = new auth.LoginGuard(limits);
+ const key = auth.LoginGuard.DIRECT;
+ const t = 2_000_000;
+ // An attacker hammering the login page for a minute, as fast as it's allowed.
+ let tries = 0;
+ for (let now = t; now < t + 60_000; now += 100) {
+ if (g.blockedFor(key, now) > 0) continue;
+ g.fail(key, now);
+ tries++;
+ }
+ expect(tries).toBeLessThanOrEqual(20);
+ // The owner waits at most one throttle step, never a full lock.
+ const wait = g.blockedFor(key, t + 60_000);
+ expect(wait).toBeLessThanOrEqual(4_000);
+ expect(g.blockedFor(key, t + 60_000 + wait)).toBe(0);
+ });
+
it("keeps its memory bounded", () => {
- const g = new auth.LoginGuard({ perClient: 5, global: 1e9, windowMs: 60_000, lockMs: 60_000, maxClients: 100 });
+ const g = new auth.LoginGuard({ ...limits, global: 1e9, maxClients: 100 });
for (let i = 0; i < 5000; i++) g.fail(`k${i}`, 1_000_000 + i);
expect(g.size).toBeLessThanOrEqual(101);
});