CVE-2023-49095 (published 2023-11-30T07:15Z)

nexkey is a microblogging platform. Insufficient validation of ActivityPub requests received in inbox could allow any user to impersonate another user in certain circumstances. This issue has been patched in version 12.122.2.

CVSS v3 base score: 7.5, HIGH (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N)

Weakness information:
cwe_id: CWE-20
cwe_name: Improper Input Validation
description: The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
extended_description: 
	   Input validation is a frequently-used technique
	   for checking potentially dangerous inputs in order to
	   ensure that the inputs are safe for processing within the
	   code, or when communicating with other components.  When
	   software does not validate input properly, an attacker is
	   able to craft the input in a form that is not expected by
	   the rest of the application. This will lead to parts of the
	   system receiving unintended input, which may result in
	   altered control flow, arbitrary control of a resource, or
	   arbitrary code execution.
	   Input validation is not the only technique for
	   processing input, however.  Other techniques attempt to
	   transform potentially-dangerous input into something safe, such
	   as filtering (CWE-790) - which attempts to remove dangerous
	   inputs - or encoding/escaping (CWE-116), which attempts to
	   ensure that the input is not misinterpreted when it is included
	   in output to another component. Other techniques exist as well
	   (see CWE-138 for more examples.)
	   Input validation can be applied to:
	   
	     raw data - strings, numbers, parameters, file contents, etc.
	     metadata - information about the raw data, such as headers or size
	   
	   Data can be simple or structured.  Structured data
	   can be composed of many nested layers, composed of
	   combinations of metadata and raw data, with other simple or
	   structured data.
	   Many properties of raw data or metadata may need
	   to be validated upon entry into the code, such
	   as:
	   
	     specified quantities such as size, length, frequency, price, rate, number of operations, time, etc.
	     implied or derived quantities, such as the actual size of a file instead of a specified size
	     indexes, offsets, or positions into more complex data structures
	     symbolic keys or other elements into hash tables, associative arrays, etc.
	     well-formedness, i.e. syntactic correctness - compliance with expected syntax 
	     lexical token correctness - compliance with rules for what is treated as a token
	     specified or derived type - the actual type of the input (or what the input appears to be)
	     consistency - between individual data elements, between raw data and metadata, between references, etc.
	     conformance to domain-specific rules, e.g. business logic 
	     equivalence - ensuring that equivalent inputs are treated the same
	     authenticity, ownership, or other attestations about the input, e.g. a cryptographic signature to prove the source of the data
	   
	   Implied or derived properties of data must often
	   be calculated or inferred by the code itself.  Errors in
	   deriving properties may be considered a contributing factor
	   to improper input validation.
	   
	   Note that "input validation" has very different
	   meanings to different people, or within different
	   classification schemes.  Caution must be used when
	   referencing this CWE entry or mapping to it.  For example,
	   some weaknesses might involve inadvertently giving control
	   to an attacker over an input when they should not be able
	   to provide an input at all, but sometimes this is referred
	   to as input validation.
	   Finally, it is important to emphasize that the
	   distinctions between input validation and output escaping
	   are often blurred, and developers must be careful to
	   understand the difference, including how input validation
	   is not always sufficient to prevent vulnerabilities,
	   especially when less stringent data types must be
	   supported, such as free-form text. Consider a SQL injection
	   scenario in which a person's last name is inserted into a
	   query. The name "O'Reilly" would likely pass the validation
	   step since it is a common last name in the English
	   language. However, this valid name cannot be directly
	   inserted into the database because it contains the "'"
	   apostrophe character, which would need to be escaped or
	   otherwise transformed. In this case, removing the
	   apostrophe might reduce the risk of SQL injection, but it
	   would produce incorrect behavior because the wrong name
	   would be recorded.
       
         

