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

E2EEncryption.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. /* global __filename */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import debounce from 'lodash.debounce';
  4. import * as JitsiConferenceEvents from '../../JitsiConferenceEvents';
  5. import RTCEvents from '../../service/RTC/RTCEvents';
  6. import browser from '../browser';
  7. import Deferred from '../util/Deferred';
  8. import E2EEContext from './E2EEContext';
  9. import { OlmAdapter } from './OlmAdapter';
  10. import { importKey, ratchet } from './crypto-utils';
  11. const logger = getLogger(__filename);
  12. // Period which we'll wait before updating / rotating our keys when a participant
  13. // joins or leaves.
  14. const DEBOUNCE_PERIOD = 5000;
  15. /**
  16. * This module integrates {@link E2EEContext} with {@link JitsiConference} in order to enable E2E encryption.
  17. */
  18. export class E2EEncryption {
  19. /**
  20. * A constructor.
  21. * @param {JitsiConference} conference - The conference instance for which E2E encryption is to be enabled.
  22. */
  23. constructor(conference) {
  24. this.conference = conference;
  25. this._conferenceJoined = false;
  26. this._enabled = false;
  27. this._key = undefined;
  28. this._enabling = undefined;
  29. this._e2eeCtx = new E2EEContext();
  30. this._olmAdapter = new OlmAdapter(conference);
  31. // Debounce key rotation / ratcheting to avoid a storm of messages.
  32. this._ratchetKey = debounce(this._ratchetKeyImpl, DEBOUNCE_PERIOD);
  33. this._rotateKey = debounce(this._rotateKeyImpl, DEBOUNCE_PERIOD);
  34. // Participant join / leave operations. Used for key advancement / rotation.
  35. //
  36. this.conference.on(
  37. JitsiConferenceEvents.CONFERENCE_JOINED,
  38. () => {
  39. this._conferenceJoined = true;
  40. });
  41. this.conference.on(
  42. JitsiConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  43. this._onParticipantPropertyChanged.bind(this));
  44. this.conference.on(
  45. JitsiConferenceEvents.USER_JOINED,
  46. this._onParticipantJoined.bind(this));
  47. this.conference.on(
  48. JitsiConferenceEvents.USER_LEFT,
  49. this._onParticipantLeft.bind(this));
  50. // Conference media events in order to attach the encryptor / decryptor.
  51. // FIXME add events to TraceablePeerConnection which will allow to see when there's new receiver or sender
  52. // added instead of shenanigans around conference track events and track muted.
  53. //
  54. this.conference.on(
  55. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  56. this._onMediaSessionStarted.bind(this));
  57. this.conference.on(
  58. JitsiConferenceEvents.TRACK_ADDED,
  59. track => track.isLocal() && this._onLocalTrackAdded(track));
  60. this.conference.rtc.on(
  61. RTCEvents.REMOTE_TRACK_ADDED,
  62. (track, tpc) => this._setupReceiverE2EEForTrack(tpc, track));
  63. this.conference.on(
  64. JitsiConferenceEvents.TRACK_MUTE_CHANGED,
  65. this._trackMuteChanged.bind(this));
  66. // Olm signalling events.
  67. this._olmAdapter.on(
  68. OlmAdapter.events.OLM_ID_KEY_READY,
  69. this._onOlmIdKeyReady.bind(this));
  70. this._olmAdapter.on(
  71. OlmAdapter.events.PARTICIPANT_E2EE_CHANNEL_READY,
  72. this._onParticipantE2EEChannelReady.bind(this));
  73. this._olmAdapter.on(
  74. OlmAdapter.events.PARTICIPANT_KEY_UPDATED,
  75. this._onParticipantKeyUpdated.bind(this));
  76. }
  77. /**
  78. * Indicates if E2EE is supported in the current platform.
  79. *
  80. * @param {object} config - Global configuration.
  81. * @returns {boolean}
  82. */
  83. static isSupported(config) {
  84. return !(config.testing && config.testing.disableE2EE)
  85. && (browser.supportsInsertableStreams()
  86. || (config.enableEncodedTransformSupport && browser.supportsEncodedTransform()))
  87. && OlmAdapter.isSupported();
  88. }
  89. /**
  90. * Indicates whether E2EE is currently enabled or not.
  91. *
  92. * @returns {boolean}
  93. */
  94. isEnabled() {
  95. return this._enabled;
  96. }
  97. /**
  98. * Enables / disables End-To-End encryption.
  99. *
  100. * @param {boolean} enabled - whether E2EE should be enabled or not.
  101. * @returns {void}
  102. */
  103. async setEnabled(enabled) {
  104. if (enabled === this._enabled) {
  105. return;
  106. }
  107. this._enabling && await this._enabling;
  108. this._enabling = new Deferred();
  109. this._enabled = enabled;
  110. if (enabled) {
  111. await this._olmAdapter.initSessions();
  112. } else {
  113. for (const participant of this.conference.getParticipants()) {
  114. this._e2eeCtx.cleanup(participant.getId());
  115. }
  116. this._olmAdapter.clearAllParticipantsSessions();
  117. }
  118. this.conference.setLocalParticipantProperty('e2ee.enabled', enabled);
  119. this.conference._restartMediaSessions();
  120. // Generate a random key in case we are enabling.
  121. this._key = enabled ? this._generateKey() : false;
  122. // Send it to others using the E2EE olm channel.
  123. const index = await this._olmAdapter.updateKey(this._key);
  124. // Set our key so we begin encrypting.
  125. this._e2eeCtx.setKey(this.conference.myUserId(), this._key, index);
  126. this._enabling.resolve();
  127. }
  128. /**
  129. * Generates a new 256 bit random key.
  130. *
  131. * @returns {Uint8Array}
  132. * @private
  133. */
  134. _generateKey() {
  135. return window.crypto.getRandomValues(new Uint8Array(32));
  136. }
  137. /**
  138. * Setup E2EE on the new track that has been added to the conference, apply it on all the open peerconnections.
  139. * @param {JitsiLocalTrack} track - the new track that's being added to the conference.
  140. * @private
  141. */
  142. _onLocalTrackAdded(track) {
  143. for (const session of this.conference._getMediaSessions()) {
  144. this._setupSenderE2EEForTrack(session, track);
  145. }
  146. }
  147. /**
  148. * Setups E2E encryption for the new session.
  149. * @param {JingleSessionPC} session - the new media session.
  150. * @private
  151. */
  152. _onMediaSessionStarted(session) {
  153. const localTracks = this.conference.getLocalTracks();
  154. for (const track of localTracks) {
  155. this._setupSenderE2EEForTrack(session, track);
  156. }
  157. }
  158. /**
  159. * Publushes our own Olmn id key in presence.
  160. * @private
  161. */
  162. _onOlmIdKeyReady(idKey) {
  163. logger.debug(`Olm id key ready: ${idKey}`);
  164. // Publish it in presence.
  165. this.conference.setLocalParticipantProperty('e2ee.idKey', idKey);
  166. }
  167. /**
  168. * Advances (using ratcheting) the current key when a new participant joins the conference.
  169. * @private
  170. */
  171. _onParticipantJoined() {
  172. if (this._conferenceJoined && this._enabled) {
  173. this._ratchetKey();
  174. }
  175. }
  176. /**
  177. * Rotates the current key when a participant leaves the conference.
  178. * @private
  179. */
  180. _onParticipantLeft(id) {
  181. this._e2eeCtx.cleanup(id);
  182. if (this._enabled) {
  183. this._rotateKey();
  184. }
  185. }
  186. /**
  187. * Event posted when the E2EE signalling channel has been established with the given participant.
  188. * @private
  189. */
  190. _onParticipantE2EEChannelReady(id) {
  191. logger.debug(`E2EE channel with participant ${id} is ready`);
  192. }
  193. /**
  194. * Handles an update in a participant's key.
  195. *
  196. * @param {string} id - The participant ID.
  197. * @param {Uint8Array | boolean} key - The new key for the participant.
  198. * @param {Number} index - The new key's index.
  199. * @private
  200. */
  201. _onParticipantKeyUpdated(id, key, index) {
  202. logger.debug(`Participant ${id} updated their key`);
  203. this._e2eeCtx.setKey(id, key, index);
  204. }
  205. /**
  206. * Handles an update in a participant's presence property.
  207. *
  208. * @param {JitsiParticipant} participant - The participant.
  209. * @param {string} name - The name of the property that changed.
  210. * @param {*} oldValue - The property's previous value.
  211. * @param {*} newValue - The property's new value.
  212. * @private
  213. */
  214. async _onParticipantPropertyChanged(participant, name, oldValue, newValue) {
  215. switch (name) {
  216. case 'e2ee.idKey':
  217. logger.debug(`Participant ${participant.getId()} updated their id key: ${newValue}`);
  218. break;
  219. case 'e2ee.enabled':
  220. if (!newValue && this._enabled) {
  221. this._olmAdapter.clearParticipantSession(participant);
  222. this._rotateKey();
  223. }
  224. break;
  225. }
  226. }
  227. /**
  228. * Advances the current key by using ratcheting.
  229. *
  230. * @private
  231. */
  232. async _ratchetKeyImpl() {
  233. logger.debug('Ratchetting key');
  234. const material = await importKey(this._key);
  235. const newKey = await ratchet(material);
  236. this._key = new Uint8Array(newKey);
  237. const index = this._olmAdapter.updateCurrentKey(this._key);
  238. this._e2eeCtx.setKey(this.conference.myUserId(), this._key, index);
  239. }
  240. /**
  241. * Rotates the local key. Rotating the key implies creating a new one, then distributing it
  242. * to all participants and once they all received it, start using it.
  243. *
  244. * @private
  245. */
  246. async _rotateKeyImpl() {
  247. logger.debug('Rotating key');
  248. this._key = this._generateKey();
  249. const index = await this._olmAdapter.updateKey(this._key);
  250. this._e2eeCtx.setKey(this.conference.myUserId(), this._key, index);
  251. }
  252. /**
  253. * Setup E2EE for the receiving side.
  254. *
  255. * @private
  256. */
  257. _setupReceiverE2EEForTrack(tpc, track) {
  258. if (!this._enabled) {
  259. return;
  260. }
  261. const receiver = tpc.findReceiverForTrack(track.track);
  262. if (receiver) {
  263. this._e2eeCtx.handleReceiver(receiver, track.getType(), track.getParticipantId());
  264. } else {
  265. logger.warn(`Could not handle E2EE for ${track}: receiver not found in: ${tpc}`);
  266. }
  267. }
  268. /**
  269. * Setup E2EE for the sending side.
  270. *
  271. * @param {JingleSessionPC} session - the session which sends the media produced by the track.
  272. * @param {JitsiLocalTrack} track - the local track for which e2e encoder will be configured.
  273. * @private
  274. */
  275. _setupSenderE2EEForTrack(session, track) {
  276. if (!this._enabled) {
  277. return;
  278. }
  279. const pc = session.peerconnection;
  280. const sender = pc && pc.findSenderForTrack(track.track);
  281. if (sender) {
  282. this._e2eeCtx.handleSender(sender, track.getType(), track.getParticipantId());
  283. } else {
  284. logger.warn(`Could not handle E2EE for ${track}: sender not found in ${pc}`);
  285. }
  286. }
  287. /**
  288. * Setup E2EE on the sender that is created for the unmuted local video track.
  289. * @param {JitsiLocalTrack} track - the track for which muted status has changed.
  290. * @private
  291. */
  292. _trackMuteChanged(track) {
  293. if (browser.doesVideoMuteByStreamRemove() && track.isLocal() && track.isVideoTrack() && !track.isMuted()) {
  294. for (const session of this.conference._getMediaSessions()) {
  295. this._setupSenderE2EEForTrack(session, track);
  296. }
  297. }
  298. }
  299. }