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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. /* global __filename, Olm */
  2. import base64js from 'base64-js';
  3. import { getLogger } from 'jitsi-meet-logger';
  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('OlmAdapte 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. const participantFeatures = await participant.getFeatures();
  82. if (participantFeatures.has(FEATURE_E2EE) && localParticipantId < participant.getId()) {
  83. promises.push(this._sendSessionInit(participant));
  84. }
  85. }
  86. await Promise.allSettled(promises);
  87. // TODO: retry failed ones.
  88. this._sessionInitialization.resolve();
  89. this._sessionInitialization = undefined;
  90. }
  91. }
  92. /**
  93. * Indicates if olm is supported on the current platform.
  94. *
  95. * @returns {boolean}
  96. */
  97. static isSupported() {
  98. return typeof window.Olm !== 'undefined';
  99. }
  100. /**
  101. * Updates the current participant key and distributes it to all participants in the conference
  102. * by sending a key-info message.
  103. *
  104. * @param {Uint8Array|boolean} key - The new key.
  105. * @retrns {Promise<Number>}
  106. */
  107. async updateKey(key) {
  108. // Store it locally for new sessions.
  109. this._key = key;
  110. this._keyIndex++;
  111. // Broadcast it.
  112. const promises = [];
  113. for (const participant of this._conf.getParticipants()) {
  114. const pId = participant.getId();
  115. const olmData = this._getParticipantOlmData(participant);
  116. // TODO: skip those who don't support E2EE.
  117. if (!olmData.session) {
  118. logger.warn(`Tried to send key to participant ${pId} but we have no session`);
  119. // eslint-disable-next-line no-continue
  120. continue;
  121. }
  122. const uuid = uuidv4();
  123. const data = {
  124. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  125. olm: {
  126. type: OLM_MESSAGE_TYPES.KEY_INFO,
  127. data: {
  128. ciphertext: this._encryptKeyInfo(olmData.session),
  129. uuid
  130. }
  131. }
  132. };
  133. const d = new Deferred();
  134. d.setRejectTimeout(REQ_TIMEOUT);
  135. d.catch(() => {
  136. this._reqs.delete(uuid);
  137. });
  138. this._reqs.set(uuid, d);
  139. promises.push(d);
  140. this._sendMessage(data, pId);
  141. }
  142. await Promise.allSettled(promises);
  143. // TODO: retry failed ones?
  144. return this._keyIndex;
  145. }
  146. /**
  147. * Updates the current participant key.
  148. * @param {Uint8Array|boolean} key - The new key.
  149. * @returns {number}
  150. */
  151. updateCurrentKey(key) {
  152. this._key = key;
  153. return this._keyIndex;
  154. }
  155. /**
  156. * Internal helper to bootstrap the olm library.
  157. *
  158. * @returns {Promise<void>}
  159. * @private
  160. */
  161. async _bootstrapOlm() {
  162. logger.debug('Initializing Olm...');
  163. try {
  164. await Olm.init();
  165. this._olmAccount = new Olm.Account();
  166. this._olmAccount.create();
  167. const idKeys = JSON.parse(this._olmAccount.identity_keys());
  168. this._idKey = idKeys.curve25519;
  169. logger.debug(`Olm ${Olm.get_library_version().join('.')} initialized`);
  170. this._init.resolve();
  171. this.eventEmitter.emit(OlmAdapterEvents.OLM_ID_KEY_READY, this._idKey);
  172. } catch (e) {
  173. logger.error('Failed to initialize Olm', e);
  174. this._init.reject(e);
  175. }
  176. }
  177. /**
  178. * Internal helper for encrypting the current key information for a given participant.
  179. *
  180. * @param {Olm.Session} session - Participant's session.
  181. * @returns {string} - The encrypted text with the key information.
  182. * @private
  183. */
  184. _encryptKeyInfo(session) {
  185. const keyInfo = {};
  186. if (this._key !== undefined) {
  187. keyInfo.key = this._key ? base64js.fromByteArray(this._key) : false;
  188. keyInfo.keyIndex = this._keyIndex;
  189. }
  190. return session.encrypt(JSON.stringify(keyInfo));
  191. }
  192. /**
  193. * Internal helper for getting the olm related data associated with a participant.
  194. *
  195. * @param {JitsiParticipant} participant - Participant whose data wants to be extracted.
  196. * @returns {Object}
  197. * @private
  198. */
  199. _getParticipantOlmData(participant) {
  200. participant[kOlmData] = participant[kOlmData] || {};
  201. return participant[kOlmData];
  202. }
  203. /**
  204. * Handles leaving the conference, cleaning up olm sessions.
  205. *
  206. * @private
  207. */
  208. async _onConferenceLeft() {
  209. logger.debug('Conference left');
  210. await this._init;
  211. for (const participant of this._conf.getParticipants()) {
  212. this._onParticipantLeft(participant.getId(), participant);
  213. }
  214. if (this._olmAccount) {
  215. this._olmAccount.free();
  216. this._olmAccount = undefined;
  217. }
  218. }
  219. /**
  220. * Main message handler. Handles 1-to-1 messages received from other participants
  221. * and send the appropriate replies.
  222. *
  223. * @private
  224. */
  225. async _onEndpointMessageReceived(participant, payload) {
  226. if (payload[JITSI_MEET_MUC_TYPE] !== OLM_MESSAGE_TYPE) {
  227. return;
  228. }
  229. if (!payload.olm) {
  230. logger.warn('Incorrectly formatted message');
  231. return;
  232. }
  233. await this._init;
  234. const msg = payload.olm;
  235. const pId = participant.getId();
  236. const olmData = this._getParticipantOlmData(participant);
  237. switch (msg.type) {
  238. case OLM_MESSAGE_TYPES.SESSION_INIT: {
  239. if (olmData.session) {
  240. logger.warn(`Participant ${pId} already has a session`);
  241. this._sendError(participant, 'Session already established');
  242. } else {
  243. // Create a session for communicating with this participant.
  244. const session = new Olm.Session();
  245. session.create_outbound(this._olmAccount, msg.data.idKey, msg.data.otKey);
  246. olmData.session = session;
  247. // Send ACK
  248. const ack = {
  249. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  250. olm: {
  251. type: OLM_MESSAGE_TYPES.SESSION_ACK,
  252. data: {
  253. ciphertext: this._encryptKeyInfo(session),
  254. uuid: msg.data.uuid
  255. }
  256. }
  257. };
  258. this._sendMessage(ack, pId);
  259. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_E2EE_CHANNEL_READY, pId);
  260. }
  261. break;
  262. }
  263. case OLM_MESSAGE_TYPES.SESSION_ACK: {
  264. if (olmData.session) {
  265. logger.warn(`Participant ${pId} already has a session`);
  266. this._sendError(participant, 'No session found');
  267. } else if (msg.data.uuid === olmData.pendingSessionUuid) {
  268. const { ciphertext } = msg.data;
  269. const d = this._reqs.get(msg.data.uuid);
  270. const session = new Olm.Session();
  271. session.create_inbound(this._olmAccount, ciphertext.body);
  272. // Remove OT keys that have been used to setup this session.
  273. this._olmAccount.remove_one_time_keys(session);
  274. // Decrypt first message.
  275. const data = session.decrypt(ciphertext.type, ciphertext.body);
  276. olmData.session = session;
  277. olmData.pendingSessionUuid = undefined;
  278. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_E2EE_CHANNEL_READY, pId);
  279. this._reqs.delete(msg.data.uuid);
  280. d.resolve();
  281. const json = safeJsonParse(data);
  282. if (json.key) {
  283. const key = base64js.toByteArray(json.key);
  284. const keyIndex = json.keyIndex;
  285. olmData.lastKey = key;
  286. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_KEY_UPDATED, pId, key, keyIndex);
  287. }
  288. } else {
  289. logger.warn('Received ACK with the wrong UUID');
  290. this._sendError(participant, 'Invalid UUID');
  291. }
  292. break;
  293. }
  294. case OLM_MESSAGE_TYPES.ERROR: {
  295. logger.error(msg.data.error);
  296. break;
  297. }
  298. case OLM_MESSAGE_TYPES.KEY_INFO: {
  299. if (olmData.session) {
  300. const { ciphertext } = msg.data;
  301. const data = olmData.session.decrypt(ciphertext.type, ciphertext.body);
  302. const json = safeJsonParse(data);
  303. if (json.key !== undefined && json.keyIndex !== undefined) {
  304. const key = json.key ? base64js.toByteArray(json.key) : false;
  305. const keyIndex = json.keyIndex;
  306. if (!isEqual(olmData.lastKey, key)) {
  307. olmData.lastKey = key;
  308. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_KEY_UPDATED, pId, key, keyIndex);
  309. }
  310. // Send ACK.
  311. const ack = {
  312. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  313. olm: {
  314. type: OLM_MESSAGE_TYPES.KEY_INFO_ACK,
  315. data: {
  316. ciphertext: this._encryptKeyInfo(olmData.session),
  317. uuid: msg.data.uuid
  318. }
  319. }
  320. };
  321. this._sendMessage(ack, pId);
  322. }
  323. } else {
  324. logger.debug(`Received key info message from ${pId} but we have no session for them!`);
  325. this._sendError(participant, 'No session found while processing key-info');
  326. }
  327. break;
  328. }
  329. case OLM_MESSAGE_TYPES.KEY_INFO_ACK: {
  330. if (olmData.session) {
  331. const { ciphertext } = msg.data;
  332. const data = olmData.session.decrypt(ciphertext.type, ciphertext.body);
  333. const json = safeJsonParse(data);
  334. if (json.key !== undefined && json.keyIndex !== undefined) {
  335. const key = json.key ? base64js.toByteArray(json.key) : false;
  336. const keyIndex = json.keyIndex;
  337. if (!isEqual(olmData.lastKey, key)) {
  338. olmData.lastKey = key;
  339. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_KEY_UPDATED, pId, key, keyIndex);
  340. }
  341. }
  342. const d = this._reqs.get(msg.data.uuid);
  343. this._reqs.delete(msg.data.uuid);
  344. d.resolve();
  345. } else {
  346. logger.debug(`Received key info ack message from ${pId} but we have no session for them!`);
  347. this._sendError(participant, 'No session found while processing key-info-ack');
  348. }
  349. break;
  350. }
  351. }
  352. }
  353. /**
  354. * Handles a participant leaving. When a participant leaves their olm session is destroyed.
  355. *
  356. * @private
  357. */
  358. _onParticipantLeft(id, participant) {
  359. logger.debug(`Participant ${id} left`);
  360. const olmData = this._getParticipantOlmData(participant);
  361. if (olmData.session) {
  362. olmData.session.free();
  363. olmData.session = undefined;
  364. }
  365. }
  366. /**
  367. * Handles an update in a participant's presence property.
  368. *
  369. * @param {JitsiParticipant} participant - The participant.
  370. * @param {string} name - The name of the property that changed.
  371. * @param {*} oldValue - The property's previous value.
  372. * @param {*} newValue - The property's new value.
  373. * @private
  374. */
  375. async _onParticipantPropertyChanged(participant, name, oldValue, newValue) {
  376. switch (name) {
  377. case 'e2ee.enabled':
  378. if (newValue && this._conf.isE2EEEnabled()) {
  379. const localParticipantId = this._conf.myUserId();
  380. const participantId = participant.getId();
  381. const participantFeatures = await participant.getFeatures();
  382. if (participantFeatures.has(FEATURE_E2EE) && localParticipantId < participantId) {
  383. if (this._sessionInitialization) {
  384. await this._sessionInitialization;
  385. }
  386. await this._sendSessionInit(participant);
  387. const olmData = this._getParticipantOlmData(participant);
  388. const uuid = uuidv4();
  389. const data = {
  390. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  391. olm: {
  392. type: OLM_MESSAGE_TYPES.KEY_INFO,
  393. data: {
  394. ciphertext: this._encryptKeyInfo(olmData.session),
  395. uuid
  396. }
  397. }
  398. };
  399. this._sendMessage(data, participantId);
  400. }
  401. }
  402. break;
  403. }
  404. }
  405. /**
  406. * Builds and sends an error message to the target participant.
  407. *
  408. * @param {JitsiParticipant} participant - The target participant.
  409. * @param {string} error - The error message.
  410. * @returns {void}
  411. */
  412. _sendError(participant, error) {
  413. const pId = participant.getId();
  414. const err = {
  415. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  416. olm: {
  417. type: OLM_MESSAGE_TYPES.ERROR,
  418. data: {
  419. error
  420. }
  421. }
  422. };
  423. this._sendMessage(err, pId);
  424. }
  425. /**
  426. * Internal helper to send the given object to the given participant ID.
  427. * This function merely exists so the transport can be easily swapped.
  428. * Currently messages are transmitted via XMPP MUC private messages.
  429. *
  430. * @param {object} data - The data that will be sent to the target participant.
  431. * @param {string} participantId - ID of the target participant.
  432. */
  433. _sendMessage(data, participantId) {
  434. this._conf.sendMessage(data, participantId);
  435. }
  436. /**
  437. * Builds and sends the session-init request to the target participant.
  438. *
  439. * @param {JitsiParticipant} participant - Participant to whom we'll send the request.
  440. * @returns {Promise} - The promise will be resolved when the session-ack is received.
  441. * @private
  442. */
  443. _sendSessionInit(participant) {
  444. const pId = participant.getId();
  445. const olmData = this._getParticipantOlmData(participant);
  446. if (olmData.session) {
  447. logger.warn(`Tried to send session-init to ${pId} but we already have a session`);
  448. return Promise.reject();
  449. }
  450. if (olmData.pendingSessionUuid !== undefined) {
  451. logger.warn(`Tried to send session-init to ${pId} but we already have a pending session`);
  452. return Promise.reject();
  453. }
  454. // Generate a One Time Key.
  455. this._olmAccount.generate_one_time_keys(1);
  456. const otKeys = JSON.parse(this._olmAccount.one_time_keys());
  457. const otKey = Object.values(otKeys.curve25519)[0];
  458. if (!otKey) {
  459. return Promise.reject(new Error('No one-time-keys generated'));
  460. }
  461. // Mark the OT keys (one really) as published so they are not reused.
  462. this._olmAccount.mark_keys_as_published();
  463. const uuid = uuidv4();
  464. const init = {
  465. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  466. olm: {
  467. type: OLM_MESSAGE_TYPES.SESSION_INIT,
  468. data: {
  469. idKey: this._idKey,
  470. otKey,
  471. uuid
  472. }
  473. }
  474. };
  475. const d = new Deferred();
  476. d.setRejectTimeout(REQ_TIMEOUT);
  477. d.catch(() => {
  478. this._reqs.delete(uuid);
  479. olmData.pendingSessionUuid = undefined;
  480. });
  481. this._reqs.set(uuid, d);
  482. this._sendMessage(init, pId);
  483. // Store the UUID for matching with the ACK.
  484. olmData.pendingSessionUuid = uuid;
  485. return d;
  486. }
  487. }
  488. OlmAdapter.events = OlmAdapterEvents;
  489. /**
  490. * Helper to ensure JSON parsing always returns an object.
  491. *
  492. * @param {string} data - The data that needs to be parsed.
  493. * @returns {object} - Parsed data or empty object in case of failure.
  494. */
  495. function safeJsonParse(data) {
  496. try {
  497. return JSON.parse(data);
  498. } catch (e) {
  499. return {};
  500. }
  501. }