/* Copyright 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ "use strict"; /** * @module crypto */ var anotherjson = require('another-json'); var q = require("q"); var utils = require("../utils"); var OlmDevice = require("./OlmDevice"); var olmlib = require("./olmlib"); var algorithms = require("./algorithms"); var DeviceInfo = require("./deviceinfo"); var DeviceVerification = DeviceInfo.DeviceVerification; /** * Cryptography bits * * @constructor * @alias module:crypto * * @param {module:base-apis~MatrixBaseApis} baseApis base matrix api interface * * @param {external:EventEmitter} eventEmitter event source where we can register * for event notifications * * @param {module:store/session/webstorage~WebStorageSessionStore} sessionStore * Store to be used for end-to-end crypto session data * * @param {string} userId The user ID for the local user * * @param {string} deviceId The identifier for this device. */ function Crypto(baseApis, eventEmitter, sessionStore, userId, deviceId) { this._baseApis = baseApis; this._sessionStore = sessionStore; this._userId = userId; this._deviceId = deviceId; this._olmDevice = new OlmDevice(sessionStore); // EncryptionAlgorithm instance for each room this._roomAlgorithms = {}; this._supportedAlgorithms = utils.keys( algorithms.DECRYPTION_CLASSES ); // build our device keys: these will later be uploaded this._deviceKeys = {}; this._deviceKeys["ed25519:" + this._deviceId] = this._olmDevice.deviceEd25519Key; this._deviceKeys["curve25519:" + this._deviceId] = this._olmDevice.deviceCurve25519Key; // add our own deviceinfo to the sessionstore var deviceInfo = { keys: this._deviceKeys, algorithms: this._supportedAlgorithms, verified: DeviceVerification.VERIFIED, }; var myDevices = this._sessionStore.getEndToEndDevicesForUser( this._userId ) || {}; myDevices[this._deviceId] = deviceInfo; this._sessionStore.storeEndToEndDevicesForUser( this._userId, myDevices ); _registerEventHandlers(this, eventEmitter); this._lastNewDeviceMessageTsByUserDeviceRoom = {}; } function _registerEventHandlers(crypto, eventEmitter) { eventEmitter.on("sync", function(syncState, oldState, data) { try { if (syncState == "PREPARED") { // XXX ugh. we're assuming the eventEmitter is a MatrixClient. // how can we avoid doing so? var rooms = eventEmitter.getRooms(); crypto._onInitialSyncCompleted(rooms); } } catch (e) { console.error("Error handling sync", e); } }); eventEmitter.on("RoomMember.membership", function(event, member, oldMembership) { try { crypto._onRoomMembership(event, member, oldMembership); } catch (e) { console.error("Error handling membership change:", e); } }); eventEmitter.on("toDeviceEvent", function(event) { try { if (event.getType() == "m.room_key") { crypto._onRoomKeyEvent(event); } else if (event.getType() == "m.new_device") { crypto._onNewDeviceEvent(event); } } catch (e) { console.error("Error handling toDeviceEvent:", e); } }); eventEmitter.on("event", function(event) { try { if (!event.isState() || event.getType() != "m.room.encryption") { return; } crypto._onCryptoEvent(event); } catch (e) { console.error("Error handling crypto event:", e); } }); } /** * @return {string} The version of Olm. */ Crypto.getOlmVersion = function() { return OlmDevice.getOlmVersion(); }; /** * Get the Ed25519 key for this device * * @return {string} base64-encoded ed25519 key. */ Crypto.prototype.getDeviceEd25519Key = function() { return this._olmDevice.deviceEd25519Key; }; /** * Upload the device keys to the homeserver and ensure that the * homeserver has enough one-time keys. * @param {number} maxKeys The maximum number of keys to generate * @return {object} A promise that will resolve when the keys are uploaded. */ Crypto.prototype.uploadKeys = function(maxKeys) { var self = this; return _uploadDeviceKeys(this).then(function(res) { var keyCount = res.one_time_key_counts.curve25519 || 0; var maxOneTimeKeys = self._olmDevice.maxNumberOfOneTimeKeys(); var keyLimit = Math.floor(maxOneTimeKeys / 2); var numberToGenerate = Math.max(keyLimit - keyCount, 0); if (maxKeys !== undefined) { numberToGenerate = Math.min(numberToGenerate, maxKeys); } if (numberToGenerate <= 0) { return; } self._olmDevice.generateOneTimeKeys(numberToGenerate); return _uploadOneTimeKeys(self); }); }; // returns a promise which resolves to the response function _uploadDeviceKeys(crypto) { var userId = crypto._userId; var deviceId = crypto._deviceId; var deviceKeys = { algorithms: crypto._supportedAlgorithms, device_id: deviceId, keys: crypto._deviceKeys, user_id: userId, }; var sig = crypto._olmDevice.sign(anotherjson.stringify(deviceKeys)); deviceKeys.signatures = {}; deviceKeys.signatures[userId] = {}; deviceKeys.signatures[userId]["ed25519:" + deviceId] = sig; return crypto._baseApis.uploadKeysRequest({ device_keys: deviceKeys, }, { // for now, we set the device id explicitly, as we may not be using the // same one as used in login. device_id: deviceId, }); } // returns a promise which resolves to the response function _uploadOneTimeKeys(crypto) { var oneTimeKeys = crypto._olmDevice.getOneTimeKeys(); var oneTimeJson = {}; for (var keyId in oneTimeKeys.curve25519) { if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) { oneTimeJson["curve25519:" + keyId] = oneTimeKeys.curve25519[keyId]; } } return crypto._baseApis.uploadKeysRequest({ one_time_keys: oneTimeJson }, { // for now, we set the device id explicitly, as we may not be using the // same one as used in login. device_id: crypto._deviceId, }).then(function(res) { crypto._olmDevice.markKeysAsPublished(); return res; }); } /** * Download the keys for a list of users and stores the keys in the session * store. * @param {Array} userIds The users to fetch. * @param {bool} forceDownload Always download the keys even if cached. * * @return {Promise} A promise which resolves to a map userId->deviceId->{@link * module:crypto/deviceinfo|DeviceInfo}. */ Crypto.prototype.downloadKeys = function(userIds, forceDownload) { var self = this; // map from userid -> deviceid -> DeviceInfo var stored = {}; // list of userids we need to download keys for var downloadUsers = []; for (var i = 0; i < userIds.length; ++i) { var userId = userIds[i]; stored[userId] = {}; var devices = this.getStoredDevicesForUser(userId); for (var j = 0; j < devices.length; ++j) { var dev = devices[j]; stored[userId][dev.deviceId] = dev; } if (devices.length === 0 || forceDownload) { downloadUsers.push(userId); } } if (downloadUsers.length === 0) { return q(stored); } return this._baseApis.downloadKeysForUsers( downloadUsers ).then(function(res) { for (var userId in res.device_keys) { if (!stored.hasOwnProperty(userId)) { // spurious result continue; } // map from deviceid -> deviceinfo for this user var userStore = stored[userId]; var updated = _updateStoredDeviceKeysForUser( self._olmDevice, userId, userStore, res.device_keys[userId] ); if (!updated) { continue; } // update the session store var storage = {}; for (var deviceId in userStore) { if (!userStore.hasOwnProperty(deviceId)) { continue; } storage[deviceId] = userStore[deviceId].toStorage(); self._sessionStore.storeEndToEndDevicesForUser( userId, storage ); } } return stored; }); }; function _updateStoredDeviceKeysForUser(_olmDevice, userId, userStore, userResult) { var updated = false; // remove any devices in the store which aren't in the response for (var deviceId in userStore) { if (!userStore.hasOwnProperty(deviceId)) { continue; } if (!(deviceId in userResult)) { console.log("Device " + userId + ":" + deviceId + " has been removed"); delete userStore[deviceId]; updated = true; } } for (deviceId in userResult) { if (!userResult.hasOwnProperty(deviceId)) { continue; } if (_storeDeviceKeys( _olmDevice, userId, deviceId, userStore, userResult[deviceId] )) { updated = true; } } return updated; } /* * Process a device in a /query response, and add it to the userStore * * returns true if a change was made, else false */ function _storeDeviceKeys(_olmDevice, userId, deviceId, userStore, deviceResult) { if (!deviceResult.keys) { // no keys? return false; } var signKeyId = "ed25519:" + deviceId; var signKey = deviceResult.keys[signKeyId]; if (!signKey) { console.log("Device " + userId + ":" + deviceId + " has no ed25519 key"); return false; } var unsigned = deviceResult.unsigned || {}; var signatures = deviceResult.signatures || {}; var userSigs = signatures[userId] || {}; var signature = userSigs[signKeyId]; if (!signature) { console.log("Device " + userId + ":" + deviceId + " is not signed"); return false; } // prepare the canonical json: remove 'unsigned' and signatures, and // stringify with anotherjson delete deviceResult.unsigned; delete deviceResult.signatures; var json = anotherjson.stringify(deviceResult); try { _olmDevice.verifySignature(signKey, json, signature); } catch (e) { console.log("Unable to verify signature on device " + userId + ":" + deviceId + ":", e); return false; } // DeviceInfo var deviceStore; if (deviceId in userStore) { // already have this device. deviceStore = userStore[deviceId]; if (deviceStore.getFingerprint() != signKey) { // this should only happen if the list has been MITMed; we are // best off sticking with the original keys. // // Should we warn the user about it somehow? console.warn("Ed25519 key for device" + userId + ": " + deviceId + " has changed"); return false; } } else { userStore[deviceId] = deviceStore = new DeviceInfo(deviceId); } deviceStore.keys = deviceResult.keys || {}; deviceStore.algorithms = deviceResult.algorithms || []; deviceStore.unsigned = unsigned; return true; } /** * Get the stored device keys for a user id * * @param {string} userId the user to list keys for. * * @return {module:crypto/deviceinfo[]} list of devices */ Crypto.prototype.getStoredDevicesForUser = function(userId) { var devs = this._sessionStore.getEndToEndDevicesForUser(userId); if (!devs) { return []; } var res = []; for (var deviceId in devs) { if (devs.hasOwnProperty(deviceId)) { res.push(DeviceInfo.fromStorage(devs[deviceId], deviceId)); } } return res; }; /** * List the stored device keys for a user id * * @deprecated prefer {@link module:crypto#getStoredDevicesForUser} * * @param {string} userId the user to list keys for. * * @return {object[]} list of devices with "id", "verified", "blocked", * "key", and "display_name" parameters. */ Crypto.prototype.listDeviceKeys = function(userId) { var devices = this.getStoredDevicesForUser(userId); var result = []; for (var i = 0; i < devices.length; ++i) { var device = devices[i]; var ed25519Key = device.getFingerprint(); if (ed25519Key) { result.push({ id: device.deviceId, key: ed25519Key, verified: Boolean(device.isVerified()), blocked: Boolean(device.isBlocked()), display_name: device.getDisplayName(), }); } } // sort by deviceid result.sort(function(a, b) { if (a.deviceId < b.deviceId) { return -1; } if (a.deviceId > b.deviceId) { return 1; } return 0; }); return result; }; /** * Find a device by curve25519 identity key * * @param {string} userId owner of the device * @param {string} algorithm encryption algorithm * @param {string} sender_key curve25519 key to match * * @return {module:crypto/deviceinfo?} */ Crypto.prototype.getDeviceByIdentityKey = function(userId, algorithm, sender_key) { if ( algorithm !== olmlib.OLM_ALGORITHM && algorithm !== olmlib.MEGOLM_ALGORITHM ) { // we only deal in olm keys return null; } var devices = this._sessionStore.getEndToEndDevicesForUser(userId); if (!devices) { return null; } for (var deviceId in devices) { if (!devices.hasOwnProperty(deviceId)) { continue; } var device = devices[deviceId]; for (var keyId in device.keys) { if (!device.keys.hasOwnProperty(keyId)) { continue; } if (keyId.indexOf("curve25519:") !== 0) { continue; } var deviceKey = device.keys[keyId]; if (deviceKey == sender_key) { return DeviceInfo.fromStorage(device, deviceId); } } } // doesn't match a known device return null; }; /** * Update the blocked/verified state of the given device * * @param {string} userId owner of the device * @param {string} deviceId unique identifier for the device * * @param {?boolean} verified whether to mark the device as verified. Null to * leave unchanged. * * @param {?boolean} blocked whether to mark the device as blocked. Null to * leave unchanged. */ Crypto.prototype.setDeviceVerification = function(userId, deviceId, verified, blocked) { var devices = this._sessionStore.getEndToEndDevicesForUser(userId); if (!devices || !devices[deviceId]) { throw new Error("Unknown device " + userId + ":" + deviceId); } var dev = devices[deviceId]; var verificationStatus = dev.verified; if (verified) { verificationStatus = DeviceVerification.VERIFIED; } else if (verified !== null && verificationStatus == DeviceVerification.VERIFIED) { verificationStatus = DeviceVerification.UNVERIFIED; } if (blocked) { verificationStatus = DeviceVerification.BLOCKED; } else if (blocked !== null && verificationStatus == DeviceVerification.BLOCKED) { verificationStatus = DeviceVerification.UNVERIFIED; } if (dev.verified === verificationStatus) { return; } dev.verified = verificationStatus; this._sessionStore.storeEndToEndDevicesForUser(userId, devices); }; /** * Get information on the active olm sessions with a user *
* Returns a map from device id to an object with keys 'deviceIdKey' (the * device's curve25519 identity key) and 'sessions' (an array of objects in the * same format as that returned by * {@link module:crypto/OlmDevice#getSessionInfoForDevice}). *
* This method is provided for debugging purposes.
*
* @param {string} userId id of user to inspect
*
* @return {Object.