Skip to content
Merged
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
17 changes: 11 additions & 6 deletions docs/guide/advanced/end-to-end-encryption.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,24 +189,29 @@ receiver.transform = new RTCRtpScriptTransform(worker, { side: 'receive' });

This section specifies the format, so that it can be implemented elsewhere. It is RFC 9605 applied per frame, with the key IDs and the codec layouts below.

### Version

This is version 1, named `webrtc-java-sframe/1`: `KeyProvider.FORMAT` in Java, `FORMAT` in the browser module. Nothing in a frame says which format it is in, so the participants of a call agree on it, as on the cipher suite and the keys: by the application's signaling, as part of what it sends with the keys. A later version, such as SFrame with the RTP payload format WebRTC is working on, which needs no codec layouts, has a name of its own and is agreed the same way, never told apart by trying.

### Cipher Suites and Keys

Every participant of a call uses the same cipher suite of RFC 9605, Section 4.5, by default `AES_128_GCM_SHA256_128` (0x0004). The key and salt of each key ID are derived from the participant's key with `derive_key_salt` (RFC 9605, Section 4.4.2), and frames are encrypted and decrypted with `encrypt` and `decrypt` (Sections 4.4.3 and 4.4.4).

### Key IDs

A key ID (KID) is made up of three fields, from the most significant bit down, after the MLS scheme of RFC 9605, Section 5.2:
A key ID (KID) is made up of four fields, from the most significant bit down. The lowest 16 bits are the "key generation | ratchet step" of the sender keys scheme of RFC 9605, Section 5.1, and the fields above them follow the MLS scheme of Section 5.2:

```
63 40 39 8 7 0
+----------------+-----------------------------+------------+
| context (24) | participant (32) | generation |
+----------------+-----------------------------+------------+
63 48 47 16 15 8 7 0
+--------------+-----------------------------+-------------+--------------+
| context (16) | participant (32) | generation | ratchet step |
+--------------+-----------------------------+-------------+--------------+
```

- **participant**: the ID of the participant who encrypted the frame. A receiver finds the key by it and by the generation.
- **generation**: the generation of that participant's key, 0 to 255.
- **context**: one per RTP stream the participant sends, given out from 0 upwards and never reused for the participant's key provider. Since the KID goes into the key derivation, every stream encrypts with a key and salt of its own.
- **ratchet step**: how many times the generation's key was moved forward with the ratchet of RFC 9605, Section 5.1, `base_key[i+1] = HKDF-Expand(HKDF-Extract("", base_key[i]), "SFrame 1.0 Ratchet", Nh)`. This version of the format always sends 0, and a receiver drops a frame with any other step as one whose key it does not have.
- **context**: one per RTP stream the participant sends, given out from 0 upwards and never reused for the participant's key provider, which therefore serves up to 65,536 streams. Since the KID goes into the key derivation, every stream encrypts with a key and salt of its own.

### Counters

Expand Down
25 changes: 17 additions & 8 deletions docs/public/e2ee/webrtc-java-sframe.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@

const subtle = globalThis.crypto.subtle;

/** The name of the frame format, as the Java KeyProvider.FORMAT has it. */
export const FORMAT = 'webrtc-java-sframe/1';

