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.

Worker.js 16KB

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