From c9976af26b38f56262008bbdc801cbd7155727e0 Mon Sep 17 00:00:00 2001 From: Hornwitser Date: Wed, 2 Apr 2025 23:13:06 +0200 Subject: [PATCH] Include the name of the cookie in the signature If a cookie is signed for one purpose, but the server also uses a differently named signed cookie name for another purpose, then it's possible for a malicious client to substitute the value of one signed cookie with the value of another and have it pass the signature check. Include the name of the cookie when computing the signature so that no cookies signed for example for "user_session" can be used as a value for a hypothetical "admin_session" cookie. --- server/utils/signed-cookie.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/utils/signed-cookie.ts b/server/utils/signed-cookie.ts index 2755916..345befb 100644 --- a/server/utils/signed-cookie.ts +++ b/server/utils/signed-cookie.ts @@ -17,7 +17,7 @@ export async function useCookieSecret(event: H3Event) { export async function setSignedCookie(event: H3Event, name: string, value: string, maxAge?: number) { const secret = await useCookieSecret(event); - const signature = await crypto.subtle.sign("HMAC", secret, Buffer.from(value)); + const signature = await crypto.subtle.sign("HMAC", secret, Buffer.from(`${name}=${value}`)); const cookie = `${value}.${Buffer.from(signature).toString("base64url")}` setCookie(event, name, cookie, { httpOnly: true, secure: true, sameSite: true, maxAge }); } @@ -34,7 +34,7 @@ export async function getSignedCookie(event: H3Event, name: string) { const value = cookie.slice(0, rightDot); const secret = await useCookieSecret(event); const signature = Buffer.from(cookie.slice(rightDot + 1), "base64url"); - const valid = await crypto.subtle.verify("HMAC", secret, signature, Buffer.from(value)); + const valid = await crypto.subtle.verify("HMAC", secret, signature, Buffer.from(`${name}=${value}`)); if (!valid) return