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.

Context.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. * @param {Number} keyIndex optional
  82. * @private
  83. */
  84. _setKeys(keys, keyIndex = -1) {
  85. if (keyIndex >= 0) {
  86. this._cryptoKeyRing[keyIndex] = keys;
  87. } else {
  88. this._cryptoKeyRing[this._currentKeyIndex] = keys;
  89. }
  90. this._sendCount = BigInt(0); // eslint-disable-line new-cap
  91. }
  92. /**
  93. * Function that will be injected in a stream and will encrypt the given encoded frames.
  94. *
  95. * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.
  96. * @param {TransformStreamDefaultController} controller - TransportStreamController.
  97. *
  98. * The packet format is a variant of
  99. * https://tools.ietf.org/html/draft-omara-sframe-00
  100. * using a trailer instead of a header. One of the design goals was to not require
  101. * changes to the SFU which for video requires not encrypting the keyframe bit of VP8
  102. * as SFUs need to detect a keyframe (framemarking or the generic frame descriptor will
  103. * solve this eventually). This also "hides" that a client is using E2EE a bit.
  104. *
  105. * Note that this operates on the full frame, i.e. for VP8 the data described in
  106. * https://tools.ietf.org/html/rfc6386#section-9.1
  107. *
  108. * The VP8 payload descriptor described in
  109. * https://tools.ietf.org/html/rfc7741#section-4.2
  110. * is part of the RTP packet and not part of the encoded frame and is therefore not
  111. * controllable by us. This is fine as the SFU keeps having access to it for routing.
  112. */
  113. encodeFunction(encodedFrame, controller) {
  114. const keyIndex = this._currentKeyIndex;
  115. if (this._cryptoKeyRing[keyIndex]) {
  116. this._sendCount++;
  117. // Thіs is not encrypted and contains the VP8 payload descriptor or the Opus TOC byte.
  118. const frameHeader = new Uint8Array(encodedFrame.data, 0, UNENCRYPTED_BYTES[encodedFrame.type]);
  119. // Construct frame trailer. Similar to the frame header described in
  120. // https://tools.ietf.org/html/draft-omara-sframe-00#section-4.2
  121. // but we put it at the end.
  122. // 0 1 2 3 4 5 6 7
  123. // ---------+---------------------------------+-+-+-+-+-+-+-+-+
  124. // payload | CTR... (length=LEN) |S|LEN |KID |
  125. // ---------+---------------------------------+-+-+-+-+-+-+-+-+
  126. const counter = new Uint8Array(16);
  127. const counterView = new DataView(counter.buffer);
  128. // The counter is encoded as a variable-length field.
  129. counterView.setBigUint64(8, this._sendCount);
  130. let counterLength = 8;
  131. for (let i = 8; i < counter.byteLength; i++ && counterLength--) {
  132. if (counterView.getUint8(i) !== 0) {
  133. break;
  134. }
  135. }
  136. const frameTrailer = new Uint8Array(counterLength + 1);
  137. frameTrailer.set(new Uint8Array(counter.buffer, counter.byteLength - counterLength));
  138. // Since we never send a counter of 0 we send counterLength - 1 on the wire.
  139. // This is different from the sframe draft, increases the key space and lets us
  140. // ignore the case of a zero-length counter at the receiver.
  141. frameTrailer[frameTrailer.byteLength - 1] = keyIndex | ((counterLength - 1) << 4);
  142. // XOR the counter with the saltKey to construct the AES CTR.
  143. const saltKey = new DataView(this._cryptoKeyRing[keyIndex].saltKey);
  144. for (let i = 0; i < counter.byteLength; i++) {
  145. counterView.setUint8(i, counterView.getUint8(i) ^ saltKey.getUint8(i));
  146. }
  147. return crypto.subtle.encrypt({
  148. name: ENCRYPTION_ALGORITHM,
  149. counter,
  150. length: CTR_LENGTH
  151. }, this._cryptoKeyRing[keyIndex].encryptionKey, new Uint8Array(encodedFrame.data,
  152. UNENCRYPTED_BYTES[encodedFrame.type]))
  153. .then(cipherText => {
  154. const newData = new ArrayBuffer(frameHeader.byteLength + cipherText.byteLength
  155. + DIGEST_LENGTH[encodedFrame.type] + frameTrailer.byteLength);
  156. const newUint8 = new Uint8Array(newData);
  157. newUint8.set(frameHeader); // copy first bytes.
  158. newUint8.set(new Uint8Array(cipherText), UNENCRYPTED_BYTES[encodedFrame.type]); // add ciphertext.
  159. // Leave some space for the authentication tag. This is filled with 0s initially, similar to
  160. // STUN message-integrity described in https://tools.ietf.org/html/rfc5389#section-15.4
  161. newUint8.set(frameTrailer, frameHeader.byteLength + cipherText.byteLength
  162. + DIGEST_LENGTH[encodedFrame.type]); // append trailer.
  163. return crypto.subtle.sign(AUTHENTICATIONTAG_OPTIONS, this._cryptoKeyRing[keyIndex].authenticationKey,
  164. new Uint8Array(newData)).then(async authTag => {
  165. const truncatedAuthTag = new Uint8Array(authTag, 0, DIGEST_LENGTH[encodedFrame.type]);
  166. // Set the truncated authentication tag.
  167. newUint8.set(truncatedAuthTag, UNENCRYPTED_BYTES[encodedFrame.type] + cipherText.byteLength);
  168. encodedFrame.data = newData;
  169. return controller.enqueue(encodedFrame);
  170. });
  171. }, e => {
  172. // TODO: surface this to the app.
  173. console.error(e);
  174. // We are not enqueuing the frame here on purpose.
  175. });
  176. }
  177. /* NOTE WELL:
  178. * This will send unencrypted data (only protected by DTLS transport encryption) when no key is configured.
  179. * This is ok for demo purposes but should not be done once this becomes more relied upon.
  180. */
  181. controller.enqueue(encodedFrame);
  182. }
  183. /**
  184. * Function that will be injected in a stream and will decrypt the given encoded frames.
  185. *
  186. * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.
  187. * @param {TransformStreamDefaultController} controller - TransportStreamController.
  188. */
  189. async decodeFunction(encodedFrame, controller) {
  190. const data = new Uint8Array(encodedFrame.data);
  191. const keyIndex = data[encodedFrame.data.byteLength - 1] & 0xf; // lower four bits.
  192. if (this._cryptoKeyRing[this._currentKeyIndex] && this._cryptoKeyRing[keyIndex]) {
  193. const counterLength = 1 + ((data[encodedFrame.data.byteLength - 1] >> 4) & 0x7);
  194. const frameHeader = new Uint8Array(encodedFrame.data, 0, UNENCRYPTED_BYTES[encodedFrame.type]);
  195. // Extract the truncated authentication tag.
  196. const authTagOffset = encodedFrame.data.byteLength - (DIGEST_LENGTH[encodedFrame.type]
  197. + counterLength + 1);
  198. const authTag = encodedFrame.data.slice(authTagOffset, authTagOffset
  199. + DIGEST_LENGTH[encodedFrame.type]);
  200. // Set authentication tag bytes to 0.
  201. data.set(new Uint8Array(DIGEST_LENGTH[encodedFrame.type]), encodedFrame.data.byteLength
  202. - (DIGEST_LENGTH[encodedFrame.type] + counterLength + 1));
  203. // Do truncated hash comparison of the authentication tag.
  204. // If the hash does not match we might have to advance the ratchet a limited number
  205. // of times. See (even though the description there is odd)
  206. // https://tools.ietf.org/html/draft-omara-sframe-00#section-4.3.5.1
  207. let { authenticationKey, material } = this._cryptoKeyRing[keyIndex];
  208. let validAuthTag = false;
  209. let newKeys = null;
  210. for (let distance = 0; distance < RATCHET_WINDOW_SIZE; distance++) {
  211. const calculatedTag = await crypto.subtle.sign(AUTHENTICATIONTAG_OPTIONS,
  212. authenticationKey, encodedFrame.data);
  213. if (isArrayEqual(new Uint8Array(authTag),
  214. new Uint8Array(calculatedTag.slice(0, DIGEST_LENGTH[encodedFrame.type])))) {
  215. validAuthTag = true;
  216. if (distance > 0) {
  217. this._setKeys(newKeys, keyIndex);
  218. }
  219. break;
  220. }
  221. // Attempt to ratchet and generate the next set of keys.
  222. material = await importKey(await ratchet(material));
  223. newKeys = await deriveKeys(material);
  224. authenticationKey = newKeys.authenticationKey;
  225. }
  226. // Check whether we found a valid authentication tag.
  227. if (!validAuthTag) {
  228. // TODO: return an error to the app.
  229. console.error('Authentication tag mismatch');
  230. return;
  231. }
  232. // Extract the counter.
  233. const counter = new Uint8Array(16);
  234. counter.set(data.slice(encodedFrame.data.byteLength - (counterLength + 1),
  235. encodedFrame.data.byteLength - 1), 16 - counterLength);
  236. const counterView = new DataView(counter.buffer);
  237. // XOR the counter with the saltKey to construct the AES CTR.
  238. const saltKey = new DataView(this._cryptoKeyRing[keyIndex].saltKey);
  239. for (let i = 0; i < counter.byteLength; i++) {
  240. counterView.setUint8(i,
  241. counterView.getUint8(i) ^ saltKey.getUint8(i));
  242. }
  243. return crypto.subtle.decrypt({
  244. name: ENCRYPTION_ALGORITHM,
  245. counter,
  246. length: CTR_LENGTH
  247. }, this._cryptoKeyRing[keyIndex].encryptionKey, new Uint8Array(encodedFrame.data,
  248. UNENCRYPTED_BYTES[encodedFrame.type],
  249. encodedFrame.data.byteLength - (UNENCRYPTED_BYTES[encodedFrame.type]
  250. + DIGEST_LENGTH[encodedFrame.type] + counterLength + 1))
  251. ).then(plainText => {
  252. const newData = new ArrayBuffer(UNENCRYPTED_BYTES[encodedFrame.type] + plainText.byteLength);
  253. const newUint8 = new Uint8Array(newData);
  254. newUint8.set(frameHeader);
  255. newUint8.set(new Uint8Array(plainText), UNENCRYPTED_BYTES[encodedFrame.type]);
  256. encodedFrame.data = newData;
  257. return controller.enqueue(encodedFrame);
  258. }, e => {
  259. console.error(e);
  260. // TODO: notify the application about error status.
  261. // TODO: For video we need a better strategy since we do not want to based any
  262. // non-error frames on a garbage keyframe.
  263. if (encodedFrame.type === undefined) { // audio, replace with silence.
  264. const newData = new ArrayBuffer(3);
  265. const newUint8 = new Uint8Array(newData);
  266. newUint8.set([ 0xd8, 0xff, 0xfe ]); // opus silence frame.
  267. encodedFrame.data = newData;
  268. controller.enqueue(encodedFrame);
  269. }
  270. });
  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. }