Fix information:
repo_url: https://github.com/nexryai/nexkey
commit_details: repo_url: https://github.com/nexryai/nexkey
author: nexryai
author_date: 2023-11-27 15:19:00+09:00
msg: Security Hot fix: GHSA-3f39-6537-3cgc
repository: repo_url: https://github.com/nexryai/nexkey
repo_name: nexryai/nexkey
description: nexryaiによるMisskey v12フォーク
repo_language: TypeScript
owner: nexryai
file_changes: filename: activitypub.ts
change_type: ModificationType.MODIFY
diff: @@ -1,24 +1,31 @@
-import Router from '@koa/router';
-import json from 'koa-json-body';
-import httpSignature from '@peertube/http-signature';
-
-import { renderActivity } from '@/remote/activitypub/renderer/index.js';
-import renderNote from '@/remote/activitypub/renderer/note.js';
-import renderKey from '@/remote/activitypub/renderer/key.js';
-import { renderPerson } from '@/remote/activitypub/renderer/person.js';
-import renderEmoji from '@/remote/activitypub/renderer/emoji.js';
-import Outbox, { packActivity } from './activitypub/outbox.js';
-import Followers from './activitypub/followers.js';
-import Following from './activitypub/following.js';
-import Featured from './activitypub/featured.js';
-import { inbox as processInbox } from '@/queue/index.js';
-import { isSelfHost } from '@/misc/convert-host.js';
-import { Notes, Users, Emojis, NoteReactions } from '@/models/index.js';
-import { ILocalUser, User } from '@/models/entities/user.js';
-import { In, IsNull, Not } from 'typeorm';
-import { renderLike } from '@/remote/activitypub/renderer/like.js';
-import { getUserKeypair } from '@/misc/keypair-store.js';
-import renderFollow from '@/remote/activitypub/renderer/follow.js';
+import Router from "@koa/router";
+import bodyParser from "koa-bodyparser";
+import * as crypto from 'crypto';
+import httpSignature from "@peertube/http-signature";
+
+import { In, IsNull, Not } from "typeorm";
+import config from "@/config/index.js";
+import { apLogger } from '@/remote/activitypub/logger.js';
+import { renderActivity } from "@/remote/activitypub/renderer/index.js";
+import renderNote from "@/remote/activitypub/renderer/note.js";
+import renderKey from "@/remote/activitypub/renderer/key.js";
+import { renderPerson } from "@/remote/activitypub/renderer/person.js";
+import renderEmoji from "@/remote/activitypub/renderer/emoji.js";
+import { inbox as processInbox } from "@/queue/index.js";
+import { isSelfHost } from "@/misc/convert-host.js";
+import { Notes, Users, Emojis, NoteReactions } from "@/models/index.js";
+import { ILocalUser, User } from "@/models/entities/user.js";
+import { renderLike } from "@/remote/activitypub/renderer/like.js";
+import { getUserKeypair } from "@/misc/keypair-store.js";
+import renderFollow from "@/remote/activitypub/renderer/follow.js";
+import Featured from "./activitypub/featured.js";
+import Following from "./activitypub/following.js";
+import Followers from "./activitypub/followers.js";
+import Outbox, { packActivity } from "./activitypub/outbox.js";
+import { IActivity } from "@/remote/activitypub/type.js";
+import Koa from "koa";
+
+const logger = apLogger;
 
 // Init router
 const router = new Router();
