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

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