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 21KB

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