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
5 changes: 3 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ T3_SETUP_BASE_PATH=
# tunnel, proxy or hosting platform needs a single upstream. Publish it in
# place of the two ports in compose.yaml.
T3_SINGLE_PORT=
# Trust forwarding headers only when that port is reachable solely through
# your TLS-terminating proxy or tunnel. Keep 0 for a directly reached listener.
# Trust forwarding headers for the one-port router or the direct Setup port
# only when reachable solely through your TLS-terminating proxy or tunnel.
# Keep 0 for a directly reached listener.
T3_TRUST_PROXY_HEADERS=0

# How long links minted by t3-pair and the setup UI stay redeemable.
Expand Down
3 changes: 3 additions & 0 deletions docker/router/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ const where = config.setup
? `T3 Code (port ${config.t3.port}) at /, the setup page (port ${config.setup.port}) at ${config.setupPrefix}`
: `T3 Code (port ${config.t3.port}); the setup page is off`;
log(`listening on ${host === "::" ? "[::]" : host}:${config.port}: ${where}`);
if (config.trustedProxy) {
log("WARNING: T3_TRUST_PROXY_HEADERS=1 trusts X-Forwarded-Proto/Host from the proxy. Keep this only when this port is reachable solely through your TLS-terminating proxy or tunnel: anyone who can reach it directly can spoof the scheme and host the services behind it see.");
}