@@ -26,27 +33,75 @@ const router = new Router();
 //#region Routing
 
 function inbox(ctx: Router.RouterContext) {
-	let signature;
+	// 署名の検証
+	// referenced: https://github.com/mei23/misskey/pull/4749
+	let signature: httpSignature.IParsedSignature;
 
 	try {
-		signature = httpSignature.parseRequest(ctx.req, { 'headers': [] });
+		// ヘッダーの検証はライブラリに投げる
+		signature = httpSignature.parseRequest(ctx.req, { "headers": ["(request-target)", "digest", "host", "date"] });
 	} catch (e) {
+		logger.warn("inbox: signature parse error");
+		ctx.status = 401;
+		return;
+	}
+
+	// Digestヘッダーの検証
+	const digest = ctx.req.headers.digest;
+	if (typeof digest !== "string") {
+		//logger.warn("Invalid digest (not string)")
+		ctx.status = 401;
+		return;
+	}
+
+	const match = digest.match(/^([0-9A-Za-z-]+)=(.+)$/);
+
+	if (match == null) {
+		logger.warn("Invalid digest (match == null)")
+		ctx.status = 401;
+		return;
+	}
+
+	const digestAlgo = match[1];
+	const digestExpected = match[2];
+
+	if (digestAlgo.toUpperCase() !== "SHA-256") {
+		// アルゴリズムをサポートしていない
+		logger.warn("digestAlgo is not supported")
+		ctx.status = 401;
+		return;
+	}
+
+	const digestActual = crypto.createHash("sha256").update(ctx.request.rawBody).digest("base64")
+
+	if (digestExpected !== digestActual) {
+		// 不正なダイジェスト
+		logger.warn("Invalid digest (digestExpected !== digestActual)")
 		ctx.status = 401;
 		return;
 	}
 
-	processInbox(ctx.request.body, signature);
+
+	if (!signature.params.headers.includes("host") || ctx.headers.host !== config.host) {
+		// Host not specified or not match.
+		logger.warn("Invalid host header")
+		ctx.status = 400;
+		return;
+	}
+
+	const activity = ctx.request.body as IActivity;
+	processInbox(activity, signature);
 
 	ctx.status = 202;
 }
 
-const ACTIVITY_JSON = 'application/activity+json; charset=utf-8';
-const LD_JSON = 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"; charset=utf-8';
+const ACTIVITY_JSON = "application/activity+json; charset=utf-8";
+const LD_JSON = "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"; charset=utf-8";
 
 function isActivityPubReq(ctx: Router.RouterContext) {
-	ctx.response.vary('Accept');
-	const accepted = ctx.accepts('html', ACTIVITY_JSON, LD_JSON);
-	return typeof accepted === 'string' && !accepted.match(/html/);
+	ctx.response.vary("Accept");
+	const accepted = ctx.accepts("html", ACTIVITY_JSON, LD_JSON);
+	return typeof accepted === "string" && !accepted.match(/html/);
 }
 
 export function setResponseType(ctx: Router.RouterContext) {
@@ -58,17 +113,33 @@ export function setResponseType(ctx: Router.RouterContext) {
 	}
 }
 
+async function parseJsonBodyOrFail(ctx: Router.RouterContext, next: Koa.Next) {
+	const koaBodyParser = bodyParser({
+		enableTypes: ["json"],
+		detectJSON: () => true,
+	});
+
+	try {
+		await koaBodyParser(ctx, next);
+	}
+	catch {
+		ctx.status = 400;
+		return;
+	}
+}
+
+
 // inbox
-router.post('/inbox', json(), inbox);
-router.post('/users/:user/inbox', json(), inbox);
+router.post("/inbox", parseJsonBodyOrFail, inbox);
+router.post("/users/:user/inbox", parseJsonBodyOrFail, inbox);
 
 // note
