Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

OlmAdapter.js 18KB

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