Node.js based forum software built for the modern web
fix(activitypub): cross-check signature against verified keyId, not raw header
Julian Lamfc28231828bd
diff --git a/src/activitypub/inbox.js b/src/activitypub/inbox.jsindex ac29b0e878..d6c52a1daf 100644--- a/src/activitypub/inbox.js+++ b/src/activitypub/inbox.js@@ -240,13 +240,20 @@ inbox.update = async (req) => {switch (true) {case isNote: {const cid = await posts.getCidByPid(object.id);- const [allowed, isDeleted] = await Promise.all([+ const [allowed, isDeleted, postUid] = await Promise.all([privileges.categories.can('posts:edit', cid, activitypub._constants.uid),posts.getPostField(object.id, 'deleted'),+ posts.getPostField(object.id, 'uid'),]);if (!allowed) {throw new Error('[[error:no-privileges]]');}+ // Only the post's author (the verified signer) may edit it. The+ // fediverse group's blanket posts:edit must not let one remote+ // actor edit another's federated post.+ if (postUid !== actor) {+ throw new Error('[[error:no-privileges]]');+ }if (isDeleted) { // fediverse users can't edit deleted postsawait api.posts.restore({ uid: actor }, { pid: object.id });}@@ -380,6 +387,10 @@ inbox.delete = async (req) => {}const uid = await posts.getPostField(id, 'uid');+ // Only the post's author (the verified signer) may delete it.+ if (uid !== actor) {+ throw new Error('[[error:no-privileges]]');+ }await activitypub.feps.announce(id, req.body);try {await api.posts[method]({ uid }, { pid: id });@@ -400,6 +411,10 @@ inbox.delete = async (req) => {return;}const { tid, uid } = await posts.getPostFields(pid, ['tid', 'uid']);+ // Only the topic's author (the verified signer) may delete it.+ if (uid !== actor) {+ throw new Error('[[error:no-privileges]]');+ }activitypub.helpers.log(`[activitypub/inbox.delete] Deleting tid ${tid}.`);await api.topics[method]({ uid }, { tids: [tid] });break;@@ -658,6 +673,14 @@ inbox.announce = async (req) => {throw new Error('[[error:no-privileges]]');}+ // Self-deletion requires the delete's actor to be the post's author; a+ // group (moderator) announcer may delete on behalf of moderators.+ const isGroupAnnouncer = await db.exists(`categoryRemote:${actor}`);+ const postUid = await posts.getPostField(id, 'uid');+ if (!isGroupAnnouncer && postUid !== object.actor) {+ throw new Error('[[error:no-privileges]]');+ }+const uid = await posts.getPostField(id, 'uid');const isMain = await posts.isMain(id);const postCount = await topics.getTopicField(await posts.getPostField(id, 'tid'), 'postcount');diff --git a/src/activitypub/index.js b/src/activitypub/index.jsindex e9611ee58c..0f5691bc34 100644--- a/src/activitypub/index.js+++ b/src/activitypub/index.js@@ -312,14 +312,14 @@ ActivityPub.sign = async ({ key, keyId }, url, digest) => {ActivityPub.verify = async (req) => {ActivityPub.helpers.log('[activitypub/verify] Starting signature verification...');- const isValid = await ActivityPub.signatures.verify(req, ActivityPub.fetchPublicKey);- if (!isValid) {+ const verified = await ActivityPub.signatures.verify(req, ActivityPub.fetchPublicKey);+ if (!verified) {ActivityPub.helpers.log('[activitypub/verify] Signature verification failed.');} else {ActivityPub.helpers.log('[activitypub/verify] Signature verification succeeded.');}- return isValid;+ return verified;};async function _checkFederationPolicy(hostname, url) {diff --git a/src/activitypub/signatures.js b/src/activitypub/signatures.jsindex 70acc7a065..1effcccf14 100644--- a/src/activitypub/signatures.js+++ b/src/activitypub/signatures.js@@ -255,12 +255,12 @@ Signatures.verify = async (req, fetchPublicKeyFn) => {const rfcVerified = await tryVerifyRFC9421(req, fetchPublicKeyFn);if (rfcVerified) {- return true;+ return rfcVerified;}const draftVerified = await tryVerifyDraft(req, fetchPublicKeyFn);if (draftVerified) {- return true;+ return draftVerified;}return false;@@ -369,7 +369,7 @@ async function tryVerifyDraft(req, fetchPublicKeyFn) {msg => winston.warn(`[activitypub/signatures] verifyDraftSignature error: ${msg}`));- return !!result;+ return result ? parsed.value.keyId : false;} catch (err) {winston.debug(`[activitypub/signatures] Draft verification failed: ${err.message}`);return false;@@ -449,7 +449,7 @@ async function tryVerifyRFC9421(req, fetchPublicKeyFn) {publicKeyPem,});if (verified) {- return true;+ return keyid;}}diff --git a/src/middleware/activitypub.js b/src/middleware/activitypub.jsindex 43da64ca05..b89b8b53c9 100644--- a/src/middleware/activitypub.js+++ b/src/middleware/activitypub.js@@ -48,6 +48,9 @@ middleware.verify = async function (req, res, next) {// Verifies the HTTP Signature if present (required for POST, optional for GET)if (req.headers.hasOwnProperty('signature')) {+ // `verified` is the keyId that passed cryptographic verification (or false).+ // Caller identity MUST be derived from this value — never re-parse the raw+ // Signature header, which can be crafted to disagree with the spec parser.const verified = await activitypub.verify(req);if (!verified) {activitypub.helpers.log('[middleware/activitypub] HTTP signature verification failed.');@@ -59,11 +62,9 @@ middleware.verify = async function (req, res, next) {return next();}- // Set calling user (keyId may be a draft `keyId` or RFC 9421 `keyid` parameter)- const keyId = activitypub.signatures.getKeyId(req.headers);- if (keyId) {- req.uid = keyId.replace(/#.*$/, '');- }+ // Set calling user from the verified keyId (draft `keyId` or RFC 9421 `keyid`)+ req.apKeyId = verified;+ req.uid = verified.replace(/#.*$/, '');activitypub.helpers.log('[middleware/activitypub] HTTP signature verification passed.');} else if (req.method === 'POST') {@@ -136,14 +137,22 @@ middleware.assertPayload = helpers.try(async function (req, res, next) {activitypub.helpers.log('[middleware/activitypub] Origin check passed.');}- // Cross-check key ownership against received actor+ // Cross-check key ownership against received actor.+ // The keyId is the one that passed cryptographic verification (set on+ // req.apKeyId by the verify middleware) — NOT a re-parse of the raw header.+ if (!req.apKeyId) {+ // A signed POST reaching this point without a verified keyId is anomalous.+ activitypub.helpers.log('[middleware/activitypub] No verified keyId available for cross-check.');+ return res.sendStatus(403);+ }+await activitypub.actors.assert(actor);let compare = await db.getObjectsFields([`userRemote:${actor}:keys`, `categoryRemote:${actor}:keys`,], ['id']);compare = compare.reduce((keyId, { id }) => keyId || id || '', '').replace(/#[\w-]+$/, '');- const keyId = (activitypub.signatures.getKeyId(req.headers) || '').replace(/#[\w-]+$/, '');+ const keyId = req.apKeyId.replace(/#[\w-]+$/, '');if (compare !== keyId) {activitypub.helpers.log('[middleware/activitypub] Key ownership cross-check failed.');return res.sendStatus(403);diff --git a/test/activitypub/inbox.js b/test/activitypub/inbox.jsindex 8d3632dc20..9935325f32 100644--- a/test/activitypub/inbox.js+++ b/test/activitypub/inbox.js@@ -603,7 +603,8 @@ describe('Inbox', () => {});await activitypub.notes.assert(0, id, { skipChecks: true });note.content = utils.generateUUID();- const { activity: update } = helpers.mocks.update({ object: note });+ // The Update's actor must be the note's author (the verified signer).+ const { activity: update } = helpers.mocks.update({ object: note, actor });const { activity } = helpers.mocks.announce({actor: groupActor,object: update,@@ -614,6 +615,30 @@ describe('Inbox', () => {const content = await posts.getPostField(id, 'content');assert.strictEqual(content, note.content);});++ it('should NOT allow a non-author to update a note', async () => {+ const { id: author } = helpers.mocks.person();+ const { id: groupActor } = helpers.mocks.group();+ await activitypub.actors.assertGroup(author);+ const { id, note } = helpers.mocks.note({+ attributedTo: author,+ audience: groupActor,+ });+ await activitypub.notes.assert(0, id, { skipChecks: true });+ const originalContent = await posts.getPostField(id, 'content');+ note.content = utils.generateUUID();+ // A different (non-author) actor attempts the update.+ const { id: attacker } = helpers.mocks.person();+ const { activity: update } = helpers.mocks.update({ object: note, actor: attacker });+ const { activity } = helpers.mocks.announce({+ actor: groupActor,+ object: update,+ });+ await assert.rejects(activitypub.inbox.announce({ body: activity }), /no-privileges/);+ // Content must be unchanged+ const content = await posts.getPostField(id, 'content');+ assert.strictEqual(content, originalContent);+ });});describe('(Delete)', () => {@@ -650,6 +675,29 @@ describe('Inbox', () => {assert.strictEqual(isDeleted, 1);});+ it('should NOT allow a non-author to delete a post', async () => {+ const { id: author } = helpers.mocks.person();+ const { id: cid } = helpers.mocks.group();+ await activitypub.actors.assertGroup(cid);+ const { id } = helpers.mocks.note({+ attributedTo: author,+ audience: [cid],+ });+ await activitypub.notes.assert(0, id, { skipChecks: true });+ const postUid = await posts.getPostField(id, 'uid');+ assert.strictEqual(postUid, author);+ // A different (non-author) actor attempts the delete.+ const { id: attacker } = helpers.mocks.person();+ const { activity: deleteActivity } = helpers.mocks.delete({ actor: attacker, object: id });+ await assert.rejects(+ activitypub.inbox.delete({ body: deleteActivity }),+ /no-privileges/+ );+ // Post must NOT be deleted+ const isDeleted = await posts.getPostField(id, 'deleted');+ assert.notStrictEqual(isDeleted, 1);+ });+it('should delete the topic if the post is the only post in the topic', async () => {const { id: cid } = helpers.mocks.group();await activitypub.actors.assertGroup(cid);diff --git a/test/activitypub/middleware.js b/test/activitypub/middleware.jsindex 57ee510249..711efdf182 100644--- a/test/activitypub/middleware.js+++ b/test/activitypub/middleware.js@@ -278,19 +278,16 @@ describe('middleware.assertPayload', () => {return { nextCalled, res };}- it('should extract keyId from signature header with leading whitespace', async () => {- // Regression test: assertPayload's Map-based keyId parsing must trim- // whitespace from parameter names to match the library's behavior.- const signedHeaders = await activitypub.sign(keyData, `${nconf.get('url')}${path}`, null);-- // Reorder so algorithm precedes keyId, introducing whitespace before keyId.- const parts = signedHeaders.signature.split(',');- const algorithmPart = parts.find(p => p.startsWith('algorithm='));- const signaturePart = parts.find(p => p.startsWith('signature='));- const headersPart = parts.find(p => p.startsWith('headers='));- const reordered = `${algorithmPart}, keyId="${nconf.get('url')}/uid/${uid}#key", ${headersPart}, ${signaturePart}`;-- const req = buildReqWithSignature('POST', path, { signature: reordered, date: signedHeaders.date });+ it('should reject when the verified keyId does not match the actor\'s stored key', async () => {+ // The cross-check compares the cryptographically-verified keyId (set on+ // req.apKeyId by the verify middleware) against the claimed actor's stored+ // remote key. A local uid has no remote AP keys, so the check must fail.+ await activitypub.sign(keyData, `${nconf.get('url')}${path}`, null);++ const req = buildReqWithSignature('POST', path, {});+ // Simulate the verify middleware having verified the signature and recorded+ // the keyId that actually passed cryptographic verification.+ req.apKeyId = `${nconf.get('url')}/uid/${uid}#key`;const body = {id: `https://example.org/activity/${utils.generateUUID()}`,type: 'Create',@@ -300,11 +297,47 @@ describe('middleware.assertPayload', () => {const res = buildRes();const { nextCalled, res: response } = await runPayloadMiddleware(req, body);- // The actor (local uid) has no stored keys in the remote AP DB, so- // compare is ''. After the fix, keyId is correctly parsed as the- // actual keyId URL. '' !== keyId → cross-check fails → 403.- // Before the fix, both were '' → cross-check passed → next() called.+ // The actor (local uid) has no stored keys in the remote AP DB, so compare+ // is ''. keyId (verified) is the real key URL. '' !== keyId → 403.assert.strictEqual(nextCalled, false);assert.strictEqual(response.statusCode, 403);});++ it('should reject a signed POST that reached assertPayload without a verified keyId', async () => {+ // Defense in depth: a signed POST must have been verified first. If no+ // verified keyId is present, the cross-check cannot be satisfied.+ const req = buildReqWithSignature('POST', path, {});+ const body = {+ id: `https://example.org/activity/${utils.generateUUID()}`,+ type: 'Create',+ actor: `${nconf.get('url')}/uid/${uid}`,+ object: { type: 'Note', id: `${nconf.get('url')}/topic/1` },+ };+ const res = buildRes();+ const { nextCalled, res: response } = await runPayloadMiddleware(req, body);++ assert.strictEqual(nextCalled, false);+ assert.strictEqual(response.statusCode, 403);+ });++ it('should pass the cross-check when the actor\'s stored key matches the verified keyId', async () => {+ const actor = `${nconf.get('url')}/uid/${uid}`;+ const keyId = `${nconf.get('url')}/uid/${uid}#key`;+ // Store the actor's remote AP key so the cross-check can match it.+ await db.setObject(`userRemote:${actor}:keys`, { id: keyId });++ const req = buildReqWithSignature('POST', path, {});+ req.apKeyId = keyId;+ const body = {+ id: `https://example.org/activity/${utils.generateUUID()}`,+ type: 'Create',+ actor,+ object: { type: 'Note', id: `${nconf.get('url')}/topic/1` },+ };+ const res = buildRes();+ const { nextCalled, res: response } = await runPayloadMiddleware(req, body);++ assert.strictEqual(nextCalled, true);+ assert.strictEqual(response.statusCode, null);+ });});diff --git a/test/activitypub/mitra-interop-sim.js b/test/activitypub/mitra-interop-sim.jsindex a6a9411473..821d0bd5df 100644--- a/test/activitypub/mitra-interop-sim.js+++ b/test/activitypub/mitra-interop-sim.js@@ -90,7 +90,7 @@ describe('Mitra-style incoming RFC 9421 request (interop simulation)', () => {};const verified = await signatures.verify(req, fetchPublicKeyFn);- assert.strictEqual(verified, true, 'NodeBB failed to verify a Mitra-style RFC 9421 request');+ assert.strictEqual(verified, 'https://mitra.example/users/alice#main-key', 'NodeBB failed to verify a Mitra-style RFC 9421 request');});it('should verify a Mitra-style request whose created param is 4 minutes old (within clock skew)', async () => {@@ -132,7 +132,7 @@ describe('Mitra-style incoming RFC 9421 request (interop simulation)', () => {};const verified = await signatures.verify(req, async () => pubPem);- assert.strictEqual(verified, true);+ assert.strictEqual(verified, 'https://mitra.example/users/alice#main-key');});it('should verify when the signed @target-uri host differs from the configured URL (host mismatch)', async () => {@@ -183,6 +183,6 @@ describe('Mitra-style incoming RFC 9421 request (interop simulation)', () => {};const verified = await signatures.verify(req, async () => pubPem);- assert.strictEqual(verified, true, 'verification failed despite a valid Host-header-based target URI');+ assert.strictEqual(verified, 'https://mitra.example/users/alice#main-key', 'verification failed despite a valid Host-header-based target URI');});});diff --git a/test/activitypub/signatures.js b/test/activitypub/signatures.jsindex 156a02c7b9..5261395be5 100644--- a/test/activitypub/signatures.js+++ b/test/activitypub/signatures.js@@ -120,7 +120,7 @@ describe('http signature signing and verification', () => {};const verified = await activitypub.verify(req);- assert.strictEqual(verified, true);+ assert.strictEqual(verified, `${nconf.get('url')}/uid/${uid}#key`);});it('should return true when a digest is also passed in', async () => {@@ -145,7 +145,7 @@ describe('http signature signing and verification', () => {};const verified = await activitypub.verify(req);- assert.strictEqual(verified, true);+ assert.strictEqual(verified, `${nconf.get('url')}/uid/${uid}#key`);});it('should return true when a valid RFC 9421 signature is passed in', async () => {@@ -165,7 +165,7 @@ describe('http signature signing and verification', () => {};const verified = await activitypub.verify(req);- assert.strictEqual(verified, true);+ assert.strictEqual(verified, `${nconf.get('url')}/uid/${uid}#key`);});it('should return true when an RFC 9421 signature with content digest is passed in', async () => {@@ -206,7 +206,7 @@ describe('http signature signing and verification', () => {};const verified = await activitypub.verify(req);- assert.strictEqual(verified, true);+ assert.strictEqual(verified, `${nconf.get('url')}/uid/${uid}#key`);});it('should return false when an RFC 9421 signature does not verify', async () => {@@ -362,7 +362,60 @@ describe('http signature signing and verification', () => {};const verified = await activitypub.signatures.verify(req, async () => pubPem);- assert.strictEqual(verified, true);+ assert.strictEqual(verified, 'https://example.org/ec-actor#key');+ });+ });++ describe('keyId parser mismatch (regression)', () => {+ it('should return the verified keyId, not a value a naive re-parse extracts from a crafted header', async () => {+ const { generateKeyPairSync } = require('crypto');+ const {+ genDraftSigningString, genDraftSignature, importPrivateKey,+ } = require('@misskey-dev/node-http-message-signatures');++ const attacker = generateKeyPairSync('ec', { namedCurve: 'P-256' });+ const attackerPrivPem = attacker.privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();+ const attackerPubPem = attacker.publicKey.export({ format: 'pem', type: 'spki' }).toString();+ const attackerKeyId = 'https://attacker.example/actor#main-key';+ const victimKeyId = 'https://victim.example/actor#main-key';++ const endpoint = `${nconf.get('url')}/uid/1/inbox`;+ const url = new URL(endpoint);+ const date = new Date().toUTCString();+ const reqHeaders = { date, host: nconf.get('url_parsed').host };+ const includeHeaders = ['(request-target)', 'host', 'date'];+ const ALGO = 'ecdsa-p256-sha256';++ // The attacker signs with THEIR key; the signing string uses the attacker keyId.+ const signingString = genDraftSigningString(+ { method: 'GET', url: url.href, headers: reqHeaders },+ includeHeaders,+ { keyId: attackerKeyId, algorithm: ALGO }+ );+ const privateKey = await importPrivateKey(attackerPrivPem, ['sign']);+ const SIG = await genDraftSignature(privateKey, signingString);++ // A crafted header whose quoted `foo` value contains a comma: a naive+ // split(',')-based parser reports the VICTIM keyId (the comma-split tail+ // that looks like a standalone keyId="..." param), while the spec-aware+ // parser used for verification reports the ATTACKER keyId.+ const header = `keyId="${attackerKeyId}",algorithm="${ALGO}",headers="${includeHeaders.join(' ')}",signature="${SIG}",foo="x,keyId="${victimKeyId}"`;++ // Precondition: the two parsers actually disagree on this header.+ assert.strictEqual(activitypub.signatures.getKeyId({ signature: header }), victimKeyId);++ // The verified keyId MUST be the attacker's (the key that actually signed),+ // so downstream identity (req.uid) cannot be spoofed to the victim.+ const verified = await activitypub.signatures.verify(+ {+ method: 'GET',+ url: '/uid/1/inbox',+ path: '/uid/1/inbox',+ headers: { ...reqHeaders, signature: header },+ },+ async (keyId) => (keyId === attackerKeyId ? attackerPubPem : null)+ );+ assert.strictEqual(verified, attackerKeyId);});});});