// Stop taking connections, let what is in flight finish briefly, then go.
const stop = () => {
Expand Down
14 changes: 11 additions & 3 deletions docker/setup/client-address.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,20 @@ export const isLoopback = (address) => {
return plain === "::1" || /^127\.\d+\.\d+\.\d+$/.test(plain);
};

/** The visitor's address: the socket's peer, or the router's word for it. */
export function clientAddress(req) {
/** The visitor's address: the peer, or an explicitly trusted proxy's report. */
export function clientAddress(req, { trustProxyHeaders = false } = {}) {
const peer = plainAddress(req?.socket?.remoteAddress) || "?";
if (!isLoopback(peer)) return peer;
if (!trustsProxyHeaders(req, trustProxyHeaders)) return peer;
const header = req?.headers?.["x-forwarded-for"];
const forwarded = (Array.isArray(header) ? header.join(",") : String(header ?? "")).split(",");
const last = plainAddress(forwarded[forwarded.length - 1].trim());
return isIP(last) ? last : peer;
}

/** Whether the request arrived over loopback, as the in-container router does. */
export const peerIsLoopback = (req) => isLoopback(plainAddress(req?.socket?.remoteAddress));

// Direct Setup deployments can opt in to their TLS proxy using the same
// explicit trust setting as the single-port router. Never infer trust from
// request headers or accept a truthy string as authorization.
export const trustsProxyHeaders = (req, configured = false) => peerIsLoopback(req) || configured === true;
31 changes: 24 additions & 7 deletions docker/setup/key-throttle.mjs
Original file line number Diff line number Diff line change
@@ -1,22 +1,39 @@
// Every supplied setup-key guess, including cookies and headers, takes a slot
// before the secret is compared. Failures keep their slots through a per-IP
// serialized delay. Successful authentication releases immediately.
export function createKeyThrottle({ matches, wait = ms => new Promise(resolve => setTimeout(resolve, ms)), perAddress = 4, pendingLimit = 256, failureLimit = 1000 } = {}) {
const active = new Map(), tails = new Map(), failures = new Map();
//
// After enough failures from one address it is locked out: further guesses
// are refused at once, for a growing window, without taking a slot or
// queuing another delayed check. A locked-out flood therefore holds no room
// in the shared pending cap, so other visitors keep getting answers.
export function createKeyThrottle({ matches, wait = ms => new Promise(resolve => setTimeout(resolve, ms)), perAddress = 4, pendingLimit = 256, failureLimit = 1000, lockoutAfter = 20, lockoutBaseMs = 30_000, lockoutMaxMs = 15 * 60 * 1000, now = () => Date.now() } = {}) {
const active = new Map(), tails = new Map(), failures = new Map(), lockedUntil = new Map();
let pending = 0;
const lockoutFor = (strikes) => Math.min(lockoutBaseMs * 2 ** Math.floor((strikes - lockoutAfter) / 5), lockoutMaxMs);
return {
clearFailures() { failures.clear(); },
clearFailures() { failures.clear(); lockedUntil.clear(); },
async check(ip, candidate) {
// Locked out: refuse at once, before taking any shared slot, so a
// guessing flood stops crowding out everyone else's attempts.
const until = lockedUntil.get(ip);
if (until !== undefined) {
if (now() < until) throw Object.assign(new Error('Too many login attempts. Wait a moment and try again.'), { code: 'login-limit' });
lockedUntil.delete(ip);
}
const count = active.get(ip) ?? 0;
if (count >= perAddress || pending >= pendingLimit) throw Object.assign(new Error('Too many login attempts. Wait a moment and try again.'), { code: 'login-limit' });
active.set(ip, count + 1); pending++;
try {
if (matches(candidate)) { failures.delete(ip); return true; }
if (matches(candidate)) { failures.delete(ip); lockedUntil.delete(ip); return true; }
const run = (tails.get(ip) ?? Promise.resolve()).then(() => {
const n = Math.min((failures.get(ip) ?? 0) + 1, 12);
failures.delete(ip); failures.set(ip, n);
const strikes = (failures.get(ip) ?? 0) + 1;
failures.delete(ip); failures.set(ip, strikes);
if (failures.size > failureLimit) failures.delete(failures.keys().next().value);
return wait(n * 250);
if (strikes >= lockoutAfter) {
lockedUntil.delete(ip); lockedUntil.set(ip, now() + lockoutFor(strikes));
if (lockedUntil.size > failureLimit) lockedUntil.delete(lockedUntil.keys().next().value);
}
return wait(Math.min(strikes, 12) * 250);
});
const tail = run.catch(() => {});
tails.set(ip, tail);
Expand Down
36 changes: 35 additions & 1 deletion docker/setup/request-auth.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,14 @@ export function cookieValue(header, name) {
* usable. A proxy that rewrites the path is supposed to say so: nginx and
* Traefik send X-Forwarded-Prefix, and when the path itself no longer
* carries the prefix, that header is the only thing left that knows it.
*
* Only believed when `trusted` - from a direct peer the header is the
* visitor's own words, and must not become the cookie path or where
* redirects point. Callers pass whether the socket peer is loopback
* (client-address.mjs); the default keeps existing callers' behavior.
*/
export function forwardedPrefix(headers) {
export function forwardedPrefix(headers, { trusted = true } = {}) {
if (!trusted) return "";
const raw = headers?.["x-forwarded-prefix"];
if (typeof raw !== "string") return "";
const trimmed = raw.trim().replace(/\/+$/, "");
Expand All @@ -48,3 +54,31 @@ export function forwardedPrefix(headers) {
if (trimmed.split("/").slice(1).some((segment) => segment === "" || segment === "." || segment === "..")) return "";
return trimmed;
}

/**
* The scheme a proxy says the visitor used, lowercased, or "" when it said
* nothing. Only believed when `trusted`: from a direct peer the header is
* the visitor's own words, and must not decide the session cookie's Secure
* flag - a forged `https` over plain HTTP would set a cookie the browser
* then never sends back, and every login silently "fails".
*/
export function forwardedProto(headers, { trusted = true } = {}) {
if (!trusted) return "";
const raw = headers?.["x-forwarded-proto"];
const first = Array.isArray(raw) ? raw[0] : raw;
return String(first ?? "").split(",")[0].trim().toLowerCase();
}

/**
* The host to show: what a proxy says the visitor asked for, else the Host
* the client sent here. Only believed when `trusted`: from a direct peer
* the header is the visitor's own words.
*/
export function forwardedHost(headers, { trusted = true } = {}) {
const direct = headers?.host;
const fallback = Array.isArray(direct) ? direct[0] : direct;
if (!trusted) return fallback;
const forwarded = headers?.["x-forwarded-host"];
const value = forwarded ?? fallback;
return Array.isArray(value) ? value[0] : value;
}
34 changes: 27 additions & 7 deletions docker/setup/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ import { createGatewayProcesses } from "./gateways/processes.mjs";
import { createGatewayT3 } from "./gateways/t3.mjs";
import { createGatewayVault } from "./gateways/vault.mjs";
import { createSessionStore, TERMINAL_STATES } from "./signin-sessions.mjs";
import { clientAddress } from "./client-address.mjs";
import { cookieValue, forwardedPrefix } from "./request-auth.mjs";
import { clientAddress, trustsProxyHeaders } from "./client-address.mjs";
import { cookieValue, forwardedHost, forwardedPrefix, forwardedProto } from "./request-auth.mjs";
import { createKeyThrottle } from "./key-throttle.mjs";
import { newKey, readKeyFile, validKey, writeKeyFile } from "./setup-key.mjs";
import { createCredentialStore, credentialFailure, CredentialError, credentialDirectory } from "./credentials.mjs";
Expand Down Expand Up @@ -1079,6 +1079,16 @@ const revoke = async ({ kind, id }) => {
};

const mintPairing = async ({ ttl, label }) => {
// argv, not a shell, but the CLI still parses a leading `-` as its own
// flag (`--ttl --help` prints help instead of issuing a pairing). Refuse
// flag-like values before anything else, so a bad ttl/label fails here
// rather than as a confusing error from further down.
if (ttl !== undefined && ttl !== null && ttl !== "" && (typeof ttl !== "string" || !/^[1-9][0-9]{0,6}[smhdw]$/.test(ttl))) {
throw new Error('invalid ttl: use a duration like "30d" (a number followed by s, m, h, d or w)');
}
if (label !== undefined && label !== null && label !== "" && (typeof label !== "string" || !label.isWellFormed() || label.length > 128 || label.startsWith("-") || /[\x00-\x1F\x7F-\x9F]/.test(label))) {
throw new Error("invalid label: use up to 128 characters without control characters or a leading -");
}
const { url } = publicUrl();
if (!url) {
throw new Error("Set the public URL first: a pairing link points at it, and without it a device has nowhere to go.");
Expand Down Expand Up @@ -2534,8 +2544,11 @@ const startStorageWork = async (storage, kind, input) => {

// The session cookie. Secure when the request reached us over HTTPS (directly
// or through a proxy that says so); a plain-http LAN address must still work.
// Trust the in-container router or an explicitly configured proxy. A direct
// visitor cannot choose the cookie's Secure flag through forwarding headers.
const proxyHeadersTrusted = req => trustsProxyHeaders(req, process.env.T3_TRUST_PROXY_HEADERS === "1");
const cookie = (req, mount, value, maxAge) => {
const secure = req.socket.encrypted || /^https$/i.test(String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim());
const secure = req.socket.encrypted || forwardedProto(req.headers, { trusted: proxyHeadersTrusted(req) }) === "https";
return `${COOKIE}=${value}; HttpOnly; SameSite=Strict; Path=${mount || "/"}; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
};

Expand Down Expand Up @@ -2633,13 +2646,13 @@ const resolve = (pathname) => {

const server = createServer(async (req, res) => {
// The visitor, not the router in front of them: see client-address.mjs.
const ip = clientAddress(req);
const ip = clientAddress(req, { trustProxyHeaders: process.env.T3_TRUST_PROXY_HEADERS === "1" });
const raw = new URL(req.url ?? "/", "http://localhost");
const resolved = resolve(raw.pathname);
const route = resolved.route;
// The inferred mount wins when the prefix survived the hop; otherwise fall
// back to what the proxy declared.
const mount = resolved.mount || forwardedPrefix(req.headers);
// back to a trusted proxy's prefix. Direct visitors cannot choose it.
const mount = resolved.mount || forwardedPrefix(req.headers, { trusted: proxyHeadersTrusted(req) });
// The page sends a cookie; the in-container CLIs send a header. Same key,
// same comparison - so `t3-expose` and the page are the same client as far
// as this server is concerned, and neither can act on state the other cannot.
Expand Down Expand Up @@ -2719,7 +2732,8 @@ const server = createServer(async (req, res) => {
if (route === "/") {
if (authed) return sendPage(req, res, (nonce) => renderConsole({ assets: ASSETS, nonce, mount, embed, host, layout }));
// The host the browser asked for, for the card's eyebrow; escaped by the template.
const hostname = String(req.headers["x-forwarded-host"] ?? req.headers.host ?? "").split(",")[0].trim().slice(0, 200);
// Forwarded host names require the same explicit trust as the scheme.
const hostname = String(forwardedHost(req.headers, { trusted: proxyHeadersTrusted(req) }) ?? "").split(",")[0].trim().slice(0, 200);
return sendPage(req, res, (nonce) => renderUnlock({
assets: ASSETS, nonce, mount, host, hostname, layout, publicUrl: publicUrl().url, error: raw.searchParams.get("error") === "1", embed,
}));
Expand Down Expand Up @@ -2984,6 +2998,12 @@ const server = createServer(async (req, res) => {
if (req.method === "POST" && route === "/ports/expose") {
try {
const input = JSON.parse((await readBody(req)) || "{}");
// A quick tunnel has nothing in front of it, so a dev database must
// not be published by port number alone: refuse looks-like-database
// ports unless the request says it means it.
if (looksLikeDatabase(Number(input.port)) && input.confirmDatabase !== true) {
return sendJson(res, 400, { error: `Port ${Number(input.port)} looks like a database. Resend with {"confirmDatabase": true} to publish it anyway.` });
}
return sendJson(res, 200, publicTunnel(startTunnel(input.port)));
} catch (error) {
return sendJson(res, 400, { error: String(error?.message ?? error) });
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Environment variables (all optional except where noted):
| `T3_PRINT_SETUP_KEY` | `0` | Print a generated setup key to the log in full on a first/ephemeral start. Without it, only a SHA-256 fingerprint is logged. Prefer retrieving the owner-only key file; opt in only when the hosting platform has no shell. |
| `T3_SETUP_PORT` | `3774` | Setup page port inside the container |
| `T3_SETUP_BASE_PATH` | — | Serve the setup page under a path, such as `/__setup` |
| `T3_TRUST_PROXY_HEADERS` | `0` | Trust the `X-Forwarded-Proto`/`Host` the proxy in front of `T3_SINGLE_PORT` set (`1` only when that port is reachable solely through your TLS-terminating proxy or tunnel) |
| `T3_TRUST_PROXY_HEADERS` | `0` | Trust forwarding headers from the proxy in front of `T3_SINGLE_PORT` or the direct Setup listener. This preserves the external HTTPS scheme, host, path prefix and visitor address. Use `1` only when the listener is reachable solely through your trusted proxy or tunnel. Loopback requests from the in-container router remain trusted. |
| `T3_SINGLE_PORT` | — | Also serve T3 Code and the setup page together on this port, the setup page under `/__setup`, for a tunnel, proxy or hosting platform that routes one port. See [Exposing it through one hostname](remote-access.md#exposing-it-through-one-hostname). |
| `T3_SETUP_ACCEPT_T3_SESSIONS` | `1` | Let a browser signed in to T3 Code with terminal access open the setup page without the key. `0` always asks for the key. |
| `T3_ALLOW_SUDO` | `0` | Give agents passwordless sudo in the container |
Expand Down
Loading
Loading