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.

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