security: stop leaking the admin password length through timing (#395)
verifyAdminPassword compared the raw strings, so timingSafeEqual could
only run once the lengths already matched. The early return on a length
mismatch is observable: an attacker who can time login attempts learns
how long ADMIN_PASSWORD is, which is exactly the information that makes
a brute-force search tractable. The dummy comparison that guarded the
mismatch path did not help — it ran on Buffer.alloc(attempt.length),
which is attacker-sized and leaves the branch timing intact anyway.
HMAC both sides to a fixed 32 bytes first, then compare. Every attempt
now takes the same path regardless of length. Keyed with AUTH_SECRET
rather than a bare SHA-256 so the intermediate values are useless
without the secret, matching how lib/auth.ts already compares subpage
passwords.
MAX_PASSWORD_LENGTH caps an attempt at 1024 characters, rejected in the
route before the body reaches the hashing path and again in the library
so no caller can bypass it. 1024 is far above any real passphrase — a
cap a user could actually hit would be a lockout, not a fix.
Supersedes #390 and #388, which fixed the same comparison with an
unkeyed digest. The .jules/sentinel.md note the original branch carried
is left out: .jules/ is gitignored since cf2e8e6.
Adds 3 tests: a wrong password of exactly the right length, an
oversized attempt, and that a long configured password still logs in.
Verified: 210 unit tests passing (207 before), vitest exit 0, tsc 0
errors, production build exit 0, prettier clean.
Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -6,6 +6,7 @@ import {
|
|||||||
isAdminEnabled,
|
isAdminEnabled,
|
||||||
COOKIE_NAME,
|
COOKIE_NAME,
|
||||||
SESSION_DURATION_MS,
|
SESSION_DURATION_MS,
|
||||||
|
MAX_PASSWORD_LENGTH,
|
||||||
} from '@/lib/admin/auth';
|
} from '@/lib/admin/auth';
|
||||||
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
|
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
|
||||||
|
|
||||||
@@ -37,6 +38,11 @@ export async function POST(request: NextRequest) {
|
|||||||
if (!body?.password || typeof body.password !== 'string') {
|
if (!body?.password || typeof body.password !== 'string') {
|
||||||
return NextResponse.json({ error: 'Password is required' }, { status: 400 });
|
return NextResponse.json({ error: 'Password is required' }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
// Reject before hashing rather than after: nothing downstream should have to
|
||||||
|
// carry an unbounded request body.
|
||||||
|
if (body.password.length > MAX_PASSWORD_LENGTH) {
|
||||||
|
return NextResponse.json({ error: 'Password is too long' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
if (!verifyAdminPassword(body.password)) {
|
if (!verifyAdminPassword(body.password)) {
|
||||||
return NextResponse.json({ error: 'Invalid password' }, { status: 401 });
|
return NextResponse.json({ error: 'Invalid password' }, { status: 401 });
|
||||||
|
|||||||
@@ -134,4 +134,28 @@ describe('verifyAdminPassword', () => {
|
|||||||
expect(verifyAdminPassword('')).toBe(false);
|
expect(verifyAdminPassword('')).toBe(false);
|
||||||
expect(verifyAdminPassword('anything')).toBe(false);
|
expect(verifyAdminPassword('anything')).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The comparison used to run on the raw strings, so a length mismatch
|
||||||
|
// returned before timingSafeEqual could. That early exit is what leaked the
|
||||||
|
// length of ADMIN_PASSWORD; a wrong password of the *right* length has to be
|
||||||
|
// rejected by the same code path as any other.
|
||||||
|
it('rejects a wrong password of exactly the right length', async () => {
|
||||||
|
const { verifyAdminPassword } = await loadAuth();
|
||||||
|
const sameLength = 'x'.repeat(ADMIN_PASSWORD.length);
|
||||||
|
expect(sameLength).toHaveLength(ADMIN_PASSWORD.length);
|
||||||
|
expect(sameLength).not.toBe(ADMIN_PASSWORD);
|
||||||
|
expect(verifyAdminPassword(sameLength)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an oversized attempt without hashing it', async () => {
|
||||||
|
const { verifyAdminPassword, MAX_PASSWORD_LENGTH } = await loadAuth();
|
||||||
|
expect(verifyAdminPassword('x'.repeat(MAX_PASSWORD_LENGTH + 1))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
// A cap that a real passphrase could hit would be a lockout, not a fix.
|
||||||
|
it('still accepts the configured password when it is long', async () => {
|
||||||
|
const { verifyAdminPassword, MAX_PASSWORD_LENGTH } = await loadAuth();
|
||||||
|
expect(ADMIN_PASSWORD.length).toBeLessThanOrEqual(MAX_PASSWORD_LENGTH);
|
||||||
|
expect(verifyAdminPassword(ADMIN_PASSWORD)).toBe(true);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,6 +11,15 @@ import { cookies } from 'next/headers';
|
|||||||
const COOKIE_NAME = 'folio_admin_session';
|
const COOKIE_NAME = 'folio_admin_session';
|
||||||
const SESSION_DURATION_MS = 24 * 60 * 60 * 1000; // 24 hours
|
const SESSION_DURATION_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Longest password attempt the login endpoint will look at.
|
||||||
|
*
|
||||||
|
* Generous enough that no real passphrase hits it — the point is only to keep
|
||||||
|
* an unbounded request body out of the hashing path, not to constrain what
|
||||||
|
* users may choose.
|
||||||
|
*/
|
||||||
|
export const MAX_PASSWORD_LENGTH = 1024;
|
||||||
|
|
||||||
function getSigningKey(): Buffer {
|
function getSigningKey(): Buffer {
|
||||||
// Bind the key to ADMIN_PASSWORD as well, so rotating the password
|
// Bind the key to ADMIN_PASSWORD as well, so rotating the password
|
||||||
// immediately invalidates every outstanding session token.
|
// immediately invalidates every outstanding session token.
|
||||||
@@ -62,20 +71,28 @@ export function verifyAdminToken(token: string): boolean {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Verify admin password. */
|
/**
|
||||||
|
* Verify admin password.
|
||||||
|
*
|
||||||
|
* Both sides are HMAC'd to a fixed 32 bytes before the constant-time compare.
|
||||||
|
* Comparing the raw strings meant `timingSafeEqual` could only run when the
|
||||||
|
* lengths already matched, so the early return on a length mismatch leaked how
|
||||||
|
* long ADMIN_PASSWORD is. Hashing first makes every attempt take the same path.
|
||||||
|
*
|
||||||
|
* Keyed with AUTH_SECRET rather than a bare digest, matching how `lib/auth.ts`
|
||||||
|
* compares subpage passwords: the intermediate values are then useless to
|
||||||
|
* anyone who cannot also read the secret.
|
||||||
|
*/
|
||||||
export function verifyAdminPassword(password: string): boolean {
|
export function verifyAdminPassword(password: string): boolean {
|
||||||
const adminPw = env.ADMIN_PASSWORD;
|
const adminPw = env.ADMIN_PASSWORD;
|
||||||
if (!adminPw) return false;
|
if (!adminPw) return false;
|
||||||
|
if (password.length > MAX_PASSWORD_LENGTH) return false;
|
||||||
|
|
||||||
// Constant-time comparison
|
const secret = resolveAuthSecret();
|
||||||
const pwBuf = Buffer.from(password);
|
const attemptHash = crypto.createHmac('sha256', secret).update(password).digest();
|
||||||
const expectedBuf = Buffer.from(adminPw);
|
const expectedHash = crypto.createHmac('sha256', secret).update(adminPw).digest();
|
||||||
if (pwBuf.length !== expectedBuf.length) {
|
|
||||||
// Still do a comparison to prevent timing attacks on length
|
return crypto.timingSafeEqual(attemptHash, expectedHash);
|
||||||
crypto.timingSafeEqual(pwBuf, Buffer.alloc(pwBuf.length));
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return crypto.timingSafeEqual(pwBuf, expectedBuf);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Check if the current request has a valid admin session. */
|
/** Check if the current request has a valid admin session. */
|
||||||
|
|||||||
Reference in New Issue
Block a user