Skip to content

Feature(MatrixRTC): E2E ratchet key on new joiners #4816

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: valere/rtc/simple_encryption_manager
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion spec/unit/matrixrtc/RTCEncrytionManager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ describe("RTCEncryptionManager", () => {
let mockTransport: Mocked<ToDeviceKeyTransport>;
let statistics: Statistics;
let onEncryptionKeysChanged: jest.Mock;
let ratchetKey: jest.Mock;

beforeEach(() => {
statistics = {
Expand All @@ -46,6 +47,7 @@ describe("RTCEncryptionManager", () => {
};
getMembershipMock = jest.fn().mockReturnValue([]);
onEncryptionKeysChanged = jest.fn();
ratchetKey = jest.fn();
mockTransport = {
start: jest.fn(),
stop: jest.fn(),
Expand All @@ -61,6 +63,7 @@ describe("RTCEncryptionManager", () => {
mockTransport,
statistics,
onEncryptionKeysChanged,
ratchetKey,
);
});

Expand Down Expand Up @@ -115,7 +118,8 @@ describe("RTCEncryptionManager", () => {
);
});

it("Should re-distribute keys to members whom callMemberhsip ts has changed", async () => {
// TODO make this work with ratcheting
it.skip("Should re-distribute keys to members whom callMemberhsip ts has changed", async () => {
let members = [aCallMembership("@bob:example.org", "BOBDEVICE", 1000)];
getMembershipMock.mockReturnValue(members);

Expand Down Expand Up @@ -320,6 +324,7 @@ describe("RTCEncryptionManager", () => {
mockTransport,
statistics,
onEncryptionKeysChanged,
jest.fn(),
);
});

Expand Down Expand Up @@ -547,6 +552,7 @@ describe("RTCEncryptionManager", () => {
transport,
statistics,
onEncryptionKeysChanged,
jest.fn(),
);

const members = [
Expand Down
11 changes: 11 additions & 0 deletions src/matrixrtc/EncryptionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ export interface IEncryptionManager {
* objects containing encryption keys and their associated timestamps.
*/
getEncryptionKeys(): Map<string, Array<{ key: Uint8Array; timestamp: number }>>;

/**
* The ratcheting is done on the decoding layer, the encryption manager asks for a key to be ratcheted, then
* the lower layer will emit the ratcheted key to the encryption manager.
* This is called after the key a ratchet request has been performed.
*/
onOwnKeyRatcheted(key: ArrayBuffer, keyIndex: number | undefined): void;
}

/**
Expand Down Expand Up @@ -100,6 +107,10 @@ export class EncryptionManager implements IEncryptionManager {
this.logger = (parentLogger ?? rootLogger).getChild(`[EncryptionManager]`);
}

public onOwnKeyRatcheted(key: ArrayBuffer, keyIndex: number | undefined): void {
this.logger.warn("Ratcheting key is not implemented in EncryptionManager");
}

public getEncryptionKeys(): Map<string, Array<{ key: Uint8Array; timestamp: number }>> {
return this.encryptionKeys;
}
Expand Down
17 changes: 16 additions & 1 deletion src/matrixrtc/MatrixRTCSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { MembershipManager } from "./NewMembershipManager.ts";
import { EncryptionManager, type IEncryptionManager } from "./EncryptionManager.ts";
import { LegacyMembershipManager } from "./LegacyMembershipManager.ts";
import { logDurationSync } from "../utils.ts";
import { type Statistics } from "./types.ts";
import { type ParticipantId, type Statistics } from "./types.ts";
import { RoomKeyTransport } from "./RoomKeyTransport.ts";
import type { IMembershipManager } from "./IMembershipManager.ts";
import { RTCEncryptionManager } from "./RTCEncryptionManager.ts";
Expand All @@ -49,6 +49,9 @@ export enum MatrixRTCSessionEvent {
JoinStateChanged = "join_state_changed",
// The key used to encrypt media has changed
EncryptionKeyChanged = "encryption_key_changed",
// Request ratcheting the current encryption key. When done `onOwnKeyRatcheted` will be called with the
// ratcheted material.
EncryptionKeyQueryRatchetStep = "encryption_key_ratchet_step",
/** The membership manager had to shut down caused by an unrecoverable error */
MembershipManagerError = "membership_manager_error",
}
Expand All @@ -65,6 +68,7 @@ export type MatrixRTCSessionEventHandlerMap = {
participantId: string,
) => void;
[MatrixRTCSessionEvent.MembershipManagerError]: (error: unknown) => void;
[MatrixRTCSessionEvent.EncryptionKeyQueryRatchetStep]: (participantId: string, keyIndex: number) => void;
};

export interface MembershipConfig {
Expand Down Expand Up @@ -424,6 +428,13 @@ export class MatrixRTCSession extends TypedEventEmitter<
participantId,
);
},
(participantId: ParticipantId, encryptionKeyIndex: number) => {
this.emit(
MatrixRTCSessionEvent.EncryptionKeyQueryRatchetStep,
participantId,
encryptionKeyIndex,
);
},
this.logger,
);
} else {
Expand Down Expand Up @@ -522,6 +533,10 @@ export class MatrixRTCSession extends TypedEventEmitter<
});
}

public onOwnKeyRatcheted(material: ArrayBuffer, keyIndex?: number): void {
this.encryptionManager?.onOwnKeyRatcheted(material, keyIndex);
}

/**
* A map of keys used to encrypt and decrypt (we are using a symmetric
* cipher) given participant's media. This also includes our own key
Expand Down
73 changes: 58 additions & 15 deletions src/matrixrtc/RTCEncryptionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { type CallMembership } from "./CallMembership.ts";
import { decodeBase64, encodeBase64 } from "../base64.ts";
import { type IKeyTransport, type KeyTransportEventListener, KeyTransportEvents } from "./IKeyTransport.ts";
import { logger as rootLogger, type Logger } from "../logger.ts";
import { sleep } from "../utils.ts";
import { defer, type IDeferred, sleep } from "../utils.ts";
import type { InboundEncryptionSession, ParticipantDeviceInfo, ParticipantId, Statistics } from "./types.ts";
import { getParticipantId, KeyBuffer } from "./utils.ts";
import {
Expand Down Expand Up @@ -75,6 +75,8 @@ export class RTCEncryptionManager implements IEncryptionManager {

private logger: Logger;

private currentRatchetRequest: IDeferred<{ key: ArrayBuffer; keyIndex: number }> | null = null;

public constructor(
private userId: string,
private deviceId: string,
Expand All @@ -86,9 +88,10 @@ export class RTCEncryptionManager implements IEncryptionManager {
encryptionKeyIndex: number,
participantId: ParticipantId,
) => void,
private ratchetKey: (participantId: ParticipantId, encryptionKeyIndex: number) => void,
parentLogger?: Logger,
) {
this.logger = (parentLogger ?? rootLogger).getChild(`[EncryptionManager]`);
this.logger = (parentLogger ?? rootLogger).getChild(`[RTCEncryptionManager]`);
}

public getEncryptionKeys(): Map<string, Array<{ key: Uint8Array; timestamp: number }>> {
Expand Down Expand Up @@ -163,7 +166,9 @@ export class RTCEncryptionManager implements IEncryptionManager {
}

public onNewKeyReceived: KeyTransportEventListener = (userId, deviceId, keyBase64Encoded, index, timestamp) => {
this.logger.debug(`Received key over transport ${userId}:${deviceId} at index ${index}`);
this.logger.debug(
`Received key over transport ${userId}:${deviceId} at index ${index} key: ${keyBase64Encoded}`,
);

// We received a new key, notify the video layer of this new key so that it can decrypt the frames properly.
const participantId = getParticipantId(userId, deviceId);
Expand Down Expand Up @@ -216,7 +221,13 @@ export class RTCEncryptionManager implements IEncryptionManager {
// get current memberships
const toShareWith: ParticipantDeviceInfo[] = this.getMemberships()
.filter((membership) => {
return membership.sender != undefined;
return (
membership.sender != undefined &&
!(
// filter me out
(membership.sender == this.userId && membership.deviceId == this.deviceId)
)
);
})
.map((membership) => {
return {
Expand Down Expand Up @@ -272,23 +283,49 @@ export class RTCEncryptionManager implements IEncryptionManager {
toDistributeTo = toShareWith;
outboundKey = newOutboundKey;
} else if (anyJoined.length > 0) {
// keep the same key
// XXX In the future we want to distribute a ratcheted key not the current one
if (this.outboundSession!.sharedWith.length > 0) {
// This key was already shared with someone, we need to ratchet it
// We want to ratchet the current key and only distribute the ratcheted key to the new joiners
// This needs to send some async messages, so we need to wait for the ratchet to finish
const deferredKey = defer<{ key: ArrayBuffer; keyIndex: number }>();
this.currentRatchetRequest = deferredKey;
this.logger.info(`Query ratcheting key index:${this.outboundSession!.keyId} ...`);
this.ratchetKey(getParticipantId(this.userId, this.deviceId), this.outboundSession!.keyId);
const res = await Promise.race([deferredKey.promise, sleep(1000)]);
if (res === undefined) {
// TODO: we might want to rotate the key instead?
this.logger.error("Ratchet key timed out sharing the same key for now :/");
} else {
const { key, keyIndex } = await deferredKey.promise;
this.logger.info(
`... Ratcheting done key index:${keyIndex} key:${encodeBase64(new Uint8Array(key))}`,
);
this.outboundSession!.key = new Uint8Array(key);
this.onEncryptionKeysChanged(
this.outboundSession!.key,
this.outboundSession!.keyId,
getParticipantId(this.userId, this.deviceId),
);
}
}
toDistributeTo = anyJoined;
outboundKey = this.outboundSession!;
} else {
// no changes
return;
// No one joined or left, it could just be the first key, keep going
toDistributeTo = [];
outboundKey = this.outboundSession!;
}

try {
this.logger.trace(`Sending key...`);
await this.transport.sendKey(encodeBase64(outboundKey.key), outboundKey.keyId, toDistributeTo);
this.statistics.counters.roomEventEncryptionKeysSent += 1;
outboundKey.sharedWith.push(...toDistributeTo);
this.logger.trace(
`key index:${outboundKey.keyId} sent to ${outboundKey.sharedWith.map((m) => `${m.userId}:${m.deviceId}`).join(",")}`,
);
if (toDistributeTo.length > 0) {
this.logger.trace(`Sending key...`);
await this.transport.sendKey(encodeBase64(outboundKey.key), outboundKey.keyId, toDistributeTo);
this.statistics.counters.roomEventEncryptionKeysSent += 1;
outboundKey.sharedWith.push(...toDistributeTo);
this.logger.trace(
`key index:${outboundKey.keyId} sent to ${outboundKey.sharedWith.map((m) => `${m.userId}:${m.deviceId}`).join(",")}`,
);
}
if (hasKeyChanged) {
// Delay a bit before using this key
// It is recommended not to start using a key immediately but instead wait for a short time to make sure it is delivered.
Expand Down Expand Up @@ -318,4 +355,10 @@ export class RTCEncryptionManager implements IEncryptionManager {
globalThis.crypto.getRandomValues(key);
return key;
}

public onOwnKeyRatcheted(key: ArrayBuffer, keyIndex: number | undefined): void {
this.logger.debug(`Own key ratcheted for key index:${keyIndex} key:${encodeBase64(new Uint8Array(key))}`);

this.currentRatchetRequest?.resolve({ key, keyIndex: keyIndex! });
}
}
Loading