/** The cipher suites of RFC 9605, Section 4.5, by their registry value. */
export const CipherSuite = Object.freeze({
AES_128_CTR_HMAC_SHA256_80: 1,
Expand Down Expand Up @@ -66,7 +69,7 @@ export const Failure = Object.freeze({

const NONCE_LENGTH = 12;
const MAX_PARTICIPANT = 0xffffffff;
const MAX_CONTEXT = 0xffffff;
const MAX_CONTEXT = 0xffff;

/** OBU_FRAME and OBU_SEQUENCE_HEADER, no extension, no size field. */
const AV1_WRAPPER = 6 << 3;
Expand Down Expand Up @@ -299,9 +302,13 @@ export class SFrameKey {

// ---------------------------------------------------------- Frame format

/** KID = context (24 bits) | participant (32 bits) | generation (8 bits). */
export function keyId(context, participant, generation) {
return BigInt(context) << 40n | BigInt(participant) << 8n | BigInt(generation);
/**
* KID = context (16 bits) | participant (32 bits) | generation (8 bits) |
* ratchet step (8 bits). This version always sends a ratchet step of 0, and
* takes any other step for a key it does not have.
*/
export function keyId(context, participant, generation, ratchetStep = 0) {
return BigInt(context) << 48n | BigInt(participant) << 16n | BigInt(generation) << 8n | BigInt(ratchetStep);
}

function codecOf(mimeType) {
Expand Down Expand Up @@ -776,12 +783,14 @@ class FrameDecryptor extends FrameCryptor {
return this.fail(stream, Failure.MALFORMED, -1, -1, info);
}

const participant = Number(header.kid >> 8n & 0xffffffffn);
const generation = Number(header.kid & 0xffn);
const context = Number(header.kid >> 40n);
const participant = Number(header.kid >> 16n & 0xffffffffn);
const generation = Number(header.kid >> 8n & 0xffn);
const ratchetStep = Number(header.kid & 0xffn);
const context = Number(header.kid >> 48n);
const now = Date.now();

const key = keys.decryptionKey(participant, generation, now);
// A key moved forward by the ratchet is one this version never has.
const key = ratchetStep === 0 ? keys.decryptionKey(participant, generation, now) : null;

if (!key) {
return this.fail(stream, Failure.UNKNOWN_KEY, participant, generation, info);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public enum CryptoFailure {
UNSUPPORTED_CODEC,

/**
* The {@link KeyProvider} gave out every one of its 2<sup>24</sup>
* The {@link KeyProvider} gave out every one of its 2<sup>16</sup>
* sender contexts, and has to be replaced.
*/
CONTEXTS_EXHAUSTED
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ int process(long ssrc, String mimeType, boolean video, boolean keyFrame, byte[]
int generation = FrameFormat.generation(kid);
long now = System.nanoTime();

KeyProvider.RemoteKey key = keys.decryptionKey(participant, generation, now);
// A key moved forward by the ratchet is one this version never has.
KeyProvider.RemoteKey key = FrameFormat.ratchetStep(kid) == 0
? keys.decryptionKey(participant, generation, now)
: null;

if (key == null) {
return fail(stream, CryptoFailure.UNKNOWN_KEY, participant, generation, mimeType);
Expand Down
28 changes: 19 additions & 9 deletions webrtc/src/main/java/dev/onvoid/webrtc/e2ee/FrameFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ final class FrameFormat {
/** The largest key generation, 8 bits. */
static final int MAX_GENERATION = 0xFF;

/** The largest context, 24 bits. */
static final int MAX_CONTEXT = 0xFF_FFFF;
/** The largest context, 16 bits. */
static final int MAX_CONTEXT = 0xFFFF;

/**
* The OBU header an AV1 delta frame is wrapped in: OBU_FRAME (type 6), no
Expand All @@ -59,23 +59,33 @@ private FrameFormat() {
}

/**
* KID = context (24 bits) | participant (32 bits) | generation (8 bits),
* from the most significant bits down, after RFC 9605, Section 5.2.
* KID = context (16 bits) | participant (32 bits) | generation (8 bits) |
* ratchet step (8 bits), from the most significant bits down. The lowest
* 16 bits are the "key generation | ratchet step" of RFC 9605, Section
* 5.1, the participant and context above them follow Section 5.2.
* <p>
* The ratchet step is the number of times the generation's key was moved
* forward with the ratchet of RFC 9605, Section 5.1. This version always
* sends 0, and takes any other step for a key it does not have.
*/
static long kid(int context, long participant, int generation) {
return (long) context << 40 | participant << 8 | generation;
static long kid(int context, long participant, int generation, int ratchetStep) {
return (long) context << 48 | participant << 16 | (long) generation << 8 | ratchetStep;
}

static int context(long kid) {
return (int) (kid >>> 40);
return (int) (kid >>> 48);
}

static long participant(long kid) {
return kid >>> 8 & MAX_PARTICIPANT;
return kid >>> 16 & MAX_PARTICIPANT;
}

static int generation(long kid) {
return (int) (kid & MAX_GENERATION);
return (int) (kid >>> 8 & MAX_GENERATION);
}

static int ratchetStep(long kid) {
return (int) (kid & 0xFF);
}

/**
Expand Down
9 changes: 8 additions & 1 deletion webrtc/src/main/java/dev/onvoid/webrtc/e2ee/KeyProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@
*/
public final class KeyProvider {

/**
* The name of the frame format the transforms write and read. Nothing in
* a frame says which format it is in, so the participants of a call agree
* on it by their signaling, along with the cipher suite and the keys.
*/
public static final String FORMAT = "webrtc-java-sframe/1";

/** The smallest base key accepted, in bytes. */
static final int MIN_KEY_LENGTH = 16;

Expand Down Expand Up @@ -636,7 +643,7 @@ static final class LocalKey {

SFrame sframe(CipherSuite suite, int context, long participant) {
return derived.computeIfAbsent(context, c ->
SFrame.derive(suite, FrameFormat.kid(c, participant, generation), baseKey));
SFrame.derive(suite, FrameFormat.kid(c, participant, generation, 0), baseKey));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ void browserModuleMatchesJava() throws Exception {

List<String> output = runNode(input.toString());

assertTrue(output.contains("format " + KeyProvider.FORMAT), () -> "The formats differ: " + output);

assertEquals(CipherSuite.values().length, output.stream().filter(l -> l.startsWith("vector")).count());
output.stream().filter(l -> l.startsWith("vector"))
.forEach(l -> assertTrue(l.endsWith(" ok"), "RFC 9605 vector in JavaScript: " + l));
Expand Down
53 changes: 51 additions & 2 deletions webrtc/src/test/java/dev/onvoid/webrtc/e2ee/FrameCryptorTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,8 @@ void everySuiteRoundTrips() {
byte[] frame = frame(1000);
byte[] sealed = process(encryptor(sender), SSRC, "video/VP8", true, true, frame);

// The tag, and a header of a two-byte KID and a counter of zero.
assertEquals(frame.length + 3 + suite.getTagLength(), sealed.length, suite.name());
// The tag, and a header of a three-byte KID and a counter of zero.
assertEquals(frame.length + 4 + suite.getTagLength(), sealed.length, suite.name());
assertArrayEquals(frame, process(decryptor(receiver), SSRC, "video/VP8", true, true, sealed),
suite.name());
}
Expand Down Expand Up @@ -408,6 +408,55 @@ void oldGenerationsRetire() throws InterruptedException {
assertEquals(0, last(bobEvents).getGeneration());
}

@Test
void keyIdHasFourFields() {
long kid = FrameFormat.kid(0xABCD, 0xFEDC_BA98L, 0x76, 0x54);

assertEquals(0xABCD_FEDC_BA98_7654L, kid);
assertEquals(0xABCD, FrameFormat.context(kid));
assertEquals(0xFEDC_BA98L, FrameFormat.participant(kid));
assertEquals(0x76, FrameFormat.generation(kid));
assertEquals(0x54, FrameFormat.ratchetStep(kid));

// What goes out: the ratchet step is always 0 in this version.
byte[] sealed = process(encryptor(alice), SSRC, "video/VP9", true, true, frame(50));
long[] header = header(sealed, 0);

assertEquals(FrameFormat.kid(0, ALICE, 0, 0), header[0]);
}

@Test
void ratchetedKeysAreUnknown() {
// A frame under a key moved forward once, as a later version may
// send: its key is not there, however well it would authenticate.
long kid = FrameFormat.kid(0, ALICE, 0, 1);
SFrame sframe = SFrame.derive(alice.getCipherSuite(), kid, aliceKey);

byte[] plaintext = frame(100);
byte[] sealed = new byte[SFrame.MAX_HEADER_LENGTH + plaintext.length + 16];
int length = sframe.encrypt(0, new byte[0], 0, 0, plaintext, 0, plaintext.length, sealed, 0);

assertNull(process(decryptor(bob), SSRC, "video/VP9", true, true, Arrays.copyOf(sealed, length)));

CryptoEvent event = last(bobEvents);
assertEquals(CryptoFailure.UNKNOWN_KEY, event.getFailure());
assertEquals(ALICE, event.getParticipant());
assertEquals(0, event.getGeneration());
}

@Test
void contextsRunOut() {
KeyProvider keys = KeyProvider.builder(ALICE).build();

for (int i = 0; i <= FrameFormat.MAX_CONTEXT; i++) {
assertEquals(i, keys.allocateContext());
}

// 65,536 streams in all, and then none.
assertEquals(-1, keys.allocateContext());
assertEquals(-1, keys.allocateContext());
}

@Test
void generationsWrapAround() {
assertTrue(KeyProvider.isNewer(1, 0));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
// jsKey <participant> <hex> the key this side encrypts with
// frame <mime> <key 0|1> <ssrc> <plain hex> <sealed hex>
//
// Prints "vector <n> ok|fail", "decrypt <n> ok|fail <why>" and
// Prints "format <name>", "vector <n> ok|fail", "decrypt <n> ok|fail <why>" and
// "sealed <n> <hex>", then "done".

import { readFileSync } from 'node:fs';
Expand All @@ -23,6 +23,8 @@ const sframe = await import(pathToFileURL(moduleFile).href);
const hex = (s) => Uint8Array.from(s.match(/../g) || [], (b) => parseInt(b, 16));
const toHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');

console.log(`format ${sframe.FORMAT}`);

// The SFrame vectors of RFC 9605, Appendix C.3.
let index = 0;

Expand Down
Loading