taper / server /events.js
abr00kx's picture
Round 2 security fixes (part 4)
cce9364 verified
Raw History Blame Contribute Delete
15.6 kB
// Pure event logic, shared by the local and the federation paths: parameter
// checks, Canonical JSON, Ed25519 signatures, the redaction algorithm, event
// IDs, the strict Room version 13 content validators, and the checks on
// events and room state that come from other servers. No I/O, no server state.
import { createHash, createPublicKey, verify as cryptoVerify, sign as cryptoSign } from 'node:crypto';
import { isPlaintextState, isValidUserId, checkAuthRules, stateKeyOf } from './state-res.js';
export const ROOM_VERSION = '13';
export const RETENTION_CEILING_MS = 1_814_400_000; // 21 days, fixed by the spec
export const MAX_EVENT_DEPTH = 1_000_000_000;
// ---------------------------------------------------------------------------
// Errors and parameters
// ---------------------------------------------------------------------------
export class TaperError extends Error {
constructor(errcode, message, extra = {}) {
super(message);
this.errcode = errcode;
this.extra = extra;
}
}
export const fail = (errcode, message, extra) => { throw new TaperError(errcode, message, extra); };
export const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
// Own properties only: an inherited (polluted) property is never a parameter.
const own = (obj, key) => (isPlainObject(obj) && Object.hasOwn(obj, key) ? obj[key] : undefined);
export function requireString(body, key, { optional = false, max = 255 } = {}) {
const v = own(body, key);
if (v === undefined || v === null) {
if (optional) return undefined;
fail('T_MISSING_PARAM', `Missing '${key}'`);
}
if (typeof v !== 'string' || v.length === 0 || v.length > max) fail('T_INVALID_PARAM', `'${key}' must be a non-empty string of at most ${max} characters`);
return v;
}
export function requireObject(body, key) {
const v = own(body, key);
if (v === undefined) fail('T_MISSING_PARAM', `Missing '${key}'`);
if (!isPlainObject(v)) fail('T_INVALID_PARAM', `'${key}' must be an object`);
return v;
}
function onlyKeys(obj, allowed, what) {
for (const k of Object.keys(obj)) if (!allowed.includes(k)) fail('T_INVALID_PARAM', `Field '${k}' is not allowed in ${what}`);
}
// ---------------------------------------------------------------------------
// Canonical JSON and Ed25519 (Signing JSON appendix)
// ---------------------------------------------------------------------------
export function canonicalJson(value) {
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
if (value && typeof value === 'object') {
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
}
return JSON.stringify(value);
}
export const unpadded = (buf) => buf.toString('base64').replace(/=+$/, '');
export const signWith = (privateKey, obj) => unpadded(cryptoSign(null, Buffer.from(canonicalJson(obj)), privateKey));
export function verifyWith(publicKeyB64, obj, sigB64) {
if (typeof publicKeyB64 !== 'string' || typeof sigB64 !== 'string') return false;
try {
const x = publicKeyB64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
return cryptoVerify(null, Buffer.from(canonicalJson(obj)), createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x }, format: 'jwk' }), Buffer.from(sigB64, 'base64'));
} catch {
return false;
}
}
// A signature by `user_id`'s `keyId` over `obj` without `signatures` and `unsigned`.
export function verifySigned(obj, user_id, keyId, publicKeyB64) {
const { signatures, unsigned: _unsigned, ...signed } = isPlainObject(obj) ? obj : {};
return verifyWith(publicKeyB64, signed, own(own(signatures, user_id), keyId));
}
// ---------------------------------------------------------------------------
// Redaction and event IDs (room version 13)
// ---------------------------------------------------------------------------
// Content kept by the redaction algorithm (v11/v12 rules plus `binding`).
const REDACT_KEEP = {
't.room.member': ['membership'],
't.room.create': null, // all keys
't.room.join_rules': ['join_rule'],
't.room.power_levels': ['ban', 'events', 'events_default', 'invite', 'kick', 'redact', 'state_default', 'users', 'users_default'],
't.room.history_visibility': ['history_visibility'],
't.room.server_acl': ['allow', 'deny', 'allow_ip_literals'],
't.room.retention': ['max_lifetime'],
't.room.redaction': ['redacts'],
't.room.encrypted': ['binding'],
};
export function redactContent(type, content) {
const keep = Object.hasOwn(REDACT_KEEP, type) ? REDACT_KEEP[type] : [];
if (keep === null) return { ...content };
const out = {};
for (const k of keep) if (Object.hasOwn(content ?? {}, k)) out[k] = content[k];
return out;
}
// What event IDs hash and server signatures cover. Non-state events keep no
// message content; the create event leaves out room_id (derived from its ID).
export function redactedForm(ev) {
const redacted = {
sender: ev.sender,
type: ev.type,
origin_server_ts: ev.origin_server_ts,
depth: ev.depth,
prev_events: ev.prev_events,
auth_events: Array.isArray(ev.auth_events) ? ev.auth_events : [],
content: ev.state_key === undefined ? redactContent(ev.type, ev.content) : ev.content,
};
if (ev.type !== 't.room.create') redacted.room_id = ev.room_id;
if (ev.state_key !== undefined) redacted.state_key = ev.state_key;
return redacted;
}
export const computeEventId = (ev) => '$' + createHash('sha256').update(canonicalJson(redactedForm(ev))).digest('base64url');
// ---------------------------------------------------------------------------
// Content validators: every field is listed; anything else is refused.
// ---------------------------------------------------------------------------
const ENCRYPTED_KEYS = ['algorithm', 'ciphertext', 'session_id', 'binding', 't.relates_to', 'attachments', 'sender_key', 'device_id'];
// Room version 13 allows only encrypted messages and bare redactions.
export function validateMessageEvent(type, content) {
if (!isPlainObject(content)) fail('T_INVALID_PARAM', "'content' must be an object");
if (type === 't.room.redaction') {
onlyKeys(content, ['redacts'], 't.room.redaction (no plaintext reason)');
return { redacts: requireString(content, 'redacts') };
}
if (type !== 't.room.encrypted') {
fail('T_FORBIDDEN', `Room version ${ROOM_VERSION} only allows t.room.encrypted and t.room.redaction message events; encrypt '${type}' instead`);
}
onlyKeys(content, ENCRYPTED_KEYS, 't.room.encrypted content');
if (content.algorithm !== 't.megolm.v1.aes-sha2') fail('T_INVALID_PARAM', "'algorithm' must be t.megolm.v1.aes-sha2");
const out = {
algorithm: content.algorithm,
ciphertext: requireString(content, 'ciphertext', { max: 60_000 }),
session_id: requireString(content, 'session_id'),
binding: requireString(content, 'binding', { max: 128 }),
};
// 128 bits = 16 bytes = 22 unpadded base64 characters.
if (!/^[A-Za-z0-9+/_-]{22,}$/.test(out.binding)) fail('T_INVALID_PARAM', "'binding' must be at least 128 bits of unpadded base64");
if (Object.hasOwn(content, 't.relates_to')) {
const rel = requireObject(content, 't.relates_to');
onlyKeys(rel, ['rel_type', 'event_id'], 't.relates_to');
out['t.relates_to'] = { rel_type: requireString(rel, 'rel_type', { max: 128 }), event_id: requireString(rel, 'event_id') };
}
if (Object.hasOwn(content, 'attachments')) {
const a = content.attachments;
if (!Array.isArray(a) || a.length > 16 || a.some((u) => typeof u !== 'string' || u.length > 512)) fail('T_INVALID_PARAM', "'attachments' must be an array of at most 16 content URIs");
out.attachments = [...a];
}
if (Object.hasOwn(content, 'sender_key')) out.sender_key = requireString(content, 'sender_key', { max: 128 });
if (Object.hasOwn(content, 'device_id')) out.device_id = requireString(content, 'device_id', { max: 128 });
return out;
}
// Plaintext state: the fields servers need, nothing else.
const STATE_KEYS = {
't.room.create': ['room_version', 'additional_creators', 't.federate'],
't.room.member': ['membership'],
't.room.join_rules': ['join_rule'],
't.room.power_levels': REDACT_KEEP['t.room.power_levels'],
't.room.history_visibility': ['history_visibility'],
't.room.guest_access': ['guest_access'],
't.room.encryption': ['algorithm', 'rotation_period_ms', 'rotation_period_msgs'],
't.room.server_acl': ['allow', 'deny', 'allow_ip_literals'],
't.room.retention': ['max_lifetime'],
't.room.tombstone': ['replacement_room'],
't.room.third_party_invite': ['display_name', 'key_validity_url', 'public_key', 'public_keys'],
};
const POLICY_KEYS = ['entity', 'recommendation', 'reason'];
const KEYED_STATE = new Set(['t.room.member', 't.room.third_party_invite']); // the rest are singletons
// The room version 13 state rule (auth rule 12) plus structure. `retention`
// is { minMs, maxMs }: the range a room's max_lifetime may take here.
export function validateStateEvent(type, state_key, content, retention) {
if (!isPlainObject(content)) fail('T_INVALID_PARAM', "'content' must be an object");
if (typeof state_key !== 'string' || state_key.length > 255) fail('T_INVALID_PARAM', "'state_key' must be a string of at most 255 characters");
if (type === 't.room.encrypted') {
const sep = state_key.indexOf(':');
if (sep <= 0) fail('T_INVALID_PARAM', "Encrypted state needs a state_key of the form '{type}:{state_key}'");
if (isPlaintextState(state_key.slice(0, sep))) fail('T_FORBIDDEN', `${state_key.slice(0, sep)} must not be encrypted: servers need to read it`);
return validateMessageEvent('t.room.encrypted', content);
}
if (!isPlaintextState(type)) fail('T_FORBIDDEN', `Room version ${ROOM_VERSION} requires '${type}' to be sent as encrypted state`);
const policy = type.startsWith('t.policy.rule.');
if (!policy && !KEYED_STATE.has(type) && state_key !== '') fail('T_INVALID_PARAM', `'${type}' must use an empty state_key`);
onlyKeys(content, policy ? POLICY_KEYS : STATE_KEYS[type], type);
if (type === 't.room.retention') {
const max = content.max_lifetime;
if (max !== undefined && (!Number.isSafeInteger(max) || max < retention.minMs || max > retention.maxMs)) {
fail('T_INVALID_PARAM', `'max_lifetime' must be an integer from ${retention.minMs} to ${retention.maxMs} ms`);
}
return max === undefined ? {} : { max_lifetime: max };
}
if (type === 't.room.server_acl') {
for (const k of ['allow', 'deny']) {
const v = content[k];
if (v !== undefined && (!Array.isArray(v) || v.length > 200 || v.some((x) => typeof x !== 'string' || x.length > 255))) {
fail('T_INVALID_PARAM', `'${k}' must be an array of at most 200 glob strings`);
}
}
if (content.allow_ip_literals !== undefined && typeof content.allow_ip_literals !== 'boolean') fail('T_INVALID_PARAM', "'allow_ip_literals' must be a boolean");
return {
allow: content.allow ?? ['*'],
deny: content.deny ?? [],
...(content.allow_ip_literals !== undefined ? { allow_ip_literals: content.allow_ip_literals } : {}),
};
}
return content;
}
// ---------------------------------------------------------------------------
// Events from other servers
// ---------------------------------------------------------------------------
export const isIdList = (v, max) => Array.isArray(v) && v.length <= max && v.every((x) => typeof x === 'string' && x.length > 0 && x.length <= 255);
// The envelope of a remote event, before its signature is checked.
export function checkEnvelope(ev) {
if (!isPlainObject(ev)) fail('T_BAD_JSON', 'Event must be an object');
if (typeof ev.event_id !== 'string' || ev.event_id.length > 255) fail('T_INVALID_PARAM', 'Event needs an event_id');
if (typeof ev.type !== 'string' || !ev.type || ev.type.length > 255) fail('T_INVALID_PARAM', 'Event needs a type');
if (typeof ev.room_id !== 'string' || ev.room_id.length > 255) fail('T_INVALID_PARAM', 'Event needs a room_id');
if (!isValidUserId(ev.sender)) fail('T_INVALID_PARAM', 'Event sender must be a valid user ID');
if (!isPlainObject(ev.content)) fail('T_INVALID_PARAM', 'Event content must be an object');
if (ev.state_key !== undefined && (typeof ev.state_key !== 'string' || ev.state_key.length > 255)) fail('T_INVALID_PARAM', 'Event state_key must be a string of at most 255 characters');
if (!Number.isSafeInteger(ev.depth) || ev.depth < 0 || ev.depth > MAX_EVENT_DEPTH) fail('T_INVALID_PARAM', 'Event depth must be a valid non-negative integer');
if (!isIdList(ev.prev_events, 20)) fail('T_INVALID_PARAM', 'Event prev_events must be an array of at most 20 event IDs');
if (ev.auth_events !== undefined && !isIdList(ev.auth_events, 20)) fail('T_INVALID_PARAM', 'Event auth_events must be an array of at most 20 event IDs');
if (!Number.isSafeInteger(ev.origin_server_ts)) fail('T_INVALID_PARAM', 'Event timestamp must be an integer');
}
// Rebuild a checked remote event from known fields only: message content is
// re-validated (it is not covered by the event ID), and only the signature
// that verified is kept.
export function sanitizeRemoteEvent(ev, server, keyId) {
const out = {
event_id: ev.event_id,
room_id: ev.room_id,
sender: ev.sender,
type: ev.type,
content: ev.state_key === undefined ? validateMessageEvent(ev.type, ev.content) : ev.content,
origin_server_ts: ev.origin_server_ts,
depth: ev.depth,
prev_events: [...ev.prev_events],
auth_events: [...(ev.auth_events ?? [])],
signatures: { [server]: { [keyId]: ev.signatures[server][keyId] } },
};
if (ev.state_key !== undefined) out.state_key = ev.state_key;
return out;
}
// The state a resident server returned for a join (already signature-checked
// and sanitized: `events` maps ID -> event; `stateIds` is the current state).
// Exactly one create event, matching the room ID; one event per state key;
// every event authorized by its own auth_events, whatever order they came in.
export function checkJoinState(room_id, events, stateIds, retention) {
const creates = [...events.values()].filter((e) => e.type === 't.room.create');
if (creates.length !== 1) fail('T_INVALID_PARAM', 'Join state must hold exactly one t.room.create');
const createEv = creates[0];
if (createEv.content?.room_version !== ROOM_VERSION) fail('T_INCOMPATIBLE_ROOM_VERSION', `Unsupported room version '${createEv.content?.room_version}'`);
if (`!${createEv.event_id.slice(1)}` !== room_id) fail('T_INVALID_PARAM', 'room_id does not match t.room.create hash');
for (const ev of events.values()) {
if (ev.state_key === undefined) fail('T_INVALID_PARAM', 'Non-state event returned in join state');
if (ev.type !== 't.room.create' && ev.room_id !== room_id) fail('T_INVALID_PARAM', 'State event belongs to another room');
validateStateEvent(ev.type, ev.state_key, ev.content, retention);
const auth = new Map();
for (const id of ev.auth_events) {
if (!events.has(id)) fail('T_INVALID_PARAM', 'Join state is missing an auth event');
auth.set(stateKeyOf(events.get(id)), events.get(id));
}
const check = checkAuthRules(ev, auth, createEv, { eventsById: events });
if (!check.ok) fail('T_FORBIDDEN', `Peer returned unauthorized state event: ${check.reason}`);
}
const state = new Map();
for (const id of stateIds) {
const ev = events.get(id);
if (state.has(stateKeyOf(ev))) fail('T_INVALID_PARAM', 'Join state has two events for one state key');
state.set(stateKeyOf(ev), ev);
}
return { createEv, state };
}