選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Context.js 14KB

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