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

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