Harden the login flow: new session at sign-in, signed ID tokens, same-origin requests, headers
From an audit of the Authentik login, run against a fake OIDC provider: - Session fixation: the session id wasn't changed at sign-in, so one planted beforehand (from another page on the domain) became signed in as the victim. It is regenerated now. - Requests from another origin: SameSite=Lax doesn't stop another app on the same parent domain, and a body-less POST (stop a guest, rotate a token) needs no preflight. Every POST/PUT/PATCH/DELETE, and GET /auth/logout, is refused when Sec-Fetch-Site (or, for older browsers, Origin) says it came from elsewhere. The agent endpoint is exempt: it uses a token. - ID token signature: openid-client checks a token's claims but, as OIDC allows for a token from the token endpoint, not its signature, so the login rested on HTTPS to Authentik alone. The signature is now verified against the provider's published keys (jose, now a declared dependency). - SESSION_SECRET: production refuses to start without one (the fallback is in the source code) and warns when it is the .env.example placeholder or short. - Response headers: frame-ancestors 'none', X-Frame-Options, nosniff, Referrer-Policy; the framework name is no longer sent. - A failed sign-in shows a plain page and is audited (session / login_failed, with address and reason, no tokens); sign-in is limited to 20 attempts a minute per address so the audit log and session store can't be flooded. - A failed OIDC discovery (provider down at the first sign-in) was remembered until restart; it is retried now. Tests run the real app against the fake provider; switching each fix off in turn makes the matching tests fail. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
73b86d88de
commit
2dac273b1d
12 files changed
+681
-18
No files matched your search
@@ -0,0 +1,37 @@
|
||||
import * as client from "openid-client";
|
||||
import { createRemoteJWKSet, jwtVerify } from "jose";
|
||||
import { env } from "../env.js";
|
||||
|
||||
const keySets = new WeakMap<client.Configuration, ReturnType<typeof createRemoteJWKSet>>();
|
||||
|
||||
/**
|
||||
* Checks the ID token's signature against the keys the identity provider publishes.
|
||||
*
|
||||
* openid-client already checks the token's claims (issuer, audience, expiry, subject) but, as OpenID Connect allows for a token
|
||||
* received straight from the token endpoint, not its signature: it takes the HTTPS connection to the provider as proof of where
|
||||
* the token came from. That makes the whole login only as strong as that connection — if certificate checking toward the
|
||||
* provider is ever switched off (the usual way to cope with an internal CA is NODE_TLS_REJECT_UNAUTHORIZED=0), anyone on the
|
||||
* network path could hand the app a token naming any user, the admin included. Verifying the signature as well means a weakened
|
||||
* connection no longer lets a forged login through.
|
||||
*
|
||||
* Throws if the signature is wrong or the provider publishes no keys.
|
||||
*/
|
||||
export async function verifyIdTokenSignature(config: client.Configuration, idToken: string): Promise<void> {
|
||||
const metadata = config.serverMetadata();
|
||||
if (!metadata.jwks_uri) throw new Error("The identity provider publishes no signing keys (no jwks_uri).");
|
||||
|
||||
let keys = keySets.get(config);
|
||||
if (!keys) {
|
||||
// Fetched on demand and cached; an unknown key id (the provider rotated its key) triggers a re-fetch.
|
||||
keys = createRemoteJWKSet(new URL(metadata.jwks_uri));
|
||||
keySets.set(config, keys);
|
||||
}
|
||||
|
||||
await jwtVerify(idToken, keys, {
|
||||
issuer: metadata.issuer,
|
||||
audience: env.authentik.clientId,
|
||||
// The one algorithm openid-client itself accepts unless told otherwise, so this can't turn away a token the library would take.
|
||||
algorithms: [config.clientMetadata().id_token_signed_response_alg ?? "RS256"],
|
||||
clockTolerance: 60,
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,10 @@ export function getOidcConfig(): Promise<client.Configuration> {
|
||||
env.authentik.clientId,
|
||||
env.authentik.clientSecret,
|
||||
);
|
||||
// If the provider was unreachable this time, try again on the next sign-in — not never, until the app is restarted.
|
||||
configPromise.catch(() => {
|
||||
configPromise = null;
|
||||
});
|
||||
}
|
||||
return configPromise;
|
||||
}
|
||||
+74
-18
@@ -1,4 +1,4 @@
|
||||
import { Router } from "express";
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import * as client from "openid-client";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { getOidcConfig } from "./oidc.js";
|
||||
@@ -7,12 +7,54 @@ import { env } from "../env.js";
|
||||
import { db } from "../db/client.js";
|
||||
import { users } from "../db/schema.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { verifyIdTokenSignature } from "./idToken.js";
|
||||
import { rateLimit } from "../utils/rateLimit.js";
|
||||
|
||||
export const authRouter = Router();
|
||||
|
||||
authRouter.get("/login", async (req, res, next) => {
|
||||
// Anyone can reach these two without an account. Each visit to /login starts a session and each failed callback is written to the
|
||||
// audit log, so without a limit one script could fill the disk and the log.
|
||||
const signInLimiter = rateLimit({ windowMs: 60_000, max: 20, message: "Too many sign-in attempts. Wait a minute and try again." });
|
||||
|
||||
const SIGN_IN_FAILED_PAGE = `<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sign-in failed</title></head>
|
||||
<body style="font-family: system-ui, sans-serif; max-width: 32rem; margin: 4rem auto; padding: 0 1rem; line-height: 1.5">
|
||||
<h1>Sign-in failed</h1>
|
||||
<p>Something went wrong while signing you in. <a href="/auth/login">Try again</a>.</p>
|
||||
<p>If it keeps failing, ask an administrator to look at the audit log.</p>
|
||||
</body></html>`;
|
||||
|
||||
/**
|
||||
* A sign-in that didn't work: the person gets a plain explanation (never the reason — that tells an attacker what to adjust),
|
||||
* and the reason goes to the server log and, unless it's just a stale page, the audit log.
|
||||
*/
|
||||
async function failSignIn(req: Request, res: Response, reason: string, err?: unknown, options: { audit?: boolean } = {}) {
|
||||
const message = err instanceof Error ? err.message : err === undefined ? undefined : String(err);
|
||||
console.error(`[auth] sign-in failed (${reason})${message ? `: ${message}` : ""}`);
|
||||
if (options.audit !== false) {
|
||||
try {
|
||||
await recordAudit({
|
||||
category: "session",
|
||||
action: "login_failed",
|
||||
targetType: "auth",
|
||||
detail: { reason, ...(message ? { error: message.slice(0, 200) } : {}), ip: req.ip },
|
||||
});
|
||||
} catch (auditErr) {
|
||||
console.error("[auth] couldn't record the failed sign-in:", auditErr);
|
||||
}
|
||||
}
|
||||
delete req.session.pendingAuth; // a failed attempt's state and verifier can't be tried again
|
||||
res.status(400).type("html").send(SIGN_IN_FAILED_PAGE);
|
||||
}
|
||||
|
||||
authRouter.get("/login", signInLimiter, async (req, res, next) => {
|
||||
try {
|
||||
const config = await getOidcConfig();
|
||||
let config;
|
||||
try {
|
||||
config = await getOidcConfig();
|
||||
} catch (err) {
|
||||
return await failSignIn(req, res, "provider_unreachable", err);
|
||||
}
|
||||
const codeVerifier = client.randomPKCECodeVerifier();
|
||||
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
|
||||
const state = client.randomState();
|
||||
@@ -37,24 +79,33 @@ authRouter.get("/login", async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
authRouter.get("/callback", async (req, res, next) => {
|
||||
authRouter.get("/callback", signInLimiter, async (req, res, next) => {
|
||||
try {
|
||||
const pending = req.session.pendingAuth;
|
||||
if (!pending) {
|
||||
return res.status(400).send("Login session expired. Please try signing in again.");
|
||||
// A page left open, or the callback address visited by hand: not worth an audit entry.
|
||||
return await failSignIn(req, res, "no_pending_login", undefined, { audit: false });
|
||||
}
|
||||
|
||||
const config = await getOidcConfig();
|
||||
const currentUrl = new URL(req.originalUrl, env.appBaseUrl);
|
||||
|
||||
const tokens = await client.authorizationCodeGrant(config, currentUrl, {
|
||||
pkceCodeVerifier: pending.codeVerifier,
|
||||
expectedState: pending.state,
|
||||
});
|
||||
let config;
|
||||
let tokens;
|
||||
try {
|
||||
config = await getOidcConfig();
|
||||
const currentUrl = new URL(req.originalUrl, env.appBaseUrl);
|
||||
tokens = await client.authorizationCodeGrant(config, currentUrl, {
|
||||
pkceCodeVerifier: pending.codeVerifier,
|
||||
expectedState: pending.state,
|
||||
});
|
||||
if (!tokens.id_token) throw new Error("The identity provider returned no ID token.");
|
||||
// Not just the claims: the signature too, so the login doesn't rest on the connection to the provider alone.
|
||||
await verifyIdTokenSignature(config, tokens.id_token);
|
||||
} catch (err) {
|
||||
return await failSignIn(req, res, "provider_rejected", err);
|
||||
}
|
||||
|
||||
const claims = tokens.claims();
|
||||
if (!claims?.sub) {
|
||||
return res.status(400).send("Identity provider did not return a valid identity.");
|
||||
return await failSignIn(req, res, "no_identity");
|
||||
}
|
||||
|
||||
let email: string | undefined = typeof claims.email === "string" ? claims.email : undefined;
|
||||
@@ -90,8 +141,7 @@ authRouter.get("/callback", async (req, res, next) => {
|
||||
detail: { name: user.name ?? user.email ?? user.oidcSub, ip: req.ip },
|
||||
});
|
||||
|
||||
delete req.session.pendingAuth;
|
||||
req.session.user = {
|
||||
const signedIn = {
|
||||
sub: claims.sub,
|
||||
email,
|
||||
name,
|
||||
@@ -99,9 +149,15 @@ authRouter.get("/callback", async (req, res, next) => {
|
||||
ip: req.ip,
|
||||
userAgent: req.headers["user-agent"],
|
||||
};
|
||||
req.session.save((err) => {
|
||||
if (err) return next(err);
|
||||
res.redirect("/");
|
||||
// A new session id for the signed-in session. Reusing the one the browser arrived with would let anyone who had planted that
|
||||
// id beforehand (from another page on the same domain, say) be signed in as whoever then completes the login.
|
||||
req.session.regenerate((regenerateErr) => {
|
||||
if (regenerateErr) return next(regenerateErr);
|
||||
req.session.user = signedIn;
|
||||
req.session.save((saveErr) => {
|
||||
if (saveErr) return next(saveErr);
|
||||
res.redirect("/");
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
next(err);
|
||||
|
||||
Reference in new issue
Block a user