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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. /* global 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. import { E2EEErrors } from './E2EEErrors';
  11. import { generateSas } from './SAS';
  12. const logger = getLogger(__filename);
  13. const REQ_TIMEOUT = 5 * 1000;
  14. const OLM_MESSAGE_TYPE = 'olm';
  15. const OLM_MESSAGE_TYPES = {
  16. ERROR: 'error',
  17. KEY_INFO: 'key-info',
  18. KEY_INFO_ACK: 'key-info-ack',
  19. SESSION_ACK: 'session-ack',
  20. SESSION_INIT: 'session-init',
  21. SAS_START: 'sas-start',
  22. SAS_ACCEPT: 'sas-accept',
  23. SAS_KEY: 'sas-key',
  24. SAS_MAC: 'sas-mac'
  25. };
  26. const OLM_SAS_NUM_BYTES = 6;
  27. const OLM_KEY_VERIFICATION_MAC_INFO = 'Jitsi-KEY_VERIFICATION_MAC';
  28. const OLM_KEY_VERIFICATION_MAC_KEY_IDS = 'Jitsi-KEY_IDS';
  29. const kOlmData = Symbol('OlmData');
  30. const OlmAdapterEvents = {
  31. PARTICIPANT_E2EE_CHANNEL_READY: 'olm.participant_e2ee_channel_ready',
  32. PARTICIPANT_SAS_AVAILABLE: 'olm.participant_sas_available',
  33. PARTICIPANT_SAS_READY: 'olm.participant_sas_ready',
  34. PARTICIPANT_KEY_UPDATED: 'olm.partitipant_key_updated',
  35. PARTICIPANT_VERIFICATION_COMPLETED: 'olm.participant_verification_completed'
  36. };
  37. /**
  38. * This class implements an End-to-End Encrypted communication channel between every two peers
  39. * in the conference. This channel uses libolm to achieve E2EE.
  40. *
  41. * The created channel is then used to exchange the secret key that each participant will use
  42. * to encrypt the actual media (see {@link E2EEContext}).
  43. *
  44. * A simple JSON message based protocol is implemented, which follows a request - response model:
  45. * - session-init: Initiates an olm session establishment procedure. This message will be sent
  46. * by the participant who just joined, to everyone else.
  47. * - session-ack: Completes the olm session etablishment. This messsage may contain ancilliary
  48. * encrypted data, more specifically the sender's current key.
  49. * - key-info: Includes the sender's most up to date key information.
  50. * - key-info-ack: Acknowledges the reception of a key-info request. In addition, it may contain
  51. * the sender's key information, if available.
  52. * - error: Indicates a request processing error has occurred.
  53. *
  54. * These requessts and responses are transport independent. Currently they are sent using XMPP
  55. * MUC private messages.
  56. */
  57. console.log("ljm_dbg OlmAdapter! dev~j8")
  58. export class OlmAdapter extends Listenable {
  59. /**
  60. * Creates an adapter instance for the given conference.
  61. */
  62. constructor(conference) {
  63. console.log("ljm_dbg OlmAdapter constructor")
  64. super();
  65. if (glob_rx?.fns?.glob_dev_fncb("mkh_dev")){
  66. this.mkh_dev =true
  67. }
  68. this._conf = conference;
  69. this._init = new Deferred();
  70. this._mediaKey = undefined;
  71. this._mediaKeyIndex = -1;
  72. this._reqs = new Map();
  73. this._sessionInitialization = undefined;
  74. if (OlmAdapter.isSupported()) {
  75. this._bootstrapOlm();
  76. this._conf.on(JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED, this._onEndpointMessageReceived.bind(this));
  77. this._conf.on(JitsiConferenceEvents.CONFERENCE_LEFT, this._onConferenceLeft.bind(this));
  78. this._conf.on(JitsiConferenceEvents.USER_LEFT, this._onParticipantLeft.bind(this));
  79. this._conf.on(JitsiConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  80. this._onParticipantPropertyChanged.bind(this));
  81. } else {
  82. this._init.reject(new Error('Olm not supported'));
  83. }
  84. }
  85. /**
  86. * Returns the current participants conference ID.
  87. *
  88. * @returns {string}
  89. */
  90. get myId() {
  91. return this._conf.myUserId();
  92. }
  93. /**
  94. * Starts new olm sessions with every other participant that has the participantId "smaller" the localParticipantId.
  95. */
  96. async initSessions() {
  97. if (this._sessionInitialization) {
  98. throw new Error('OlmAdapter initSessions called multiple times');
  99. } else {
  100. this._sessionInitialization = new Deferred();
  101. await this._init;
  102. const promises = [];
  103. const localParticipantId = this._conf.myUserId();
  104. for (const participant of this._conf.getParticipants()) {
  105. if (participant.hasFeature(FEATURE_E2EE) && localParticipantId < participant.getId()) {
  106. promises.push(this._sendSessionInit(participant));
  107. }
  108. }
  109. await Promise.allSettled(promises);
  110. // TODO: retry failed ones.
  111. this._sessionInitialization.resolve();
  112. this._sessionInitialization = undefined;
  113. }
  114. }
  115. /**
  116. * Indicates if olm is supported on the current platform.
  117. *
  118. * @returns {boolean}
  119. */
  120. static isSupported() {
  121. return typeof window.Olm !== 'undefined';
  122. }
  123. /**
  124. * Updates the current participant key and distributes it to all participants in the conference
  125. * by sending a key-info message.
  126. *
  127. * @param {Uint8Array|boolean} key - The new key.
  128. * @retrns {Promise<Number>}
  129. */
  130. async updateKey(_key) {
  131. var key
  132. if (this.mkh_dev){
  133. key = glob_u.tvar.e2ee.key2
  134. } else {
  135. key = _key
  136. }
  137. // Store it locally for new sessions.
  138. this._mediaKey = key;
  139. this._mediaKeyIndex++;
  140. // Broadcast it.
  141. const promises = [];
  142. for (const participant of this._conf.getParticipants()) {
  143. const pId = participant.getId();
  144. const olmData = this._getParticipantOlmData(participant);
  145. // TODO: skip those who don't support E2EE.
  146. if (!olmData.session) {
  147. logger.warn(`Tried to send key to participant ${pId} but we have no session`);
  148. // eslint-disable-next-line no-continue
  149. continue;
  150. }
  151. const uuid = uuidv4();
  152. const data = {
  153. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  154. olm: {
  155. type: OLM_MESSAGE_TYPES.KEY_INFO,
  156. data: {
  157. ciphertext: this._encryptKeyInfo(olmData.session),
  158. uuid
  159. }
  160. }
  161. };
  162. const d = new Deferred();
  163. d.setRejectTimeout(REQ_TIMEOUT);
  164. d.catch(() => {
  165. this._reqs.delete(uuid);
  166. });
  167. this._reqs.set(uuid, d);
  168. promises.push(d);
  169. this._sendMessage(data, pId);
  170. }
  171. await Promise.allSettled(promises);
  172. // TODO: retry failed ones?
  173. return this._mediaKeyIndex;
  174. }
  175. /**
  176. * Updates the current participant key.
  177. * @param {Uint8Array|boolean} key - The new key.
  178. * @returns {number}
  179. */
  180. updateCurrentMediaKey(_key) {
  181. var key
  182. if (this.mkh_dev){
  183. key = glob_u.tvar.e2ee.key2
  184. } else {
  185. key = _key
  186. }
  187. this._mediaKey = key;
  188. return this._mediaKeyIndex;
  189. }
  190. /**
  191. * Frees the olmData session for the given participant.
  192. *
  193. */
  194. clearParticipantSession(participant) {
  195. const olmData = this._getParticipantOlmData(participant);
  196. if (olmData.session) {
  197. olmData.session.free();
  198. olmData.session = undefined;
  199. }
  200. }
  201. /**
  202. * Frees the olmData sessions for all participants.
  203. *
  204. */
  205. clearAllParticipantsSessions() {
  206. for (const participant of this._conf.getParticipants()) {
  207. this.clearParticipantSession(participant);
  208. }
  209. }
  210. /**
  211. * Sends sacMac if channel verification waas successful.
  212. *
  213. */
  214. markParticipantVerified(participant, isVerified) {
  215. const olmData = this._getParticipantOlmData(participant);
  216. const pId = participant.getId();
  217. if (!isVerified) {
  218. olmData.sasVerification = undefined;
  219. logger.warn(`Verification failed for participant ${pId}`);
  220. this.eventEmitter.emit(
  221. OlmAdapterEvents.PARTICIPANT_VERIFICATION_COMPLETED,
  222. pId,
  223. false,
  224. E2EEErrors.E2EE_SAS_CHANNEL_VERIFICATION_FAILED);
  225. return;
  226. }
  227. if (!olmData.sasVerification) {
  228. logger.warn(`Participant ${pId} does not have valid sasVerification`);
  229. this.eventEmitter.emit(
  230. OlmAdapterEvents.PARTICIPANT_VERIFICATION_COMPLETED,
  231. pId,
  232. false,
  233. E2EEErrors.E2EE_SAS_INVALID_SAS_VERIFICATION);
  234. return;
  235. }
  236. const { sas, sasMacSent } = olmData.sasVerification;
  237. if (sas && sas.is_their_key_set() && !sasMacSent) {
  238. this._sendSasMac(participant);
  239. // Mark the MAC as sent so we don't send it multiple times.
  240. olmData.sasVerification.sasMacSent = true;
  241. }
  242. }
  243. /**
  244. * Internal helper to bootstrap the olm library.
  245. *
  246. * @returns {Promise<void>}
  247. * @private
  248. */
  249. async _bootstrapOlm() {
  250. logger.debug('Initializing Olm...');
  251. try {
  252. await Olm.init();
  253. this._olmAccount = new Olm.Account();
  254. this._olmAccount.create();
  255. this._idKeys = JSON.parse(this._olmAccount.identity_keys());
  256. logger.debug(`Olm ${Olm.get_library_version().join('.')} initialized`);
  257. this._init.resolve();
  258. this._onIdKeysReady(this._idKeys);
  259. } catch (e) {
  260. logger.error('Failed to initialize Olm', e);
  261. this._init.reject(e);
  262. }
  263. }
  264. /**
  265. * Starts the verification process for the given participant as described here
  266. * https://spec.matrix.org/latest/client-server-api/#short-authentication-string-sas-verification
  267. *
  268. * | |
  269. | m.key.verification.start |
  270. |-------------------------------->|
  271. | |
  272. | m.key.verification.accept |
  273. |<--------------------------------|
  274. | |
  275. | m.key.verification.key |
  276. |-------------------------------->|
  277. | |
  278. | m.key.verification.key |
  279. |<--------------------------------|
  280. | |
  281. | m.key.verification.mac |
  282. |-------------------------------->|
  283. | |
  284. | m.key.verification.mac |
  285. |<--------------------------------|
  286. | |
  287. *
  288. * @param {JitsiParticipant} participant - The target participant.
  289. * @returns {Promise<void>}
  290. * @private
  291. */
  292. startVerification(participant) {
  293. const pId = participant.getId();
  294. const olmData = this._getParticipantOlmData(participant);
  295. if (!olmData.session) {
  296. logger.warn(`Tried to start verification with participant ${pId} but we have no session`);
  297. return;
  298. }
  299. if (olmData.sasVerification) {
  300. logger.warn(`There is already a verification in progress with participant ${pId}`);
  301. return;
  302. }
  303. olmData.sasVerification = {
  304. sas: new Olm.SAS(),
  305. transactionId: uuidv4()
  306. };
  307. const startContent = {
  308. transactionId: olmData.sasVerification.transactionId
  309. };
  310. olmData.sasVerification.startContent = startContent;
  311. olmData.sasVerification.isInitiator = true;
  312. const startMessage = {
  313. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  314. olm: {
  315. type: OLM_MESSAGE_TYPES.SAS_START,
  316. data: startContent
  317. }
  318. };
  319. this._sendMessage(startMessage, pId);
  320. }
  321. /**
  322. * Publishes our own Olmn id key in presence.
  323. * @private
  324. */
  325. _onIdKeysReady(idKeys) {
  326. logger.debug(`Olm id key ready: ${idKeys}`);
  327. // Publish it in presence.
  328. for (const keyType in idKeys) {
  329. if (idKeys.hasOwnProperty(keyType)) {
  330. const key = idKeys[keyType];
  331. this._conf.setLocalParticipantProperty(`e2ee.idKey.${keyType}`, key);
  332. }
  333. }
  334. }
  335. /**
  336. * Event posted when the E2EE signalling channel has been established with the given participant.
  337. * @private
  338. */
  339. _onParticipantE2EEChannelReady(id) {
  340. logger.debug(`E2EE channel with participant ${id} is ready`);
  341. }
  342. /**
  343. * Internal helper for encrypting the current key information for a given participant.
  344. *
  345. * @param {Olm.Session} session - Participant's session.
  346. * @returns {string} - The encrypted text with the key information.
  347. * @private
  348. */
  349. _encryptKeyInfo(session) {
  350. const keyInfo = {};
  351. if (this._mediaKey !== undefined) {
  352. keyInfo.key = this._mediaKey ? base64js.fromByteArray(this._mediaKey) : false;
  353. keyInfo.keyIndex = this._mediaKeyIndex;
  354. }
  355. return session.encrypt(JSON.stringify(keyInfo));
  356. }
  357. /**
  358. * Internal helper for getting the olm related data associated with a participant.
  359. *
  360. * @param {JitsiParticipant} participant - Participant whose data wants to be extracted.
  361. * @returns {Object}
  362. * @private
  363. */
  364. _getParticipantOlmData(participant) {
  365. participant[kOlmData] = participant[kOlmData] || {};
  366. return participant[kOlmData];
  367. }
  368. /**
  369. * Handles leaving the conference, cleaning up olm sessions.
  370. *
  371. * @private
  372. */
  373. async _onConferenceLeft() {
  374. logger.debug('Conference left');
  375. await this._init;
  376. for (const participant of this._conf.getParticipants()) {
  377. this._onParticipantLeft(participant.getId(), participant);
  378. }
  379. if (this._olmAccount) {
  380. this._olmAccount.free();
  381. this._olmAccount = undefined;
  382. }
  383. }
  384. /**
  385. * Main message handler. Handles 1-to-1 messages received from other participants
  386. * and send the appropriate replies.
  387. *
  388. * @private
  389. */
  390. async _onEndpointMessageReceived(participant, payload) {
  391. console.log("ljm_olm _onEndpointMessageReceived")
  392. if (payload[JITSI_MEET_MUC_TYPE] !== OLM_MESSAGE_TYPE) {
  393. return;
  394. }
  395. if (!payload.olm) {
  396. logger.warn('Incorrectly formatted message');
  397. return;
  398. }
  399. await this._init;
  400. const msg = payload.olm;
  401. const pId = participant.getId();
  402. const olmData = this._getParticipantOlmData(participant);
  403. switch (msg.type) {
  404. case OLM_MESSAGE_TYPES.SESSION_INIT: {
  405. if (olmData.session) {
  406. logger.warn(`Participant ${pId} already has a session`);
  407. this._sendError(participant, 'Session already established');
  408. } else {
  409. // Create a session for communicating with this participant.
  410. const session = new Olm.Session();
  411. session.create_outbound(this._olmAccount, msg.data.idKey, msg.data.otKey);
  412. olmData.session = session;
  413. // Send ACK
  414. const ack = {
  415. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  416. olm: {
  417. type: OLM_MESSAGE_TYPES.SESSION_ACK,
  418. data: {
  419. ciphertext: this._encryptKeyInfo(session),
  420. uuid: msg.data.uuid
  421. }
  422. }
  423. };
  424. this._sendMessage(ack, pId);
  425. this._onParticipantE2EEChannelReady(pId);
  426. }
  427. break;
  428. }
  429. case OLM_MESSAGE_TYPES.SESSION_ACK: {
  430. if (olmData.session) {
  431. logger.warn(`Participant ${pId} already has a session`);
  432. this._sendError(participant, 'No session found');
  433. } else if (msg.data.uuid === olmData.pendingSessionUuid) {
  434. const { ciphertext } = msg.data;
  435. const d = this._reqs.get(msg.data.uuid);
  436. const session = new Olm.Session();
  437. session.create_inbound(this._olmAccount, ciphertext.body);
  438. // Remove OT keys that have been used to setup this session.
  439. this._olmAccount.remove_one_time_keys(session);
  440. // Decrypt first message.
  441. const data = session.decrypt(ciphertext.type, ciphertext.body);
  442. olmData.session = session;
  443. olmData.pendingSessionUuid = undefined;
  444. this._onParticipantE2EEChannelReady(pId);
  445. this._reqs.delete(msg.data.uuid);
  446. d.resolve();
  447. const json = safeJsonParse(data);
  448. if (json.key) {
  449. const key = base64js.toByteArray(json.key);
  450. const keyIndex = json.keyIndex;
  451. olmData.lastKey = key;
  452. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_KEY_UPDATED, pId, key, keyIndex);
  453. }
  454. } else {
  455. logger.warn('Received ACK with the wrong UUID');
  456. this._sendError(participant, 'Invalid UUID');
  457. }
  458. break;
  459. }
  460. case OLM_MESSAGE_TYPES.ERROR: {
  461. logger.error(msg.data.error);
  462. break;
  463. }
  464. case OLM_MESSAGE_TYPES.KEY_INFO: {
  465. if (olmData.session) {
  466. const { ciphertext } = msg.data;
  467. const data = olmData.session.decrypt(ciphertext.type, ciphertext.body);
  468. const json = safeJsonParse(data);
  469. if (json.key !== undefined && json.keyIndex !== undefined) {
  470. const key = json.key ? base64js.toByteArray(json.key) : false;
  471. const keyIndex = json.keyIndex;
  472. if (!isEqual(olmData.lastKey, key)) {
  473. olmData.lastKey = key;
  474. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_KEY_UPDATED, pId, key, keyIndex);
  475. }
  476. // Send ACK.
  477. const ack = {
  478. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  479. olm: {
  480. type: OLM_MESSAGE_TYPES.KEY_INFO_ACK,
  481. data: {
  482. ciphertext: this._encryptKeyInfo(olmData.session),
  483. uuid: msg.data.uuid
  484. }
  485. }
  486. };
  487. this._sendMessage(ack, pId);
  488. }
  489. } else {
  490. logger.debug(`Received key info message from ${pId} but we have no session for them!`);
  491. this._sendError(participant, 'No session found while processing key-info');
  492. }
  493. break;
  494. }
  495. case OLM_MESSAGE_TYPES.KEY_INFO_ACK: {
  496. if (olmData.session) {
  497. const { ciphertext } = msg.data;
  498. const data = olmData.session.decrypt(ciphertext.type, ciphertext.body);
  499. const json = safeJsonParse(data);
  500. if (json.key !== undefined && json.keyIndex !== undefined) {
  501. const key = json.key ? base64js.toByteArray(json.key) : false;
  502. const keyIndex = json.keyIndex;
  503. if (!isEqual(olmData.lastKey, key)) {
  504. olmData.lastKey = key;
  505. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_KEY_UPDATED, pId, key, keyIndex);
  506. }
  507. }
  508. const d = this._reqs.get(msg.data.uuid);
  509. this._reqs.delete(msg.data.uuid);
  510. d.resolve();
  511. } else {
  512. logger.debug(`Received key info ack message from ${pId} but we have no session for them!`);
  513. this._sendError(participant, 'No session found while processing key-info-ack');
  514. }
  515. break;
  516. }
  517. case OLM_MESSAGE_TYPES.SAS_START: {
  518. if (!olmData.session) {
  519. logger.debug(`Received sas init message from ${pId} but we have no session for them!`);
  520. this._sendError(participant, 'No session found while processing sas-init');
  521. return;
  522. }
  523. if (olmData.sasVerification?.sas) {
  524. logger.warn(`SAS already created for participant ${pId}`);
  525. this.eventEmitter.emit(
  526. OlmAdapterEvents.PARTICIPANT_VERIFICATION_COMPLETED,
  527. pId,
  528. false,
  529. E2EEErrors.E2EE_SAS_INVALID_SAS_VERIFICATION);
  530. return;
  531. }
  532. const { transactionId } = msg.data;
  533. const sas = new Olm.SAS();
  534. olmData.sasVerification = {
  535. sas,
  536. transactionId,
  537. isInitiator: false
  538. };
  539. const pubKey = olmData.sasVerification.sas.get_pubkey();
  540. const commitment = this._computeCommitment(pubKey, msg.data);
  541. /* The first phase of the verification process, the Key agreement phase
  542. https://spec.matrix.org/latest/client-server-api/#short-authentication-string-sas-verification
  543. */
  544. const acceptMessage = {
  545. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  546. olm: {
  547. type: OLM_MESSAGE_TYPES.SAS_ACCEPT,
  548. data: {
  549. transactionId,
  550. commitment
  551. }
  552. }
  553. };
  554. this._sendMessage(acceptMessage, pId);
  555. break;
  556. }
  557. case OLM_MESSAGE_TYPES.SAS_ACCEPT: {
  558. if (!olmData.session) {
  559. logger.debug(`Received sas accept message from ${pId} but we have no session for them!`);
  560. this._sendError(participant, 'No session found while processing sas-accept');
  561. return;
  562. }
  563. const { commitment, transactionId } = msg.data;
  564. if (!olmData.sasVerification) {
  565. logger.warn(`SAS_ACCEPT Participant ${pId} does not have valid sasVerification`);
  566. this.eventEmitter.emit(
  567. OlmAdapterEvents.PARTICIPANT_VERIFICATION_COMPLETED,
  568. pId,
  569. false,
  570. E2EEErrors.E2EE_SAS_INVALID_SAS_VERIFICATION);
  571. return;
  572. }
  573. if (olmData.sasVerification.sasCommitment) {
  574. logger.debug(`Already received sas commitment message from ${pId}!`);
  575. this._sendError(participant, 'Already received sas commitment message from ${pId}!');
  576. return;
  577. }
  578. olmData.sasVerification.sasCommitment = commitment;
  579. const pubKey = olmData.sasVerification.sas.get_pubkey();
  580. // Send KEY.
  581. const keyMessage = {
  582. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  583. olm: {
  584. type: OLM_MESSAGE_TYPES.SAS_KEY,
  585. data: {
  586. key: pubKey,
  587. transactionId
  588. }
  589. }
  590. };
  591. this._sendMessage(keyMessage, pId);
  592. olmData.sasVerification.keySent = true;
  593. break;
  594. }
  595. case OLM_MESSAGE_TYPES.SAS_KEY: {
  596. if (!olmData.session) {
  597. logger.debug(`Received sas key message from ${pId} but we have no session for them!`);
  598. this._sendError(participant, 'No session found while processing sas-key');
  599. return;
  600. }
  601. if (!olmData.sasVerification) {
  602. logger.warn(`SAS_KEY Participant ${pId} does not have valid sasVerification`);
  603. this.eventEmitter.emit(
  604. OlmAdapterEvents.PARTICIPANT_VERIFICATION_COMPLETED,
  605. pId,
  606. false,
  607. E2EEErrors.E2EE_SAS_INVALID_SAS_VERIFICATION);
  608. return;
  609. }
  610. const { isInitiator, sas, sasCommitment, startContent, keySent } = olmData.sasVerification;
  611. if (sas.is_their_key_set()) {
  612. logger.warn('SAS already has their key!');
  613. return;
  614. }
  615. const { key: theirKey, transactionId } = msg.data;
  616. if (sasCommitment) {
  617. const commitment = this._computeCommitment(theirKey, startContent);
  618. if (sasCommitment !== commitment) {
  619. this._sendError(participant, 'OlmAdapter commitments mismatched');
  620. this.eventEmitter.emit(
  621. OlmAdapterEvents.PARTICIPANT_VERIFICATION_COMPLETED,
  622. pId,
  623. false,
  624. E2EEErrors.E2EE_SAS_COMMITMENT_MISMATCHED);
  625. olmData.sasVerification.free();
  626. return;
  627. }
  628. }
  629. sas.set_their_key(theirKey);
  630. const pubKey = sas.get_pubkey();
  631. const myInfo = `${this.myId}|${pubKey}`;
  632. const theirInfo = `${pId}|${theirKey}`;
  633. const info = isInitiator ? `${myInfo}|${theirInfo}` : `${theirInfo}|${myInfo}`;
  634. const sasBytes = sas.generate_bytes(info, OLM_SAS_NUM_BYTES);
  635. const generatedSas = generateSas(sasBytes);
  636. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_SAS_READY, pId, generatedSas);
  637. if (keySent) {
  638. return;
  639. }
  640. const keyMessage = {
  641. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  642. olm: {
  643. type: OLM_MESSAGE_TYPES.SAS_KEY,
  644. data: {
  645. key: pubKey,
  646. transactionId
  647. }
  648. }
  649. };
  650. this._sendMessage(keyMessage, pId);
  651. olmData.sasVerification.keySent = true;
  652. break;
  653. }
  654. case OLM_MESSAGE_TYPES.SAS_MAC: {
  655. if (!olmData.session) {
  656. logger.debug(`Received sas mac message from ${pId} but we have no session for them!`);
  657. this._sendError(participant, 'No session found while processing sas-mac');
  658. return;
  659. }
  660. const { keys, mac, transactionId } = msg.data;
  661. if (!mac || !keys) {
  662. logger.warn('Invalid SAS MAC message');
  663. return;
  664. }
  665. if (!olmData.sasVerification) {
  666. logger.warn(`SAS_MAC Participant ${pId} does not have valid sasVerification`);
  667. return;
  668. }
  669. const sas = olmData.sasVerification.sas;
  670. // Verify the received MACs.
  671. const baseInfo = `${OLM_KEY_VERIFICATION_MAC_INFO}${pId}${this.myId}${transactionId}`;
  672. const keysMac = sas.calculate_mac(
  673. Object.keys(mac).sort().join(','), // eslint-disable-line newline-per-chained-call
  674. baseInfo + OLM_KEY_VERIFICATION_MAC_KEY_IDS
  675. );
  676. if (keysMac !== keys) {
  677. logger.error('SAS verification error: keys MAC mismatch');
  678. this.eventEmitter.emit(
  679. OlmAdapterEvents.PARTICIPANT_VERIFICATION_COMPLETED,
  680. pId,
  681. false,
  682. E2EEErrors.E2EE_SAS_KEYS_MAC_MISMATCH);
  683. return;
  684. }
  685. if (!olmData.ed25519) {
  686. logger.warn('SAS verification error: Missing ed25519 key');
  687. this.eventEmitter.emit(
  688. OlmAdapterEvents.PARTICIPANT_VERIFICATION_COMPLETED,
  689. pId,
  690. false,
  691. E2EEErrors.E2EE_SAS_MISSING_KEY);
  692. return;
  693. }
  694. for (const [ keyInfo, computedMac ] of Object.entries(mac)) {
  695. const ourComputedMac = sas.calculate_mac(
  696. olmData.ed25519,
  697. baseInfo + keyInfo
  698. );
  699. if (computedMac !== ourComputedMac) {
  700. logger.error('SAS verification error: MAC mismatch');
  701. this.eventEmitter.emit(
  702. OlmAdapterEvents.PARTICIPANT_VERIFICATION_COMPLETED,
  703. pId,
  704. false,
  705. E2EEErrors.E2EE_SAS_MAC_MISMATCH);
  706. return;
  707. }
  708. }
  709. logger.info(`SAS MAC verified for participant ${pId}`);
  710. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_VERIFICATION_COMPLETED, pId, true);
  711. break;
  712. }
  713. }
  714. }
  715. /**
  716. * Handles a participant leaving. When a participant leaves their olm session is destroyed.
  717. *
  718. * @private
  719. */
  720. _onParticipantLeft(id, participant) {
  721. logger.debug(`Participant ${id} left`);
  722. this.clearParticipantSession(participant);
  723. }
  724. /**
  725. * Handles an update in a participant's presence property.
  726. *
  727. * @param {JitsiParticipant} participant - The participant.
  728. * @param {string} name - The name of the property that changed.
  729. * @param {*} oldValue - The property's previous value.
  730. * @param {*} newValue - The property's new value.
  731. * @private
  732. */
  733. async _onParticipantPropertyChanged(participant, name, oldValue, newValue) {
  734. const participantId = participant.getId();
  735. const olmData = this._getParticipantOlmData(participant);
  736. switch (name) {
  737. case 'e2ee.enabled':
  738. if (newValue && this._conf.isE2EEEnabled()) {
  739. const localParticipantId = this._conf.myUserId();
  740. const participantFeatures = await participant.getFeatures();
  741. if (participantFeatures.has(FEATURE_E2EE) && localParticipantId < participantId) {
  742. if (this._sessionInitialization) {
  743. await this._sessionInitialization;
  744. }
  745. await this._sendSessionInit(participant);
  746. const uuid = uuidv4();
  747. const d = new Deferred();
  748. d.setRejectTimeout(REQ_TIMEOUT);
  749. d.catch(() => {
  750. this._reqs.delete(uuid);
  751. olmData.pendingSessionUuid = undefined;
  752. });
  753. this._reqs.set(uuid, d);
  754. const data = {
  755. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  756. olm: {
  757. type: OLM_MESSAGE_TYPES.KEY_INFO,
  758. data: {
  759. ciphertext: this._encryptKeyInfo(olmData.session),
  760. uuid
  761. }
  762. }
  763. };
  764. this._sendMessage(data, participantId);
  765. }
  766. }
  767. break;
  768. case 'e2ee.idKey.ed25519':
  769. olmData.ed25519 = newValue;
  770. this.eventEmitter.emit(OlmAdapterEvents.PARTICIPANT_SAS_AVAILABLE, participantId);
  771. break;
  772. }
  773. }
  774. /**
  775. * Builds and sends an error message to the target participant.
  776. *
  777. * @param {JitsiParticipant} participant - The target participant.
  778. * @param {string} error - The error message.
  779. * @returns {void}
  780. */
  781. _sendError(participant, error) {
  782. const pId = participant.getId();
  783. const err = {
  784. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  785. olm: {
  786. type: OLM_MESSAGE_TYPES.ERROR,
  787. data: {
  788. error
  789. }
  790. }
  791. };
  792. this._sendMessage(err, pId);
  793. }
  794. /**
  795. * Internal helper to send the given object to the given participant ID.
  796. * This function merely exists so the transport can be easily swapped.
  797. * Currently messages are transmitted via XMPP MUC private messages.
  798. *
  799. * @param {object} data - The data that will be sent to the target participant.
  800. * @param {string} participantId - ID of the target participant.
  801. */
  802. _sendMessage(data, participantId) {
  803. this._conf.sendMessage(data, participantId);
  804. }
  805. /**
  806. * Builds and sends the session-init request to the target participant.
  807. *
  808. * @param {JitsiParticipant} participant - Participant to whom we'll send the request.
  809. * @returns {Promise} - The promise will be resolved when the session-ack is received.
  810. * @private
  811. */
  812. _sendSessionInit(participant) {
  813. const pId = participant.getId();
  814. const olmData = this._getParticipantOlmData(participant);
  815. if (olmData.session) {
  816. logger.warn(`Tried to send session-init to ${pId} but we already have a session`);
  817. return Promise.reject();
  818. }
  819. if (olmData.pendingSessionUuid !== undefined) {
  820. logger.warn(`Tried to send session-init to ${pId} but we already have a pending session`);
  821. return Promise.reject();
  822. }
  823. // Generate a One Time Key.
  824. this._olmAccount.generate_one_time_keys(1);
  825. const otKeys = JSON.parse(this._olmAccount.one_time_keys());
  826. const otKey = Object.values(otKeys.curve25519)[0];
  827. if (!otKey) {
  828. return Promise.reject(new Error('No one-time-keys generated'));
  829. }
  830. // Mark the OT keys (one really) as published so they are not reused.
  831. this._olmAccount.mark_keys_as_published();
  832. const uuid = uuidv4();
  833. const init = {
  834. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  835. olm: {
  836. type: OLM_MESSAGE_TYPES.SESSION_INIT,
  837. data: {
  838. idKey: this._idKeys.curve25519,
  839. otKey,
  840. uuid
  841. }
  842. }
  843. };
  844. const d = new Deferred();
  845. d.setRejectTimeout(REQ_TIMEOUT);
  846. d.catch(() => {
  847. this._reqs.delete(uuid);
  848. olmData.pendingSessionUuid = undefined;
  849. });
  850. this._reqs.set(uuid, d);
  851. this._sendMessage(init, pId);
  852. // Store the UUID for matching with the ACK.
  853. olmData.pendingSessionUuid = uuid;
  854. return d;
  855. }
  856. /**
  857. * Builds and sends the SAS MAC message to the given participant.
  858. * The second phase of the verification process, the Key verification phase
  859. https://spec.matrix.org/latest/client-server-api/#short-authentication-string-sas-verification
  860. */
  861. _sendSasMac(participant) {
  862. const pId = participant.getId();
  863. const olmData = this._getParticipantOlmData(participant);
  864. const { sas, transactionId } = olmData.sasVerification;
  865. // Calculate and send MAC with the keys to be verified.
  866. const mac = {};
  867. const keyList = [];
  868. const baseInfo = `${OLM_KEY_VERIFICATION_MAC_INFO}${this.myId}${pId}${transactionId}`;
  869. const deviceKeyId = `ed25519:${pId}`;
  870. mac[deviceKeyId] = sas.calculate_mac(
  871. this._idKeys.ed25519,
  872. baseInfo + deviceKeyId);
  873. keyList.push(deviceKeyId);
  874. const keys = sas.calculate_mac(
  875. keyList.sort().join(','),
  876. baseInfo + OLM_KEY_VERIFICATION_MAC_KEY_IDS
  877. );
  878. const macMessage = {
  879. [JITSI_MEET_MUC_TYPE]: OLM_MESSAGE_TYPE,
  880. olm: {
  881. type: OLM_MESSAGE_TYPES.SAS_MAC,
  882. data: {
  883. keys,
  884. mac,
  885. transactionId
  886. }
  887. }
  888. };
  889. this._sendMessage(macMessage, pId);
  890. }
  891. /**
  892. * Computes the commitment.
  893. */
  894. _computeCommitment(pubKey, data) {
  895. const olmUtil = new Olm.Utility();
  896. const commitment = olmUtil.sha256(pubKey + JSON.stringify(data));
  897. olmUtil.free();
  898. return commitment;
  899. }
  900. }
  901. /**
  902. * Helper to ensure JSON parsing always returns an object.
  903. *
  904. * @param {string} data - The data that needs to be parsed.
  905. * @returns {object} - Parsed data or empty object in case of failure.
  906. */
  907. function safeJsonParse(data) {
  908. try {
  909. return JSON.parse(data);
  910. } catch (e) {
  911. return {};
  912. }
  913. }
  914. OlmAdapter.events = OlmAdapterEvents;