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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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._initialized = false;
  28. this._key = undefined;
  29. this._enabling = undefined;
  30. this._e2eeCtx = new E2EEContext();
  31. this._olmAdapter = new OlmAdapter(conference);
  32. // Debounce key rotation / ratcheting to avoid a storm of messages.
  33. this._ratchetKey = debounce(this._ratchetKeyImpl, DEBOUNCE_PERIOD);
  34. this._rotateKey = debounce(this._rotateKeyImpl, DEBOUNCE_PERIOD);
  35. // Participant join / leave operations. Used for key advancement / rotation.
  36. //
  37. this.conference.on(
  38. JitsiConferenceEvents.CONFERENCE_JOINED,
  39. () => {
  40. this._conferenceJoined = true;
  41. });
  42. this.conference.on(
  43. JitsiConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  44. this._onParticipantPropertyChanged.bind(this));
  45. this.conference.on(
  46. JitsiConferenceEvents.USER_JOINED,
  47. this._onParticipantJoined.bind(this));
  48. this.conference.on(
  49. JitsiConferenceEvents.USER_LEFT,
  50. this._onParticipantLeft.bind(this));
  51. // Conference media events in order to attach the encryptor / decryptor.
  52. // FIXME add events to TraceablePeerConnection which will allow to see when there's new receiver or sender
  53. // added instead of shenanigans around conference track events and track muted.
  54. //
  55. this.conference.on(
  56. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  57. this._onMediaSessionStarted.bind(this));
  58. this.conference.on(
  59. JitsiConferenceEvents.TRACK_ADDED,
  60. track => track.isLocal() && this._onLocalTrackAdded(track));
  61. this.conference.rtc.on(
  62. RTCEvents.REMOTE_TRACK_ADDED,
  63. (track, tpc) => this._setupReceiverE2EEForTrack(tpc, track));
  64. this.conference.on(
  65. JitsiConferenceEvents.TRACK_MUTE_CHANGED,
  66. this._trackMuteChanged.bind(this));
  67. // Olm signalling events.
  68. this._olmAdapter.on(
  69. OlmAdapter.events.OLM_ID_KEY_READY,
  70. this._onOlmIdKeyReady.bind(this));
  71. this._olmAdapter.on(
  72. OlmAdapter.events.PARTICIPANT_E2EE_CHANNEL_READY,
  73. this._onParticipantE2EEChannelReady.bind(this));
  74. this._olmAdapter.on(
  75. OlmAdapter.events.PARTICIPANT_KEY_UPDATED,
  76. this._onParticipantKeyUpdated.bind(this));
  77. }
  78. /**
  79. * Indicates if E2EE is supported in the current platform.
  80. *
  81. * @param {object} config - Global configuration.
  82. * @returns {boolean}
  83. */
  84. static isSupported(config) {
  85. return browser.supportsInsertableStreams()
  86. && OlmAdapter.isSupported()
  87. && !(config.testing && config.testing.disableE2EE);
  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. }
  113. this.conference.setLocalParticipantProperty('e2ee.enabled', enabled);
  114. if (!this._initialized && enabled) {
  115. // Need to re-create the peerconnections in order to apply the insertable streams constraint.
  116. // TODO: this was necessary due to some audio issues when indertable streams are used
  117. // even though encryption is not performed. This should be fixed in the browser eventually.
  118. // https://bugs.chromium.org/p/chromium/issues/detail?id=1103280
  119. this.conference._restartMediaSessions();
  120. this._initialized = true;
  121. }
  122. // Generate a random key in case we are enabling.
  123. this._key = enabled ? this._generateKey() : false;
  124. // Send it to others using the E2EE olm channel.
  125. const index = await this._olmAdapter.updateKey(this._key);
  126. // Set our key so we begin encrypting.
  127. this._e2eeCtx.setKey(this.conference.myUserId(), this._key, index);
  128. this._enabling.resolve();
  129. }
  130. /**
  131. * Generates a new 256 bit random key.
  132. *
  133. * @returns {Uint8Array}
  134. * @private
  135. */
  136. _generateKey() {
  137. return window.crypto.getRandomValues(new Uint8Array(32));
  138. }
  139. /**
  140. * Setup E2EE on the new track that has been added to the conference, apply it on all the open peerconnections.
  141. * @param {JitsiLocalTrack} track - the new track that's being added to the conference.
  142. * @private
  143. */
  144. _onLocalTrackAdded(track) {
  145. for (const session of this.conference._getMediaSessions()) {
  146. this._setupSenderE2EEForTrack(session, track);
  147. }
  148. }
  149. /**
  150. * Setups E2E encryption for the new session.
  151. * @param {JingleSessionPC} session - the new media session.
  152. * @private
  153. */
  154. _onMediaSessionStarted(session) {
  155. const localTracks = this.conference.getLocalTracks();
  156. for (const track of localTracks) {
  157. this._setupSenderE2EEForTrack(session, track);
  158. }
  159. }
  160. /**
  161. * Publushes our own Olmn id key in presence.
  162. * @private
  163. */
  164. _onOlmIdKeyReady(idKey) {
  165. logger.debug(`Olm id key ready: ${idKey}`);
  166. // Publish it in presence.
  167. this.conference.setLocalParticipantProperty('e2ee.idKey', idKey);
  168. }
  169. /**
  170. * Advances (using ratcheting) the current key when a new participant joins the conference.
  171. * @private
  172. */
  173. _onParticipantJoined(id) {
  174. logger.debug(`Participant ${id} joined`);
  175. if (this._conferenceJoined && this._enabled) {
  176. this._ratchetKey();
  177. }
  178. }
  179. /**
  180. * Rotates the current key when a participant leaves the conference.
  181. * @private
  182. */
  183. _onParticipantLeft(id) {
  184. logger.debug(`Participant ${id} left`);
  185. this._e2eeCtx.cleanup(id);
  186. if (this._enabled) {
  187. this._rotateKey();
  188. }
  189. }
  190. /**
  191. * Event posted when the E2EE signalling channel has been established with the given participant.
  192. * @private
  193. */
  194. _onParticipantE2EEChannelReady(id) {
  195. logger.debug(`E2EE channel with participant ${id} is ready`);
  196. }
  197. /**
  198. * Handles an update in a participant's key.
  199. *
  200. * @param {string} id - The participant ID.
  201. * @param {Uint8Array | boolean} key - The new key for the participant.
  202. * @param {Number} index - The new key's index.
  203. * @private
  204. */
  205. _onParticipantKeyUpdated(id, key, index) {
  206. logger.debug(`Participant ${id} updated their key`);
  207. this._e2eeCtx.setKey(id, key, index);
  208. }
  209. /**
  210. * Handles an update in a participant's presence property.
  211. *
  212. * @param {JitsiParticipant} participant - The participant.
  213. * @param {string} name - The name of the property that changed.
  214. * @param {*} oldValue - The property's previous value.
  215. * @param {*} newValue - The property's new value.
  216. * @private
  217. */
  218. async _onParticipantPropertyChanged(participant, name, oldValue, newValue) {
  219. switch (name) {
  220. case 'e2ee.idKey':
  221. logger.debug(`Participant ${participant.getId()} updated their id key: ${newValue}`);
  222. break;
  223. case 'e2ee.enabled':
  224. if (!newValue && this._enabled) {
  225. this._olmAdapter.clearParticipantSession(participant);
  226. this._rotateKey();
  227. }
  228. break;
  229. }
  230. }
  231. /**
  232. * Advances the current key by using ratcheting.
  233. *
  234. * @private
  235. */
  236. async _ratchetKeyImpl() {
  237. logger.debug('Ratchetting key');
  238. const material = await importKey(this._key);
  239. const newKey = await ratchet(material);
  240. this._key = new Uint8Array(newKey);
  241. const index = this._olmAdapter.updateCurrentKey(this._key);
  242. this._e2eeCtx.setKey(this.conference.myUserId(), this._key, index);
  243. }
  244. /**
  245. * Rotates the local key. Rotating the key implies creating a new one, then distributing it
  246. * to all participants and once they all received it, start using it.
  247. *
  248. * @private
  249. */
  250. async _rotateKeyImpl() {
  251. logger.debug('Rotating key');
  252. this._key = this._generateKey();
  253. const index = await this._olmAdapter.updateKey(this._key);
  254. this._e2eeCtx.setKey(this.conference.myUserId(), this._key, index);
  255. }
  256. /**
  257. * Setup E2EE for the receiving side.
  258. *
  259. * @private
  260. */
  261. _setupReceiverE2EEForTrack(tpc, track) {
  262. if (!this._enabled) {
  263. return;
  264. }
  265. const receiver = tpc.findReceiverForTrack(track.track);
  266. if (receiver) {
  267. this._e2eeCtx.handleReceiver(receiver, track.getType(), track.getParticipantId());
  268. } else {
  269. logger.warn(`Could not handle E2EE for ${track}: receiver not found in: ${tpc}`);
  270. }
  271. }
  272. /**
  273. * Setup E2EE for the sending side.
  274. *
  275. * @param {JingleSessionPC} session - the session which sends the media produced by the track.
  276. * @param {JitsiLocalTrack} track - the local track for which e2e encoder will be configured.
  277. * @private
  278. */
  279. _setupSenderE2EEForTrack(session, track) {
  280. if (!this._enabled) {
  281. return;
  282. }
  283. const pc = session.peerconnection;
  284. const sender = pc && pc.findSenderForTrack(track.track);
  285. if (sender) {
  286. this._e2eeCtx.handleSender(sender, track.getType(), track.getParticipantId());
  287. } else {
  288. logger.warn(`Could not handle E2EE for ${track}: sender not found in ${pc}`);
  289. }
  290. }
  291. /**
  292. * Setup E2EE on the sender that is created for the unmuted local video track.
  293. * @param {JitsiLocalTrack} track - the track for which muted status has changed.
  294. * @private
  295. */
  296. _trackMuteChanged(track) {
  297. if (browser.doesVideoMuteByStreamRemove() && track.isLocal() && track.isVideoTrack() && !track.isMuted()) {
  298. for (const session of this.conference._getMediaSessions()) {
  299. this._setupSenderE2EEForTrack(session, track);
  300. }
  301. }
  302. }
  303. }