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

Context.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. this._signatureKey = null;
  60. this._signatureOptions = null;
  61. }
  62. /**
  63. * Derives the different subkeys and starts using them for encryption or
  64. * decryption.
  65. * @param {Uint8Array|false} key bytes. Pass false to disable.
  66. * @param {Number} keyIndex
  67. */
  68. async setKey(keyBytes, keyIndex) {
  69. let newKey;
  70. if (keyBytes) {
  71. const material = await importKey(keyBytes);
  72. newKey = await deriveKeys(material);
  73. } else {
  74. newKey = false;
  75. }
  76. this._currentKeyIndex = keyIndex % this._cryptoKeyRing.length;
  77. this._setKeys(newKey);
  78. }
  79. /**
  80. * Sets a set of keys and resets the sendCount.
  81. * decryption.
  82. * @param {Object} keys set of keys.
  83. * @param {Number} keyIndex optional
  84. * @private
  85. */
  86. _setKeys(keys, keyIndex = -1) {
  87. if (keyIndex >= 0) {
  88. this._cryptoKeyRing[keyIndex] = keys;
  89. } else {
  90. this._cryptoKeyRing[this._currentKeyIndex] = keys;
  91. }
  92. this._sendCount = BigInt(0); // eslint-disable-line new-cap
  93. }
  94. /**
  95. * Sets the public or private key used to sign or verify frames.
  96. * @param {CryptoKey} public or private CryptoKey object.
  97. * @param {Object} signature options. Will be passed to sign/verify and need to specify byteLength of the signature.
  98. * Defaults to ECDSA with SHA-256 and a byteLength of 132.
  99. */
  100. setSignatureKey(key, options = {
  101. name: 'ECDSA',
  102. hash: { name: 'SHA-256' },
  103. byteLength: 132 // Length of the signature.
  104. }) {
  105. this._signatureKey = key;
  106. this._signatureOptions = options;
  107. }
  108. /**
  109. * Decide whether we should sign a frame.
  110. * @returns {boolean}
  111. * @private
  112. */
  113. _shouldSignFrame() {
  114. if (!this._signatureKey) {
  115. return false;
  116. }
  117. return true;
  118. }
  119. /**
  120. * Function that will be injected in a stream and will encrypt the given encoded frames.
  121. *
  122. * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.
  123. * @param {TransformStreamDefaultController} controller - TransportStreamController.
  124. *
  125. * The packet format is a variant of
  126. * https://tools.ietf.org/html/draft-omara-sframe-00
  127. * using a trailer instead of a header. One of the design goals was to not require
  128. * changes to the SFU which for video requires not encrypting the keyframe bit of VP8
  129. * as SFUs need to detect a keyframe (framemarking or the generic frame descriptor will
  130. * solve this eventually). This also "hides" that a client is using E2EE a bit.
  131. *
  132. * Note that this operates on the full frame, i.e. for VP8 the data described in
  133. * https://tools.ietf.org/html/rfc6386#section-9.1
  134. *
  135. * The VP8 payload descriptor described in
  136. * https://tools.ietf.org/html/rfc7741#section-4.2
  137. * is part of the RTP packet and not part of the encoded frame and is therefore not
  138. * controllable by us. This is fine as the SFU keeps having access to it for routing.
  139. */
  140. encodeFunction(encodedFrame, controller) {
  141. const keyIndex = this._currentKeyIndex;
  142. if (this._cryptoKeyRing[keyIndex]) {
  143. this._sendCount++;
  144. // Thіs is not encrypted and contains the VP8 payload descriptor or the Opus TOC byte.
  145. const frameHeader = new Uint8Array(encodedFrame.data, 0, UNENCRYPTED_BYTES[encodedFrame.type]);
  146. // Construct frame trailer. Similar to the frame header described in
  147. // https://tools.ietf.org/html/draft-omara-sframe-00#section-4.2
  148. // but we put it at the end.
  149. // 0 1 2 3 4 5 6 7
  150. // ---------+---------------------------------+-+-+-+-+-+-+-+-+
  151. // payload | CTR... (length=LEN) |S|LEN |KID |
  152. // ---------+---------------------------------+-+-+-+-+-+-+-+-+
  153. const counter = new Uint8Array(16);
  154. const counterView = new DataView(counter.buffer);
  155. // The counter is encoded as a variable-length field.
  156. counterView.setBigUint64(8, this._sendCount);
  157. let counterLength = 8;
  158. for (let i = 8; i < counter.byteLength; i++ && counterLength--) {
  159. if (counterView.getUint8(i) !== 0) {
  160. break;
  161. }
  162. }
  163. // If a signature is included, the S bit is set and a fixed number
  164. // of bytes (depending on the signature algorithm) is inserted between
  165. // CTR and the trailing byte.
  166. const signatureLength = this._shouldSignFrame(encodedFrame) ? this._signatureOptions.byteLength : 0;
  167. const frameTrailer = new Uint8Array(counterLength + signatureLength + 1);
  168. frameTrailer.set(new Uint8Array(counter.buffer, counter.byteLength - counterLength));
  169. // Since we never send a counter of 0 we send counterLength - 1 on the wire.
  170. // This is different from the sframe draft, increases the key space and lets us
  171. // ignore the case of a zero-length counter at the receiver.
  172. frameTrailer[frameTrailer.byteLength - 1] = keyIndex | ((counterLength - 1) << 4);
  173. if (signatureLength) {
  174. frameTrailer[frameTrailer.byteLength - 1] |= 0x80; // set the signature bit.
  175. }
  176. // XOR the counter with the saltKey to construct the AES CTR.
  177. const saltKey = new DataView(this._cryptoKeyRing[keyIndex].saltKey);
  178. for (let i = 0; i < counter.byteLength; i++) {
  179. counterView.setUint8(i, counterView.getUint8(i) ^ saltKey.getUint8(i));
  180. }
  181. return crypto.subtle.encrypt({
  182. name: ENCRYPTION_ALGORITHM,
  183. counter,
  184. length: CTR_LENGTH
  185. }, this._cryptoKeyRing[keyIndex].encryptionKey, new Uint8Array(encodedFrame.data,
  186. UNENCRYPTED_BYTES[encodedFrame.type]))
  187. .then(cipherText => {
  188. const newData = new ArrayBuffer(frameHeader.byteLength + cipherText.byteLength
  189. + DIGEST_LENGTH[encodedFrame.type] + frameTrailer.byteLength);
  190. const newUint8 = new Uint8Array(newData);
  191. newUint8.set(frameHeader); // copy first bytes.
  192. newUint8.set(new Uint8Array(cipherText), UNENCRYPTED_BYTES[encodedFrame.type]); // add ciphertext.
  193. // Leave some space for the authentication tag. This is filled with 0s initially, similar to
  194. // STUN message-integrity described in https://tools.ietf.org/html/rfc5389#section-15.4
  195. newUint8.set(frameTrailer, frameHeader.byteLength + cipherText.byteLength
  196. + DIGEST_LENGTH[encodedFrame.type]); // append trailer.
  197. return crypto.subtle.sign(AUTHENTICATIONTAG_OPTIONS, this._cryptoKeyRing[keyIndex].authenticationKey,
  198. new Uint8Array(newData)).then(async authTag => {
  199. const truncatedAuthTag = new Uint8Array(authTag, 0, DIGEST_LENGTH[encodedFrame.type]);
  200. // Set the truncated authentication tag.
  201. newUint8.set(truncatedAuthTag, UNENCRYPTED_BYTES[encodedFrame.type] + cipherText.byteLength);
  202. // Sign with the long-term signature key.
  203. if (signatureLength) {
  204. const signature = await crypto.subtle.sign(this._signatureOptions,
  205. this._signatureKey, truncatedAuthTag);
  206. newUint8.set(new Uint8Array(signature), newUint8.byteLength - signature.byteLength - 1);
  207. }
  208. encodedFrame.data = newData;
  209. return controller.enqueue(encodedFrame);
  210. });
  211. }, e => {
  212. // TODO: surface this to the app.
  213. console.error(e);
  214. // We are not enqueuing the frame here on purpose.
  215. });
  216. }
  217. /* NOTE WELL:
  218. * This will send unencrypted data (only protected by DTLS transport encryption) when no key is configured.
  219. * This is ok for demo purposes but should not be done once this becomes more relied upon.
  220. */
  221. controller.enqueue(encodedFrame);
  222. }
  223. /**
  224. * Function that will be injected in a stream and will decrypt the given encoded frames.
  225. *
  226. * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.
  227. * @param {TransformStreamDefaultController} controller - TransportStreamController.
  228. */
  229. async decodeFunction(encodedFrame, controller) {
  230. const data = new Uint8Array(encodedFrame.data);
  231. const keyIndex = data[encodedFrame.data.byteLength - 1] & 0xf; // lower four bits.
  232. if (this._cryptoKeyRing[keyIndex]) {
  233. const counterLength = 1 + ((data[encodedFrame.data.byteLength - 1] >> 4) & 0x7);
  234. const signatureLength = data[encodedFrame.data.byteLength - 1] & 0x80
  235. ? this._signatureOptions.byteLength : 0;
  236. const frameHeader = new Uint8Array(encodedFrame.data, 0, UNENCRYPTED_BYTES[encodedFrame.type]);
  237. // Extract the truncated authentication tag.
  238. const authTagOffset = encodedFrame.data.byteLength - (DIGEST_LENGTH[encodedFrame.type]
  239. + counterLength + signatureLength + 1);
  240. const authTag = encodedFrame.data.slice(authTagOffset, authTagOffset
  241. + DIGEST_LENGTH[encodedFrame.type]);
  242. // Verify the long-term signature of the authentication tag.
  243. if (signatureLength) {
  244. if (this._signatureKey) {
  245. const signature = data.subarray(data.byteLength - signatureLength - 1, data.byteLength - 1);
  246. const validSignature = await crypto.subtle.verify(this._signatureOptions,
  247. this._signatureKey, signature, authTag);
  248. if (!validSignature) {
  249. // TODO: surface this to the app. We are encrypted but validation failed.
  250. console.error('Long-term signature mismatch (or no signature key)');
  251. return;
  252. }
  253. // TODO: surface this to the app. We are now encrypted and verified.
  254. } else {
  255. // TODO: surface this to the app. We are now encrypted but can not verify.
  256. }
  257. // Then set signature bytes to 0.
  258. data.set(new Uint8Array(signatureLength), encodedFrame.data.byteLength - (signatureLength + 1));
  259. }
  260. // Set authentication tag bytes to 0.
  261. data.set(new Uint8Array(DIGEST_LENGTH[encodedFrame.type]), encodedFrame.data.byteLength
  262. - (DIGEST_LENGTH[encodedFrame.type] + counterLength + signatureLength + 1));
  263. // Do truncated hash comparison of the authentication tag.
  264. // If the hash does not match we might have to advance the ratchet a limited number
  265. // of times. See (even though the description there is odd)
  266. // https://tools.ietf.org/html/draft-omara-sframe-00#section-4.3.5.1
  267. let { authenticationKey, material } = this._cryptoKeyRing[keyIndex];
  268. let validAuthTag = false;
  269. let newKeys = null;
  270. for (let distance = 0; distance < RATCHET_WINDOW_SIZE; distance++) {
  271. const calculatedTag = await crypto.subtle.sign(AUTHENTICATIONTAG_OPTIONS,
  272. authenticationKey, encodedFrame.data);
  273. if (isArrayEqual(new Uint8Array(authTag),
  274. new Uint8Array(calculatedTag.slice(0, DIGEST_LENGTH[encodedFrame.type])))) {
  275. validAuthTag = true;
  276. if (distance > 0) {
  277. this._setKeys(newKeys, keyIndex);
  278. }
  279. break;
  280. }
  281. // Attempt to ratchet and generate the next set of keys.
  282. material = await importKey(await ratchet(material));
  283. newKeys = await deriveKeys(material);
  284. authenticationKey = newKeys.authenticationKey;
  285. }
  286. // Check whether we found a valid authentication tag.
  287. if (!validAuthTag) {
  288. // TODO: return an error to the app.
  289. console.error('Authentication tag mismatch');
  290. return;
  291. }
  292. // Extract the counter.
  293. const counter = new Uint8Array(16);
  294. counter.set(data.slice(encodedFrame.data.byteLength - (counterLength + signatureLength + 1),
  295. encodedFrame.data.byteLength - (signatureLength + 1)), 16 - counterLength);
  296. const counterView = new DataView(counter.buffer);
  297. // XOR the counter with the saltKey to construct the AES CTR.
  298. const saltKey = new DataView(this._cryptoKeyRing[keyIndex].saltKey);
  299. for (let i = 0; i < counter.byteLength; i++) {
  300. counterView.setUint8(i,
  301. counterView.getUint8(i) ^ saltKey.getUint8(i));
  302. }
  303. return crypto.subtle.decrypt({
  304. name: ENCRYPTION_ALGORITHM,
  305. counter,
  306. length: CTR_LENGTH
  307. }, this._cryptoKeyRing[keyIndex].encryptionKey, new Uint8Array(encodedFrame.data,
  308. UNENCRYPTED_BYTES[encodedFrame.type],
  309. encodedFrame.data.byteLength - (UNENCRYPTED_BYTES[encodedFrame.type]
  310. + DIGEST_LENGTH[encodedFrame.type] + counterLength + signatureLength + 1))
  311. ).then(plainText => {
  312. const newData = new ArrayBuffer(UNENCRYPTED_BYTES[encodedFrame.type] + plainText.byteLength);
  313. const newUint8 = new Uint8Array(newData);
  314. newUint8.set(frameHeader);
  315. newUint8.set(new Uint8Array(plainText), UNENCRYPTED_BYTES[encodedFrame.type]);
  316. encodedFrame.data = newData;
  317. return controller.enqueue(encodedFrame);
  318. }, e => {
  319. console.error(e);
  320. // TODO: notify the application about error status.
  321. // TODO: For video we need a better strategy since we do not want to based any
  322. // non-error frames on a garbage keyframe.
  323. if (encodedFrame.type === undefined) { // audio, replace with silence.
  324. const newData = new ArrayBuffer(3);
  325. const newUint8 = new Uint8Array(newData);
  326. newUint8.set([ 0xd8, 0xff, 0xfe ]); // opus silence frame.
  327. encodedFrame.data = newData;
  328. controller.enqueue(encodedFrame);
  329. }
  330. });
  331. } else if (keyIndex >= this._cryptoKeyRing.length && this._cryptoKeyRing[this._currentKeyIndex]) {
  332. // If we are encrypting but don't have a key for the remote drop the frame.
  333. // This is a heuristic since we don't know whether a packet is encrypted,
  334. // do not have a checksum and do not have signaling for whether a remote participant does
  335. // encrypt or not.
  336. return;
  337. }
  338. // TODO: this just passes through to the decoder. Is that ok? If we don't know the key yet
  339. // we might want to buffer a bit but it is still unclear how to do that (and for how long etc).
  340. controller.enqueue(encodedFrame);
  341. }
  342. }