modified lib-jitsi-meet dev repo
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

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