您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Worker.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /* global TransformStream */
  2. /* eslint-disable no-bitwise */
  3. // Worker for E2EE/Insertable streams.
  4. //
  5. import { deriveKeys, importKey, ratchet } from './crypto-utils';
  6. import { polyFillEncodedFrameMetadata, isArrayEqual } from './utils';
  7. // We use a ringbuffer of keys so we can change them and still decode packets that were
  8. // encrypted with an old key.
  9. const keyRingSize = 3;
  10. // We copy the first bytes of the VP8 payload unencrypted.
  11. // For keyframes this is 10 bytes, for non-keyframes (delta) 3. See
  12. // https://tools.ietf.org/html/rfc6386#section-9.1
  13. // This allows the bridge to continue detecting keyframes (only one byte needed in the JVB)
  14. // and is also a bit easier for the VP8 decoder (i.e. it generates funny garbage pictures
  15. // instead of being unable to decode).
  16. // This is a bit for show and we might want to reduce to 1 unconditionally in the final version.
  17. //
  18. // For audio (where frame.type is not set) we do not encrypt the opus TOC byte:
  19. // https://tools.ietf.org/html/rfc6716#section-3.1
  20. const unencryptedBytes = {
  21. key: 10,
  22. delta: 3,
  23. undefined: 1 // frame.type is not set on audio
  24. };
  25. // Use truncated SHA-256 hashes, 80 bіts for video, 32 bits for audio.
  26. // This follows the same principles as DTLS-SRTP.
  27. const authenticationTagOptions = {
  28. name: 'HMAC',
  29. hash: 'SHA-256'
  30. };
  31. const digestLength = {
  32. key: 10,
  33. delta: 10,
  34. undefined: 4 // frame.type is not set on audio
  35. };
  36. // Maximum number of forward ratchets to attempt when the authentication
  37. // tag on a remote packet does not match the current key.
  38. const ratchetWindow = 8;
  39. /**
  40. * Per-participant context holding the cryptographic keys and
  41. * encode/decode functions
  42. */
  43. class Context {
  44. /**
  45. * @param {string} id - local muc resourcepart
  46. */
  47. constructor(id) {
  48. // An array (ring) of keys that we use for sending and receiving.
  49. this._cryptoKeyRing = new Array(keyRingSize);
  50. // A pointer to the currently used key.
  51. this._currentKeyIndex = -1;
  52. // A per-sender counter that is used create the AES CTR.
  53. // Must be incremented on every frame that is sent, can be reset on
  54. // key changes.
  55. this._sendCount = 0n;
  56. this._id = id;
  57. }
  58. /**
  59. * Derives the different subkeys and starts using them for encryption or
  60. * decryption.
  61. * @param {Uint8Array|false} key bytes. Pass false to disable.
  62. * @param {Number} keyIndex
  63. */
  64. async setKey(keyBytes, keyIndex) {
  65. let newKey;
  66. if (keyBytes) {
  67. const material = await importKey(keyBytes);
  68. newKey = await deriveKeys(material);
  69. } else {
  70. newKey = false;
  71. }
  72. this._currentKeyIndex = keyIndex % this._cryptoKeyRing.length;
  73. this._setKeys(newKey);
  74. }
  75. /**
  76. * Sets a set of keys and resets the sendCount.
  77. * decryption.
  78. * @param {Object} keys set of keys.
  79. * @private
  80. */
  81. _setKeys(keys) {
  82. this._cryptoKeyRing[this._currentKeyIndex] = keys;
  83. this._sendCount = 0n; // Reset the send count (bigint).
  84. }
  85. /**
  86. * Function that will be injected in a stream and will encrypt the given encoded frames.
  87. *
  88. * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.
  89. * @param {TransformStreamDefaultController} controller - TransportStreamController.
  90. *
  91. * The packet format is a variant of
  92. * https://tools.ietf.org/html/draft-omara-sframe-00
  93. * using a trailer instead of a header. One of the design goals was to not require
  94. * changes to the SFU which for video requires not encrypting the keyframe bit of VP8
  95. * as SFUs need to detect a keyframe (framemarking or the generic frame descriptor will
  96. * solve this eventually). This also "hides" that a client is using E2EE a bit.
  97. *
  98. * Note that this operates on the full frame, i.e. for VP8 the data described in
  99. * https://tools.ietf.org/html/rfc6386#section-9.1
  100. *
  101. * The VP8 payload descriptor described in
  102. * https://tools.ietf.org/html/rfc7741#section-4.2
  103. * is part of the RTP packet and not part of the encoded frame and is therefore not
  104. * controllable by us. This is fine as the SFU keeps having access to it for routing.
  105. */
  106. encodeFunction(encodedFrame, controller) {
  107. const keyIndex = this._currentKeyIndex;
  108. if (this._cryptoKeyRing[keyIndex]) {
  109. this._sendCount++;
  110. // Thіs is not encrypted and contains the VP8 payload descriptor or the Opus TOC byte.
  111. const frameHeader = new Uint8Array(encodedFrame.data, 0, unencryptedBytes[encodedFrame.type]);
  112. // Construct frame trailer. Similar to the frame header described in
  113. // https://tools.ietf.org/html/draft-omara-sframe-00#section-4.2
  114. // but we put it at the end.
  115. // 0 1 2 3 4 5 6 7
  116. // ---------+---------------------------------+-+-+-+-+-+-+-+-+
  117. // payload | CTR... (length=LEN) |S|LEN |0| KID |
  118. // ---------+---------------------------------+-+-+-+-+-+-+-+-+
  119. const counter = new Uint8Array(16);
  120. const counterView = new DataView(counter.buffer);
  121. // The counter is encoded as a variable-length field.
  122. counterView.setBigUint64(8, this._sendCount);
  123. let counterLength = 8;
  124. for (let i = 8; i < counter.byteLength; i++ && counterLength--) {
  125. if (counterView.getUint8(i) !== 0) {
  126. break;
  127. }
  128. }
  129. const frameTrailer = new Uint8Array(counterLength + 1);
  130. frameTrailer.set(new Uint8Array(counter.buffer, counter.byteLength - counterLength));
  131. // Since we never send a counter of 0 we send counterLength - 1 on the wire.
  132. // This is different from the sframe draft, increases the key space and lets us
  133. // ignore the case of a zero-length counter at the receiver.
  134. frameTrailer[frameTrailer.byteLength - 1] = keyIndex | ((counterLength - 1) << 4);
  135. // XOR the counter with the saltKey to construct the AES CTR.
  136. const saltKey = new DataView(this._cryptoKeyRing[keyIndex].saltKey);
  137. for (let i = 0; i < counter.byteLength; i++) {
  138. counterView.setUint8(i, counterView.getUint8(i) ^ saltKey.getUint8(i));
  139. }
  140. return crypto.subtle.encrypt({
  141. name: 'AES-CTR',
  142. counter,
  143. length: 64
  144. }, this._cryptoKeyRing[keyIndex].encryptionKey, new Uint8Array(encodedFrame.data,
  145. unencryptedBytes[encodedFrame.type]))
  146. .then(cipherText => {
  147. const newData = new ArrayBuffer(frameHeader.byteLength + cipherText.byteLength
  148. + digestLength[encodedFrame.type] + frameTrailer.byteLength);
  149. const newUint8 = new Uint8Array(newData);
  150. newUint8.set(frameHeader); // copy first bytes.
  151. newUint8.set(new Uint8Array(cipherText), unencryptedBytes[encodedFrame.type]); // add ciphertext.
  152. // Leave some space for the authentication tag. This is filled with 0s initially, similar to
  153. // STUN message-integrity described in https://tools.ietf.org/html/rfc5389#section-15.4
  154. newUint8.set(frameTrailer, frameHeader.byteLength + cipherText.byteLength
  155. + digestLength[encodedFrame.type]); // append trailer.
  156. return crypto.subtle.sign(authenticationTagOptions, this._cryptoKeyRing[keyIndex].authenticationKey,
  157. new Uint8Array(newData)).then(authTag => {
  158. // Set the truncated authentication tag.
  159. newUint8.set(new Uint8Array(authTag, 0, digestLength[encodedFrame.type]),
  160. unencryptedBytes[encodedFrame.type] + cipherText.byteLength);
  161. encodedFrame.data = newData;
  162. return controller.enqueue(encodedFrame);
  163. });
  164. }, e => {
  165. // TODO: surface this to the app.
  166. console.error(e);
  167. // We are not enqueuing the frame here on purpose.
  168. });
  169. }
  170. /* NOTE WELL:
  171. * This will send unencrypted data (only protected by DTLS transport encryption) when no key is configured.
  172. * This is ok for demo purposes but should not be done once this becomes more relied upon.
  173. */
  174. controller.enqueue(encodedFrame);
  175. }
  176. /**
  177. * Function that will be injected in a stream and will decrypt the given encoded frames.
  178. *
  179. * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.
  180. * @param {TransformStreamDefaultController} controller - TransportStreamController.
  181. */
  182. async decodeFunction(encodedFrame, controller) {
  183. const data = new Uint8Array(encodedFrame.data);
  184. const keyIndex = data[encodedFrame.data.byteLength - 1] & 0x7;
  185. if (this._cryptoKeyRing[keyIndex]) {
  186. const counterLength = 1 + ((data[encodedFrame.data.byteLength - 1] >> 4) & 0x7);
  187. const frameHeader = new Uint8Array(encodedFrame.data, 0, unencryptedBytes[encodedFrame.type]);
  188. // Extract the truncated authentication tag.
  189. const authTagOffset = encodedFrame.data.byteLength - (digestLength[encodedFrame.type]
  190. + counterLength + 1);
  191. const authTag = encodedFrame.data.slice(authTagOffset, authTagOffset
  192. + digestLength[encodedFrame.type]);
  193. // Set authentication tag bytes to 0.
  194. const zeros = new Uint8Array(digestLength[encodedFrame.type]);
  195. data.set(zeros, encodedFrame.data.byteLength - (digestLength[encodedFrame.type] + counterLength + 1));
  196. // Do truncated hash comparison. If the hash does not match we might have to advance the
  197. // ratchet a limited number of times. See (even though the description there is odd)
  198. // https://tools.ietf.org/html/draft-omara-sframe-00#section-4.3.5.1
  199. let { authenticationKey, material } = this._cryptoKeyRing[keyIndex];
  200. let valid = false;
  201. let newKeys = null;
  202. for (let distance = 0; distance < ratchetWindow; distance++) {
  203. const calculatedTag = await crypto.subtle.sign(authenticationTagOptions,
  204. authenticationKey, encodedFrame.data);
  205. if (isArrayEqual(new Uint8Array(authTag),
  206. new Uint8Array(calculatedTag.slice(0, digestLength[encodedFrame.type])))) {
  207. valid = true;
  208. if (distance > 0) {
  209. this._setKeys(newKeys);
  210. }
  211. break;
  212. }
  213. // Attempt to ratchet and generate the next set of keys.
  214. material = await importKey(await ratchet(material));
  215. newKeys = await deriveKeys(material);
  216. authenticationKey = newKeys.authenticationKey;
  217. }
  218. // Check whether we found a valid signature.
  219. if (!valid) {
  220. // TODO: return an error to the app.
  221. console.error('Authentication tag mismatch');
  222. return;
  223. }
  224. // Extract the counter.
  225. const counter = new Uint8Array(16);
  226. counter.set(data.slice(encodedFrame.data.byteLength - (counterLength + 1),
  227. encodedFrame.data.byteLength - 1), 16 - counterLength);
  228. const counterView = new DataView(counter.buffer);
  229. // XOR the counter with the saltKey to construct the AES CTR.
  230. const saltKey = new DataView(this._cryptoKeyRing[keyIndex].saltKey);
  231. for (let i = 0; i < counter.byteLength; i++) {
  232. counterView.setUint8(i,
  233. counterView.getUint8(i) ^ saltKey.getUint8(i));
  234. }
  235. return crypto.subtle.decrypt({
  236. name: 'AES-CTR',
  237. counter,
  238. length: 64
  239. }, this._cryptoKeyRing[keyIndex].encryptionKey, new Uint8Array(encodedFrame.data,
  240. unencryptedBytes[encodedFrame.type],
  241. encodedFrame.data.byteLength - (unencryptedBytes[encodedFrame.type]
  242. + digestLength[encodedFrame.type] + counterLength + 1))
  243. ).then(plainText => {
  244. const newData = new ArrayBuffer(unencryptedBytes[encodedFrame.type] + plainText.byteLength);
  245. const newUint8 = new Uint8Array(newData);
  246. newUint8.set(frameHeader);
  247. newUint8.set(new Uint8Array(plainText), unencryptedBytes[encodedFrame.type]);
  248. encodedFrame.data = newData;
  249. return controller.enqueue(encodedFrame);
  250. }, e => {
  251. console.error(e);
  252. // TODO: notify the application about error status.
  253. // TODO: For video we need a better strategy since we do not want to based any
  254. // non-error frames on a garbage keyframe.
  255. if (encodedFrame.type === undefined) { // audio, replace with silence.
  256. const newData = new ArrayBuffer(3);
  257. const newUint8 = new Uint8Array(newData);
  258. newUint8.set([ 0xd8, 0xff, 0xfe ]); // opus silence frame.
  259. encodedFrame.data = newData;
  260. controller.enqueue(encodedFrame);
  261. }
  262. });
  263. } else if (keyIndex >= this._cryptoKeyRing.length && this._cryptoKeyRing[this._currentKeyIndex]) {
  264. // If we are encrypting but don't have a key for the remote drop the frame.
  265. // This is a heuristic since we don't know whether a packet is encrypted,
  266. // do not have a checksum and do not have signaling for whether a remote participant does
  267. // encrypt or not.
  268. return;
  269. }
  270. // TODO: this just passes through to the decoder. Is that ok? If we don't know the key yet
  271. // we might want to buffer a bit but it is still unclear how to do that (and for how long etc).
  272. controller.enqueue(encodedFrame);
  273. }
  274. }
  275. const contexts = new Map(); // Map participant id => context
  276. onmessage = async event => {
  277. const { operation } = event.data;
  278. if (operation === 'encode') {
  279. const { readableStream, writableStream, participantId } = event.data;
  280. if (!contexts.has(participantId)) {
  281. contexts.set(participantId, new Context(participantId));
  282. }
  283. const context = contexts.get(participantId);
  284. const transformStream = new TransformStream({
  285. transform: context.encodeFunction.bind(context)
  286. });
  287. readableStream
  288. .pipeThrough(new TransformStream({
  289. transform: polyFillEncodedFrameMetadata // M83 polyfill.
  290. }))
  291. .pipeThrough(transformStream)
  292. .pipeTo(writableStream);
  293. } else if (operation === 'decode') {
  294. const { readableStream, writableStream, participantId } = event.data;
  295. if (!contexts.has(participantId)) {
  296. contexts.set(participantId, new Context(participantId));
  297. }
  298. const context = contexts.get(participantId);
  299. const transformStream = new TransformStream({
  300. transform: context.decodeFunction.bind(context)
  301. });
  302. readableStream
  303. .pipeThrough(new TransformStream({
  304. transform: polyFillEncodedFrameMetadata // M83 polyfill.
  305. }))
  306. .pipeThrough(transformStream)
  307. .pipeTo(writableStream);
  308. } else if (operation === 'setKey') {
  309. const { participantId, key, keyIndex } = event.data;
  310. if (!contexts.has(participantId)) {
  311. contexts.set(participantId, new Context(participantId));
  312. }
  313. const context = contexts.get(participantId);
  314. if (key) {
  315. context.setKey(key, keyIndex);
  316. } else {
  317. context.setKey(false, keyIndex);
  318. }
  319. } else if (operation === 'cleanup') {
  320. const { participantId } = event.data;
  321. contexts.delete(participantId);
  322. } else {
  323. console.error('e2ee worker', operation);
  324. }
  325. };