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

Context.js 14KB

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