Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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