-router.get('/notes/:note', async (ctx, next) => {
+router.get("/notes/:note", async (ctx, next) => {
 	if (!isActivityPubReq(ctx)) return await next();
 
 	const note = await Notes.findOneBy({
 		id: ctx.params.note,
-		visibility: In(['public' as const, 'home' as const]),
+		visibility: In(["public" as const, "home" as const]),
 		localOnly: false,
 	});
 
@@ -88,16 +159,16 @@ router.get('/notes/:note', async (ctx, next) => {
 	}
 
 	ctx.body = renderActivity(await renderNote(note, false));
-	ctx.set('Cache-Control', 'public, max-age=180');
+	ctx.set("Cache-Control", "public, max-age=180");
 	setResponseType(ctx);
 });
 
 // note activity
-router.get('/notes/:note/activity', async ctx => {
+router.get("/notes/:note/activity", async ctx => {
 	const note = await Notes.findOneBy({
 		id: ctx.params.note,
 		userHost: IsNull(),
-		visibility: In(['public' as const, 'home' as const]),
+		visibility: In(["public" as const, "home" as const]),
 		localOnly: false,
 	});
 
@@ -107,24 +178,24 @@ router.get('/notes/:note/activity', async ctx => {
 	}
 
 	ctx.body = renderActivity(await packActivity(note));
-	ctx.set('Cache-Control', 'public, max-age=180');
+	ctx.set("Cache-Control", "public, max-age=180");
 	setResponseType(ctx);
 });
 
 // outbox
-router.get('/users/:user/outbox', Outbox);
+router.get("/users/:user/outbox", Outbox);
 
 // followers
-router.get('/users/:user/followers', Followers);
+router.get("/users/:user/followers", Followers);
 
 // following
-router.get('/users/:user/following', Following);
+router.get("/users/:user/following", Following);
 
 // featured
-router.get('/users/:user/collections/featured', Featured);
+router.get("/users/:user/collections/featured", Featured);
 
 // publickey
-router.get('/users/:user/publickey', async ctx => {
+router.get("/users/:user/publickey", async ctx => {
 	const userId = ctx.params.user;
 
 	const user = await Users.findOneBy({
@@ -141,7 +212,7 @@ router.get('/users/:user/publickey', async ctx => {
 
 	if (Users.isLocalUser(user)) {
 		ctx.body = renderActivity(renderKey(user, keypair));
-		ctx.set('Cache-Control', 'public, max-age=180');
+		ctx.set("Cache-Control", "public, max-age=180");
 		setResponseType(ctx);
 	} else {
 		ctx.status = 400;
@@ -156,11 +227,11 @@ async function userInfo(ctx: Router.RouterContext, user: User | null) {
 	}
 
 	ctx.body = renderActivity(await renderPerson(user as ILocalUser));
-	ctx.set('Cache-Control', 'public, max-age=180');
+	ctx.set("Cache-Control", "public, max-age=180");
 	setResponseType(ctx);
 }
 
-router.get('/users/:user', async (ctx, next) => {
+router.get("/users/:user", async (ctx, next) => {
 	if (!isActivityPubReq(ctx)) return await next();
 
 	const userId = ctx.params.user;
@@ -174,7 +245,7 @@ router.get('/users/:user', async (ctx, next) => {
 	await userInfo(ctx, user);
 });
 
-router.get('/@:user', async (ctx, next) => {
+router.get("/@:user", async (ctx, next) => {
 	if (!isActivityPubReq(ctx)) return await next();
 
 	const user = await Users.findOneBy({
@@ -188,7 +259,7 @@ router.get('/@:user', async (ctx, next) => {
 //#endregion
 
 // emoji
-router.get('/emojis/:emoji', async ctx => {
+router.get("/emojis/:emoji", async ctx => {
 	const emoji = await Emojis.findOneBy({
 		host: IsNull(),
 		name: ctx.params.emoji,
@@ -200,12 +271,12 @@ router.get('/emojis/:emoji', async ctx => {
 	}
 
 	ctx.body = renderActivity(await renderEmoji(emoji));
-	ctx.set('Cache-Control', 'public, max-age=180');
+	ctx.set("Cache-Control", "public, max-age=180");
 	setResponseType(ctx);
 });
 
 // like
-router.get('/likes/:like', async ctx => {
+router.get("/likes/:like", async ctx => {
 	const reaction = await NoteReactions.findOneBy({ id: ctx.params.like });
 
 	if (reaction == null) {
@@ -221,12 +292,12 @@ router.get('/likes/:like', async ctx => {
 	}
 
 	ctx.body = renderActivity(await renderLike(reaction, note));
-	ctx.set('Cache-Control', 'public, max-age=180');
+	ctx.set("Cache-Control", "public, max-age=180");
 	setResponseType(ctx);
 });
 
 // follow
-router.get('/follows/:follower/:followee', async ctx => {
+router.get("/follows/:follower/:followee", async ctx => {
 	// This may be used before the follow is completed, so we do not
 	// check if the following exists.
 
@@ -247,7 +318,7 @@ router.get('/follows/:follower/:followee', async ctx => {
 	}
 
 	ctx.body = renderActivity(renderFollow(follower, followee));
-	ctx.set('Cache-Control', 'public, max-age=180');
+	ctx.set("Cache-Control", "public, max-age=180");
 	setResponseType(ctx);
 });
 

programming_language: TypeScript