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.

OlmAdapter.js 20KB

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