You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. // Worker for E2EE/Insertable streams. Currently served as an inline blob.
  2. const code = `
  3. // We use a ringbuffer of keys so we can change them and still decode packets that were
  4. // encrypted with an old key.
  5. // In the future when we dont rely on a globally shared key we will actually use it. For
  6. // now set the size to 1 which means there is only a single key. This causes some
  7. // glitches when changing the key but its ok.
  8. const keyRingSize = 1;
  9. // We use a 96 bit IV for AES GCM. This is signalled in plain together with the
  10. // packet. See https://developer.mozilla.org/en-US/docs/Web/API/AesGcmParams
  11. const ivLength = 12;
  12. // We use a 128 bit key for AES GCM.
  13. const keyGenParameters = {
  14. name: 'AES-GCM',
  15. length: 128
  16. };
  17. // We copy the first bytes of the VP8 payload unencrypted.
  18. // For keyframes this is 10 bytes, for non-keyframes (delta) 3. See
  19. // https://tools.ietf.org/html/rfc6386#section-9.1
  20. // This allows the bridge to continue detecting keyframes (only one byte needed in the JVB)
  21. // and is also a bit easier for the VP8 decoder (i.e. it generates funny garbage pictures
  22. // instead of being unable to decode).
  23. // This is a bit for show and we might want to reduce to 1 unconditionally in the final version.
  24. //
  25. // For audio (where frame.type is not set) we do not encrypt the opus TOC byte:
  26. // https://tools.ietf.org/html/rfc6716#section-3.1
  27. const unencryptedBytes = {
  28. key: 10,
  29. delta: 3,
  30. undefined: 1 // frame.type is not set on audio
  31. };
  32. // Salt used in key derivation
  33. // FIXME: We currently use the MUC room name for this which has the same lifetime
  34. // as this worker. While not (pseudo)random as recommended in
  35. // https://developer.mozilla.org/en-US/docs/Web/API/Pbkdf2Params
  36. // this is easily available and the same for all participants.
  37. // We currently do not enforce a minimum length of 16 bytes either.
  38. let keySalt;
  39. // Raw keyBytes used to derive the key.
  40. let keyBytes;
  41. /**
  42. * Derives a AES-GCM key from the input using PBKDF2
  43. * The key length can be configured above and should be either 128 or 256 bits.
  44. * @param {Uint8Array} keyBytes - Value to derive key from
  45. * @param {Uint8Array} salt - Salt used in key derivation
  46. */
  47. async function deriveKey(keyBytes, salt) {
  48. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey
  49. const material = await crypto.subtle.importKey('raw', keyBytes,
  50. 'PBKDF2', false, [ 'deriveBits', 'deriveKey' ]);
  51. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveKey#PBKDF2
  52. return crypto.subtle.deriveKey({
  53. name: 'PBKDF2',
  54. salt,
  55. iterations: 100000,
  56. hash: 'SHA-256'
  57. }, material, keyGenParameters, false, [ 'encrypt', 'decrypt' ]);
  58. }
  59. /** Per-participant context holding the cryptographic keys and
  60. * encode/decode functions
  61. */
  62. class Context {
  63. /**
  64. * @param {string} id - local muc resourcepart
  65. */
  66. constructor(id) {
  67. // An array (ring) of keys that we use for sending and receiving.
  68. this._cryptoKeyRing = new Array(keyRingSize);
  69. // A pointer to the currently used key.
  70. this._currentKeyIndex = -1;
  71. // We keep track of how many frames we have sent per ssrc.
  72. // Starts with a random offset similar to the RTP sequence number.
  73. this._sendCounts = new Map();
  74. this._id = id;
  75. }
  76. /**
  77. * Sets a key and starts using it for encrypting.
  78. * @param {CryptoKey} key
  79. */
  80. setKey(key) {
  81. this._currentKeyIndex++;
  82. this._cryptoKeyRing[this._currentKeyIndex % this._cryptoKeyRing.length] = key;
  83. }
  84. /**
  85. * Construct the IV used for AES-GCM and sent (in plain) with the packet similar to
  86. * https://tools.ietf.org/html/rfc7714#section-8.1
  87. * It concatenates
  88. * - the 32 bit synchronization source (SSRC) given on the encoded frame,
  89. * - the 32 bit rtp timestamp given on the encoded frame,
  90. * - a send counter that is specific to the SSRC. Starts at a random number.
  91. * The send counter is essentially the pictureId but we currently have to implement this ourselves.
  92. * There is no XOR with a salt. Note that this IV leaks the SSRC to the receiver but since this is
  93. * randomly generated and SFUs may not rewrite this is considered acceptable.
  94. * The SSRC is used to allow demultiplexing multiple streams with the same key, as described in
  95. * https://tools.ietf.org/html/rfc3711#section-4.1.1
  96. * The RTP timestamp is 32 bits and advances by the codec clock rate (90khz for video, 48khz for
  97. * opus audio) every second. For video it rolls over roughly every 13 hours.
  98. * The send counter will advance at the frame rate (30fps for video, 50fps for 20ms opus audio)
  99. * every second. It will take a long time to roll over.
  100. *
  101. * See also https://developer.mozilla.org/en-US/docs/Web/API/AesGcmParams
  102. */
  103. makeIV(synchronizationSource, timestamp) {
  104. const iv = new ArrayBuffer(ivLength);
  105. const ivView = new DataView(iv);
  106. // having to keep our own send count (similar to a picture id) is not ideal.
  107. if (!this._sendCounts.has(synchronizationSource)) {
  108. // Initialize with a random offset, similar to the RTP sequence number.
  109. this._sendCounts.set(synchronizationSource, Math.floor(Math.random() * 0xFFFF));
  110. }
  111. const sendCount = this._sendCounts.get(synchronizationSource);
  112. ivView.setUint32(0, synchronizationSource);
  113. ivView.setUint32(4, timestamp);
  114. ivView.setUint32(8, sendCount % 0xFFFF);
  115. this._sendCounts.set(synchronizationSource, sendCount + 1);
  116. return iv;
  117. }
  118. /**
  119. * Function that will be injected in a stream and will encrypt the given encoded frames.
  120. *
  121. * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.
  122. * @param {TransformStreamDefaultController} controller - TransportStreamController.
  123. *
  124. * The packet format is described below. One of the design goals was to not require
  125. * changes to the SFU which for video requires not encrypting the keyframe bit of VP8
  126. * as SFUs need to detect a keyframe (framemarking or the generic frame descriptor will
  127. * solve this eventually). This also "hides" that a client is using E2EE a bit.
  128. *
  129. * Note that this operates on the full frame, i.e. for VP8 the data described in
  130. * https://tools.ietf.org/html/rfc6386#section-9.1
  131. *
  132. * The VP8 payload descriptor described in
  133. * https://tools.ietf.org/html/rfc7741#section-4.2
  134. * is part of the RTP packet and not part of the frame and is not controllable by us.
  135. * This is fine as the SFU keeps having access to it for routing.
  136. *
  137. * The encrypted frame is formed as follows:
  138. * 1) Leave the first (10, 3, 1) bytes unencrypted, depending on the frame type and kind.
  139. * 2) Form the GCM IV for the frame as described above.
  140. * 3) Encrypt the rest of the frame using AES-GCM.
  141. * 4) Allocate space for the encrypted frame.
  142. * 5) Copy the unencrypted bytes to the start of the encrypted frame.
  143. * 6) Append the ciphertext to the encrypted frame.
  144. * 7) Append the IV.
  145. * 8) Append a single byte for the key identifier. TODO: we don't need all the bits.
  146. * 9) Enqueue the encrypted frame for sending.
  147. */
  148. encodeFunction(encodedFrame, controller) {
  149. const keyIndex = this._currentKeyIndex % this._cryptoKeyRing.length;
  150. if (this._cryptoKeyRing[keyIndex]) {
  151. const iv = this.makeIV(encodedFrame.synchronizationSource, encodedFrame.timestamp);
  152. return crypto.subtle.encrypt({
  153. name: 'AES-GCM',
  154. iv,
  155. additionalData: new Uint8Array(encodedFrame.data, 0, unencryptedBytes[encodedFrame.type])
  156. }, this._cryptoKeyRing[keyIndex], new Uint8Array(encodedFrame.data,
  157. unencryptedBytes[encodedFrame.type]))
  158. .then(cipherText => {
  159. const newData = new ArrayBuffer(unencryptedBytes[encodedFrame.type] + cipherText.byteLength
  160. + iv.byteLength + 1);
  161. const newUint8 = new Uint8Array(newData);
  162. newUint8.set(
  163. new Uint8Array(encodedFrame.data, 0, unencryptedBytes[encodedFrame.type])); // copy first bytes.
  164. newUint8.set(
  165. new Uint8Array(cipherText), unencryptedBytes[encodedFrame.type]); // add ciphertext.
  166. newUint8.set(
  167. new Uint8Array(iv), unencryptedBytes[encodedFrame.type] + cipherText.byteLength); // append IV.
  168. newUint8[unencryptedBytes[encodedFrame.type] + cipherText.byteLength + ivLength]
  169. = keyIndex; // set key index.
  170. encodedFrame.data = newData;
  171. return controller.enqueue(encodedFrame);
  172. }, e => {
  173. console.error(e);
  174. // We are not enqueuing the frame here on purpose.
  175. });
  176. }
  177. /* NOTE WELL:
  178. * This will send unencrypted data (only protected by DTLS transport encryption) when no key is configured.
  179. * This is ok for demo purposes but should not be done once this becomes more relied upon.
  180. */
  181. controller.enqueue(encodedFrame);
  182. }
  183. /**
  184. * Function that will be injected in a stream and will decrypt the given encoded frames.
  185. *
  186. * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.
  187. * @param {TransformStreamDefaultController} controller - TransportStreamController.
  188. *
  189. * The decrypted frame is formed as follows:
  190. * 1) Extract the key index from the last byte of the encrypted frame.
  191. * If there is no key associated with the key index, the frame is enqueued for decoding
  192. * and these steps terminate.
  193. * 2) Determine the frame type in order to look up the number of unencrypted header bytes.
  194. * 2) Extract the 12-byte IV from its position near the end of the packet.
  195. * Note: the IV is treated as opaque and not reconstructed from the input.
  196. * 3) Decrypt the encrypted frame content after the unencrypted bytes using AES-GCM.
  197. * 4) Allocate space for the decrypted frame.
  198. * 5) Copy the unencrypted bytes from the start of the encrypted frame.
  199. * 6) Append the plaintext to the decrypted frame.
  200. * 7) Enqueue the decrypted frame for decoding.
  201. */
  202. decodeFunction(encodedFrame, controller) {
  203. const data = new Uint8Array(encodedFrame.data);
  204. const keyIndex = data[encodedFrame.data.byteLength - 1];
  205. if (this._cryptoKeyRing[keyIndex]) {
  206. const iv = new Uint8Array(encodedFrame.data, encodedFrame.data.byteLength - ivLength - 1, ivLength);
  207. const cipherTextStart = unencryptedBytes[encodedFrame.type];
  208. const cipherTextLength = encodedFrame.data.byteLength - (unencryptedBytes[encodedFrame.type]
  209. + ivLength + 1);
  210. return crypto.subtle.decrypt({
  211. name: 'AES-GCM',
  212. iv,
  213. additionalData: new Uint8Array(encodedFrame.data, 0, unencryptedBytes[encodedFrame.type])
  214. }, this._cryptoKeyRing[keyIndex], new Uint8Array(encodedFrame.data, cipherTextStart, cipherTextLength))
  215. .then(plainText => {
  216. const newData = new ArrayBuffer(unencryptedBytes[encodedFrame.type] + plainText.byteLength);
  217. const newUint8 = new Uint8Array(newData);
  218. newUint8.set(new Uint8Array(encodedFrame.data, 0, unencryptedBytes[encodedFrame.type]));
  219. newUint8.set(new Uint8Array(plainText), unencryptedBytes[encodedFrame.type]);
  220. encodedFrame.data = newData;
  221. return controller.enqueue(encodedFrame);
  222. }, e => {
  223. console.error(e);
  224. // TODO: notify the application about error status.
  225. // TODO: For video we need a better strategy since we do not want to based any
  226. // non-error frames on a garbage keyframe.
  227. if (encodedFrame.type === undefined) { // audio, replace with silence.
  228. // audio, replace with silence.
  229. const newData = new ArrayBuffer(3);
  230. const newUint8 = new Uint8Array(newData);
  231. newUint8.set([ 0xd8, 0xff, 0xfe ]); // opus silence frame.
  232. encodedFrame.data = newData;
  233. controller.enqueue(encodedFrame);
  234. }
  235. });
  236. } else if (keyIndex >= this._cryptoKeyRing.length
  237. && this._cryptoKeyRing[this._currentKeyIndex % this._cryptoKeyRing.length]) {
  238. // If we are encrypting but don't have a key for the remote drop the frame.
  239. // This is a heuristic since we don't know whether a packet is encrypted,
  240. // do not have a checksum and do not have signaling for whether a remote participant does
  241. // encrypt or not.
  242. return;
  243. }
  244. // TODO: this just passes through to the decoder. Is that ok? If we don't know the key yet
  245. // we might want to buffer a bit but it is still unclear how to do that (and for how long etc).
  246. controller.enqueue(encodedFrame);
  247. }
  248. }
  249. const contexts = new Map(); // Map participant id => context
  250. onmessage = async event => {
  251. const { operation } = event.data;
  252. if (operation === 'initialize') {
  253. keySalt = event.data.salt;
  254. } else if (operation === 'encode') {
  255. const { readableStream, writableStream, participantId } = event.data;
  256. if (!contexts.has(participantId)) {
  257. contexts.set(participantId, new Context(participantId));
  258. }
  259. const context = contexts.get(participantId);
  260. const transformStream = new TransformStream({
  261. transform: context.encodeFunction.bind(context)
  262. });
  263. readableStream
  264. .pipeThrough(transformStream)
  265. .pipeTo(writableStream);
  266. if (keyBytes) {
  267. context.setKey(await deriveKey(keyBytes, keySalt));
  268. }
  269. } else if (operation === 'decode') {
  270. const { readableStream, writableStream, participantId } = event.data;
  271. if (!contexts.has(participantId)) {
  272. contexts.set(participantId, new Context(participantId));
  273. }
  274. const context = contexts.get(participantId);
  275. const transformStream = new TransformStream({
  276. transform: context.decodeFunction.bind(context)
  277. });
  278. readableStream
  279. .pipeThrough(transformStream)
  280. .pipeTo(writableStream);
  281. if (keyBytes) {
  282. context.setKey(await deriveKey(keyBytes, keySalt));
  283. }
  284. } else if (operation === 'setKey') {
  285. keyBytes = event.data.key;
  286. contexts.forEach(async context => {
  287. if (keyBytes) {
  288. context.setKey(await deriveKey(keyBytes, keySalt));
  289. } else {
  290. context.setKey(false);
  291. }
  292. });
  293. } else {
  294. console.error('e2ee worker', operation);
  295. }
  296. };
  297. `;
  298. export const createWorkerScript = () => URL.createObjectURL(new Blob([ code ], { type: 'application/javascript' }));