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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. /* global Olm */
  2. import { getLogger } from '@jitsi/logger';
  3. import base64js from 'base64-js';
  4. import isEqual from 'lodash.isequal';
  5. import { v4 as uuidv4 } from 'uuid';
  6. import * as JitsiConferenceEvents from '../../JitsiConferenceEvents';
  7. import Deferred from '../util/Deferred';
  8. import Listenable from '../util/Listenable';
  9. import { FEATURE_E2EE, JITSI_MEET_MUC_TYPE } from '../xmpp/xmpp';
  10. const logger = getLogger(__filename);
  11. const REQ_TIMEOUT = 5 * 1000;
  12. const OLM_MESSAGE_TYPE = 'olm';
  13. const OLM_MESSAGE_TYPES = {
  14. ERROR: 'error',
  15. KEY_INFO: 'key-info',
  16. KEY_INFO_ACK: 'key-info-ack',
  17. SESSION_ACK: 'session-ack',
  18. SESSION_INIT: 'session-init'
  19. };
  20. const kOlmData = Symbol('OlmData');
  21. const OlmAdapterEvents = {
  22. OLM_ID_KEY_READY: 'olm.id_key_ready',
  23. PARTICIPANT_E2EE_CHANNEL_READY: 'olm.participant_e2ee_channel_ready',
  24. PARTICIPANT_KEY_UPDATED: 'olm.partitipant_key_updated'
  25. };
  26. /**
  27. * This class implements an End-to-End Encrypted communication channel between every two peers
  28. * in the conference. This channel uses libolm to achieve E2EE.
  29. *
  30. * The created channel is then used to exchange the secret key that each participant will use
  31. * to encrypt the actual media (see {@link E2EEContext}).
  32. *
  33. * A simple JSON message based protocol is implemented, which follows a request - response model:
  34. * - session-init: Initiates an olm session establishment procedure. This message will be sent
  35. * by the participant who just joined, to everyone else.
  36. * - session-ack: Completes the olm session etablishment. This messsage may contain ancilliary
  37. * encrypted data, more specifically the sender's current key.
  38. * - key-info: Includes the sender's most up to date key information.
  39. * - key-info-ack: Acknowledges the reception of a key-info request. In addition, it may contain
  40. * the sender's key information, if available.
  41. * - error: Indicates a request processing error has occurred.
  42. *
  43. * These requessts and responses are transport independent. Currently they are sent using XMPP
  44. * MUC private messages.
  45. */
  46. export class OlmAdapter extends Listenable {
  47. /**
  48. * Creates an adapter instance for the given conference.
  49. */
  50. constructor(conference) {
  51. super();
  52. this._conf = conference;
  53. this._init = new Deferred();
  54. this._key = undefined;
  55. this._keyIndex = -1;
  56. this._reqs = new Map();
  57. this._sessionInitialization = undefined;
  58. if (OlmAdapter.isSupported()) {
  59. this._bootstrapOlm();
  60. this._conf.on(JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED, this._onEndpointMessageReceived.bind(this));
  61. this._conf.on(JitsiConferenceEvents.CONFERENCE_LEFT, this._onConferenceLeft.bind(this));
  62. this._conf.on(JitsiConferenceEvents.USER_LEFT, this._onParticipantLeft.bind(this));
  63. this._conf.on(JitsiConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  64. this._onParticipantPropertyChanged.bind(this));
  65. } else {
  66. this._init.reject(new Error('Olm not supported'));
  67. }
  68. }
  69. /**
  70. * Starts new olm sessions with every other participant that has the participantId "smaller" the localParticipantId.
  71. */
  72. async initSessions() {
  73. if (this._sessionInitialization) {
  74. throw new Error('OlmAdapter initSessions called multiple times');
  75. } else {
  76. this._sessionInitialization = new Deferred();
  77. await this._init;
  78. const promises = [];
  79. const localParticipantId = this._conf.myUserId();
  80. for (const participant of this._conf.getParticipants()) {
  81. if (participant.hasFeature(FEATURE_E2EE) && localParticipantId < participant.getId()) {
  82. promises.push(this._sendSessionInit(participant));
  83. }
  84. }
  85. await Promise.allSettled(promises);
  86. // TODO: retry failed ones.
  87. this._sessionInitialization.resolve();
  88. this._sessionInitialization = undefined;
  89. }
  90. }
  91. /**
  92. * Indicates if olm is supported on the current platform.
  93. *
  94. * @returns {boolean}
  95. */
  96. static isSupported() {
  97. return typeof window.Olm !== 'undefined';
  98. }
  99. /**
  100. * Updates the current participant key and distributes it to all participants in the conference
  101. * by sending a key-info message.
  102. *
  103. * @param {Uint8Array|boolean} key - The new key.
  104. * @retrns {Promise<Number>}
  105. */
  106. async updateKey(key) {
  107. // Store it locally for new sessions.
  108. this._key = key;
  109. this._keyIndex++;
  110. // Broadcast it.
  111. const promises = [];
  112. for (const participant of this._conf.getParticipants()) {
  113. const pId = participant.getId();
  114. const olmData = this._getParticipantOlmData(participant);
  115. // TODO: skip those who don't support E2EE.
  116. if (!olmData.session) {
  117. logger.warn(`Tried to send key to participant ${pId} but we have no session`);
  118. // eslint-disable-next-line no-continue
  119. continue;
  120. }
  121. const uuid = uuidv4();
  122. const data = {
  123. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  124. olm: {
  125. type: OLM_MESSAGE_TYPES.KEY_INFO,
  126. data: {
  127. ciphertext: this._encryptKeyInfo(olmData.session),
  128. uuid
  129. }
  130. }
  131. };
  132. const d = new Deferred();
  133. d.setRejectTimeout(REQ_TIMEOUT);
  134. d.catch(() => {
  135. this._reqs.delete(uuid);
  136. });
  137. this._reqs.set(uuid, d);
  138. promises.push(d);
  139. this._sendMessage(data, pId);
  140. }
  141. await Promise.allSettled(promises);
  142. // TODO: retry failed ones?
  143. return this._keyIndex;
  144. }
  145. /**
  146. * Updates the current participant key.
  147. * @param {Uint8Array|boolean} key - The new key.
  148. * @returns {number}
  149. */
  150. updateCurrentKey(key) {
  151. this._key = key;
  152. return this._keyIndex;
  153. }
  154. /**
  155. * Frees the olmData session for the given participant.
  156. *
  157. */
  158. clearParticipantSession(participant) {
  159. const olmData = this._getParticipantOlmData(participant);
  160. if (olmData.session) {
  161. olmData.session.free();
  162. olmData.session = undefined;
  163. }
  164. }
  165. /**
  166. * Frees the olmData sessions for all participants.
  167. *
  168. */
  169. clearAllParticipantsSessions() {
  170. for (const participant of this._conf.getParticipants()) {
  171. this.clearParticipantSession(participant);
  172. }
  173. }
  174. /**
  175. * Internal helper to bootstrap the olm library.
  176. *
  177. * @returns {Promise<void>}
  178. * @private
  179. */
  180. async _bootstrapOlm() {
  181. logger.debug('Initializing Olm...');
  182. try {
  183. await Olm.init();
  184. this._olmAccount = new Olm.Account();
  185. this._olmAccount.create();
  186. const idKeys = JSON.parse(this._olmAccount.identity_keys());
  187. this._idKey = idKeys.curve25519;
  188. logger.debug(`Olm ${Olm.get_library_version().join('.')} initialized`);
  189. this._init.resolve();
  190. this._onIdKeyReady(this._idKey);
  191. } catch (e) {
  192. logger.error('Failed to initialize Olm', e);
  193. this._init.reject(e);
  194. }
  195. }
  196. /**
  197. * Publishes our own Olmn id key in presence.
  198. * @private
  199. */
  200. _onIdKeyReady(idKey) {
  201. logger.debug(`Olm id key ready: ${idKey}`);
  202. // Publish it in presence.
  203. this._conf.setLocalParticipantProperty('e2ee.idKey', idKey);
  204. }
  205. /**
  206. * Event posted when the E2EE signalling channel has been established with the given participant.
  207. * @private
  208. */
  209. _onParticipantE2EEChannelReady(id) {
  210. logger.debug(`E2EE channel with participant ${id} is ready`);
  211. }
  212. /**
  213. * Internal helper for encrypting the current key information for a given participant.
  214. *
  215. * @param {Olm.Session} session - Participant's session.
  216. * @returns {string} - The encrypted text with the key information.
  217. * @private
  218. */
  219. _encryptKeyInfo(session) {
  220. const keyInfo = {};
  221. if (this._key !== undefined) {
  222. keyInfo.key = this._key ? base64js.fromByteArray(this._key) : false;
  223. keyInfo.keyIndex = this._keyIndex;
  224. }
  225. return session.encrypt(JSON.stringify(keyInfo));
  226. }
  227. /**
  228. * Internal helper for getting the olm related data associated with a participant.
  229. *
  230. * @param {JitsiParticipant} participant - Participant whose data wants to be extracted.
  231. * @returns {Object}
  232. * @private
  233. */
  234. _getParticipantOlmData(participant) {
  235. participant[kOlmData] = participant[kOlmData] || {};
  236. return participant[kOlmData];
  237. }
  238. /**
  239. * Handles leaving the conference, cleaning up olm sessions.
  240. *
  241. * @private
  242. */
  243. async _onConferenceLeft() {
  244. logger.debug('Conference left');
  245. await this._init;
  246. for (const participant of this._conf.getParticipants()) {
  247. this._onParticipantLeft(participant.getId(), participant);
  248. }
  249. if (this._olmAccount) {
  250. this._olmAccount.free();
  251. this._olmAccount = undefined;
  252. }
  253. }
  254. /**
  255. * Main message handler. Handles 1-to-1 messages received from other participants
  256. * and send the appropriate replies.
  257. *
  258. * @private
  259. */
  260. async _onEndpointMessageReceived(participant, payload) {
  261. if (payload[JITSI_MEET_MUC_TYPE] !== OLM_MESSAGE_TYPE) {
  262. return;
  263. }
  264. if (!payload.olm) {
  265. logger.warn('Incorrectly formatted message');
  266. return;
  267. }
  268. await this._init;
  269. const msg = payload.olm;
  270. const pId = participant.getId();
  271. const olmData = this._getParticipantOlmData(participant);
  272. switch (msg.type) {
  273. case OLM_MESSAGE_TYPES.SESSION_INIT: {
  274. if (olmData.session) {
  275. logger.warn(`Participant ${pId} already has a session`);
  276. this._sendError(participant, 'Session already established');
  277. } else {
  278. // Create a session for communicating with this participant.
  279. const session = new Olm.Session();
  280. session.create_outbound(this._olmAccount, msg.data.idKey, msg.data.otKey);
  281. olmData.session = session;
  282. // Send ACK
  283. const ack = {
  284. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  285. olm: {
  286. type: OLM_MESSAGE_TYPES.SESSION_ACK,
  287. data: {
  288. ciphertext: this._encryptKeyInfo(session),
  289. uuid: msg.data.uuid
  290. }
  291. }
  292. };
  293. this._sendMessage(ack, pId);
  294. this._onParticipantE2EEChannelReady(pId);
  295. }
  296. break;
  297. }
  298. case OLM_MESSAGE_TYPES.SESSION_ACK: {
  299. if (olmData.session) {
  300. logger.warn(`Participant ${pId} already has a session`);
  301. this._sendError(participant, 'No session found');
  302. } else if (msg.data.uuid === olmData.pendingSessionUuid) {
  303. const { ciphertext } = msg.data;
  304. const d = this._reqs.get(msg.data.uuid);
  305. const session = new Olm.Session();
  306. session.create_inbound(this._olmAccount, ciphertext.body);
  307. // Remove OT keys that have been used to setup this session.
  308. this._olmAccount.remove_one_time_keys(session);
  309. // Decrypt first message.
  310. const data = session.decrypt(ciphertext.type, ciphertext.body);
  311. olmData.session = session;
  312. olmData.pendingSessionUuid = undefined;
  313. this._onParticipantE2EEChannelReady(pId);
  314. this._reqs.delete(msg.data.uuid);
  315. d.resolve();
  316. const json = safeJsonParse(data);
  317. if (json.key) {
  318. const key = base64js.toByteArray(json.key);
  319. const keyIndex = json.keyIndex;
  320. olmData.lastKey = key;
  321. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_KEY_UPDATED, pId, key, keyIndex);
  322. }
  323. } else {
  324. logger.warn('Received ACK with the wrong UUID');
  325. this._sendError(participant, 'Invalid UUID');
  326. }
  327. break;
  328. }
  329. case OLM_MESSAGE_TYPES.ERROR: {
  330. logger.error(msg.data.error);
  331. break;
  332. }
  333. case OLM_MESSAGE_TYPES.KEY_INFO: {
  334. if (olmData.session) {
  335. const { ciphertext } = msg.data;
  336. const data = olmData.session.decrypt(ciphertext.type, ciphertext.body);
  337. const json = safeJsonParse(data);
  338. if (json.key !== undefined && json.keyIndex !== undefined) {
  339. const key = json.key ? base64js.toByteArray(json.key) : false;
  340. const keyIndex = json.keyIndex;
  341. if (!isEqual(olmData.lastKey, key)) {
  342. olmData.lastKey = key;
  343. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_KEY_UPDATED, pId, key, keyIndex);
  344. }
  345. // Send ACK.
  346. const ack = {
  347. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  348. olm: {
  349. type: OLM_MESSAGE_TYPES.KEY_INFO_ACK,
  350. data: {
  351. ciphertext: this._encryptKeyInfo(olmData.session),
  352. uuid: msg.data.uuid
  353. }
  354. }
  355. };
  356. this._sendMessage(ack, pId);
  357. }
  358. } else {
  359. logger.debug(`Received key info message from ${pId} but we have no session for them!`);
  360. this._sendError(participant, 'No session found while processing key-info');
  361. }
  362. break;
  363. }
  364. case OLM_MESSAGE_TYPES.KEY_INFO_ACK: {
  365. if (olmData.session) {
  366. const { ciphertext } = msg.data;
  367. const data = olmData.session.decrypt(ciphertext.type, ciphertext.body);
  368. const json = safeJsonParse(data);
  369. if (json.key !== undefined && json.keyIndex !== undefined) {
  370. const key = json.key ? base64js.toByteArray(json.key) : false;
  371. const keyIndex = json.keyIndex;
  372. if (!isEqual(olmData.lastKey, key)) {
  373. olmData.lastKey = key;
  374. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_KEY_UPDATED, pId, key, keyIndex);
  375. }
  376. }
  377. const d = this._reqs.get(msg.data.uuid);
  378. this._reqs.delete(msg.data.uuid);
  379. d.resolve();
  380. } else {
  381. logger.debug(`Received key info ack message from ${pId} but we have no session for them!`);
  382. this._sendError(participant, 'No session found while processing key-info-ack');
  383. }
  384. break;
  385. }
  386. }
  387. }
  388. /**
  389. * Handles a participant leaving. When a participant leaves their olm session is destroyed.
  390. *
  391. * @private
  392. */
  393. _onParticipantLeft(id, participant) {
  394. logger.debug(`Participant ${id} left`);
  395. this.clearParticipantSession(participant);
  396. }
  397. /**
  398. * Handles an update in a participant's presence property.
  399. *
  400. * @param {JitsiParticipant} participant - The participant.
  401. * @param {string} name - The name of the property that changed.
  402. * @param {*} oldValue - The property's previous value.
  403. * @param {*} newValue - The property's new value.
  404. * @private
  405. */
  406. async _onParticipantPropertyChanged(participant, name, oldValue, newValue) {
  407. switch (name) {
  408. case 'e2ee.enabled':
  409. if (newValue && this._conf.isE2EEEnabled()) {
  410. const localParticipantId = this._conf.myUserId();
  411. const participantId = participant.getId();
  412. const participantFeatures = await participant.getFeatures();
  413. if (participantFeatures.has(FEATURE_E2EE) && localParticipantId < participantId) {
  414. if (this._sessionInitialization) {
  415. await this._sessionInitialization;
  416. }
  417. await this._sendSessionInit(participant);
  418. const olmData = this._getParticipantOlmData(participant);
  419. const uuid = uuidv4();
  420. const data = {
  421. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  422. olm: {
  423. type: OLM_MESSAGE_TYPES.KEY_INFO,
  424. data: {
  425. ciphertext: this._encryptKeyInfo(olmData.session),
  426. uuid
  427. }
  428. }
  429. };
  430. this._sendMessage(data, participantId);
  431. }
  432. }
  433. break;
  434. }
  435. }
  436. /**
  437. * Builds and sends an error message to the target participant.
  438. *
  439. * @param {JitsiParticipant} participant - The target participant.
  440. * @param {string} error - The error message.
  441. * @returns {void}
  442. */
  443. _sendError(participant, error) {
  444. const pId = participant.getId();
  445. const err = {
  446. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  447. olm: {
  448. type: OLM_MESSAGE_TYPES.ERROR,
  449. data: {
  450. error
  451. }
  452. }
  453. };
  454. this._sendMessage(err, pId);
  455. }
  456. /**
  457. * Internal helper to send the given object to the given participant ID.
  458. * This function merely exists so the transport can be easily swapped.
  459. * Currently messages are transmitted via XMPP MUC private messages.
  460. *
  461. * @param {object} data - The data that will be sent to the target participant.
  462. * @param {string} participantId - ID of the target participant.
  463. */
  464. _sendMessage(data, participantId) {
  465. this._conf.sendMessage(data, participantId);
  466. }
  467. /**
  468. * Builds and sends the session-init request to the target participant.
  469. *
  470. * @param {JitsiParticipant} participant - Participant to whom we'll send the request.
  471. * @returns {Promise} - The promise will be resolved when the session-ack is received.
  472. * @private
  473. */
  474. _sendSessionInit(participant) {
  475. const pId = participant.getId();
  476. const olmData = this._getParticipantOlmData(participant);
  477. if (olmData.session) {
  478. logger.warn(`Tried to send session-init to ${pId} but we already have a session`);
  479. return Promise.reject();
  480. }
  481. if (olmData.pendingSessionUuid !== undefined) {
  482. logger.warn(`Tried to send session-init to ${pId} but we already have a pending session`);
  483. return Promise.reject();
  484. }
  485. // Generate a One Time Key.
  486. this._olmAccount.generate_one_time_keys(1);
  487. const otKeys = JSON.parse(this._olmAccount.one_time_keys());
  488. const otKey = Object.values(otKeys.curve25519)[0];
  489. if (!otKey) {
  490. return Promise.reject(new Error('No one-time-keys generated'));
  491. }
  492. // Mark the OT keys (one really) as published so they are not reused.
  493. this._olmAccount.mark_keys_as_published();
  494. const uuid = uuidv4();
  495. const init = {
  496. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  497. olm: {
  498. type: OLM_MESSAGE_TYPES.SESSION_INIT,
  499. data: {
  500. idKey: this._idKey,
  501. otKey,
  502. uuid
  503. }
  504. }
  505. };
  506. const d = new Deferred();
  507. d.setRejectTimeout(REQ_TIMEOUT);
  508. d.catch(() => {
  509. this._reqs.delete(uuid);
  510. olmData.pendingSessionUuid = undefined;
  511. });
  512. this._reqs.set(uuid, d);
  513. this._sendMessage(init, pId);
  514. // Store the UUID for matching with the ACK.
  515. olmData.pendingSessionUuid = uuid;
  516. return d;
  517. }
  518. }
  519. /**
  520. * Helper to ensure JSON parsing always returns an object.
  521. *
  522. * @param {string} data - The data that needs to be parsed.
  523. * @returns {object} - Parsed data or empty object in case of failure.
  524. */
  525. function safeJsonParse(data) {
  526. try {
  527. return JSON.parse(data);
  528. } catch (e) {
  529. return {};
  530. }
  531. }
  532. OlmAdapter.events = OlmAdapterEvents;