From a8641ef879904faf8f8de2c51bbea32c7b039522 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 3 Mar 2020 12:58:04 +0100 Subject: [PATCH 01/18] Split KeysBackup to several files. No other change. --- .../keysbackup/KeysBackupScenarioData.kt | 35 +++ .../crypto/keysbackup/KeysBackupTest.kt | 241 +++--------------- .../keysbackup/KeysBackupTestConstants.kt | 24 ++ .../crypto/keysbackup/KeysBackupTestHelper.kt | 182 +++++++++++++ .../keysbackup/PrepareKeysBackupDataResult.kt | 22 ++ 5 files changed, 296 insertions(+), 208 deletions(-) create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupScenarioData.kt create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestConstants.kt create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestHelper.kt create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupScenarioData.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupScenarioData.kt new file mode 100644 index 00000000000..f10f2fef0e4 --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupScenarioData.kt @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2020 New Vector 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. + */ + +package im.vector.matrix.android.internal.crypto.keysbackup + +import im.vector.matrix.android.api.session.Session +import im.vector.matrix.android.common.CommonTestHelper +import im.vector.matrix.android.common.CryptoTestData +import im.vector.matrix.android.internal.crypto.model.OlmInboundGroupSessionWrapper + +/** + * Data class to store result of [KeysBackupTestHelper.createKeysBackupScenarioWithPassword] + */ +data class KeysBackupScenarioData(val cryptoTestData: CryptoTestData, + val aliceKeys: List, + val prepareKeysBackupDataResult: PrepareKeysBackupDataResult, + val aliceSession2: Session) { + fun cleanUp(testHelper: CommonTestHelper) { + cryptoTestData.cleanUp(testHelper) + testHelper.signOutAndClose(aliceSession2) + } +} diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTest.kt index 3042a3c68f5..59ef24beec5 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTest.kt @@ -20,27 +20,19 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import im.vector.matrix.android.InstrumentedTest import im.vector.matrix.android.api.listeners.ProgressListener import im.vector.matrix.android.api.listeners.StepProgressListener -import im.vector.matrix.android.api.session.Session -import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupService import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupState import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupStateListener import im.vector.matrix.android.common.CommonTestHelper -import im.vector.matrix.android.common.CryptoTestData import im.vector.matrix.android.common.CryptoTestHelper -import im.vector.matrix.android.common.SessionTestParams import im.vector.matrix.android.common.TestConstants import im.vector.matrix.android.common.TestMatrixCallback -import im.vector.matrix.android.common.assertDictEquals -import im.vector.matrix.android.common.assertListEquals import im.vector.matrix.android.internal.crypto.MXCRYPTO_ALGORITHM_MEGOLM_BACKUP -import im.vector.matrix.android.internal.crypto.MegolmSessionData import im.vector.matrix.android.internal.crypto.crosssigning.DeviceTrustLevel import im.vector.matrix.android.internal.crypto.keysbackup.model.KeysBackupVersionTrust import im.vector.matrix.android.internal.crypto.keysbackup.model.MegolmBackupCreationInfo import im.vector.matrix.android.internal.crypto.keysbackup.model.rest.KeysVersion import im.vector.matrix.android.internal.crypto.keysbackup.model.rest.KeysVersionResult import im.vector.matrix.android.internal.crypto.model.ImportRoomKeysResult -import im.vector.matrix.android.internal.crypto.model.OlmInboundGroupSessionWrapper import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull @@ -61,9 +53,7 @@ class KeysBackupTest : InstrumentedTest { private val mTestHelper = CommonTestHelper(context()) private val mCryptoTestHelper = CryptoTestHelper(mTestHelper) - - private val defaultSessionParams = SessionTestParams(withInitialSync = false) - private val defaultSessionParamsWithInitialSync = SessionTestParams(withInitialSync = true) + private val mKeysBackupTestHelper = KeysBackupTestHelper(mTestHelper, mCryptoTestHelper) /** * - From doE2ETestWithAliceAndBobInARoomWithEncryptedMessages, we should have no backed up keys @@ -110,7 +100,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun prepareKeysBackupVersionTest() { - val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams) + val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) assertNotNull(bobSession.cryptoService().keysBackupService()) @@ -139,7 +129,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun createKeysBackupVersionTest() { - val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams) + val bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) val keysBackup = bobSession.cryptoService().keysBackupService() @@ -182,7 +172,7 @@ class KeysBackupTest : InstrumentedTest { val stateObserver = StateObserver(keysBackup, latch, 5) - prepareAndCreateKeysBackupData(keysBackup) + mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) mTestHelper.await(latch) @@ -216,7 +206,7 @@ class KeysBackupTest : InstrumentedTest { val stateObserver = StateObserver(keysBackup) - prepareAndCreateKeysBackupData(keysBackup) + mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) // Check that backupAllGroupSessions returns valid data val nbOfKeys = cryptoTestData.firstSession.cryptoService().inboundGroupSessionsCount(false) @@ -263,7 +253,7 @@ class KeysBackupTest : InstrumentedTest { // - Pick a megolm key val session = keysBackup.store.inboundGroupSessionsToBackup(1)[0] - val keyBackupCreationInfo = prepareAndCreateKeysBackupData(keysBackup).megolmBackupCreationInfo + val keyBackupCreationInfo = mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup).megolmBackupCreationInfo // - Check encryptGroupSession() returns stg val keyBackupData = keysBackup.encryptGroupSession(session) @@ -281,7 +271,7 @@ class KeysBackupTest : InstrumentedTest { decryption!!) assertNotNull(sessionData) // - Compare the decrypted megolm key with the original one - assertKeysEquals(session.exportKeys(), sessionData) + mKeysBackupTestHelper.assertKeysEquals(session.exportKeys(), sessionData) stateObserver.stopAndCheckStates(null) cryptoTestData.cleanUp(mTestHelper) @@ -295,7 +285,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun restoreKeysBackupTest() { - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // - Restore the e2e backup from the homeserver val importRoomKeysResult = mTestHelper.doSync { @@ -308,7 +298,7 @@ class KeysBackupTest : InstrumentedTest { ) } - checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) + mKeysBackupTestHelper.checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) testData.cleanUp(mTestHelper) } @@ -329,7 +319,7 @@ class KeysBackupTest : InstrumentedTest { // fun restoreKeysBackupAndKeyShareRequestTest() { // fail("Check with Valere for this test. I think we do not send key share request") // -// val testData = createKeysBackupScenarioWithPassword(null) +// val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // // // - Check the SDK sent key share requests // val cryptoStore2 = (testData.aliceSession2.cryptoService().keysBackupService() as DefaultKeysBackupService).store @@ -352,7 +342,7 @@ class KeysBackupTest : InstrumentedTest { // ) // } // -// checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) +// mKeysBackupTestHelper.checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) // // // - There must be no more pending key share requests // val unsentRequestAfterRestoration = cryptoStore2 @@ -380,7 +370,7 @@ class KeysBackupTest : InstrumentedTest { fun trustKeyBackupVersionTest() { // - Do an e2e backup to the homeserver with a recovery key // - And log Alice on a new device - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val stateObserver = StateObserver(testData.aliceSession2.cryptoService().keysBackupService()) @@ -399,7 +389,7 @@ class KeysBackupTest : InstrumentedTest { } // Wait for backup state to be ReadyToBackUp - waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) + mKeysBackupTestHelper.waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) // - Backup must be enabled on the new device, on the same version assertEquals(testData.prepareKeysBackupDataResult.version, testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion?.version) @@ -439,7 +429,7 @@ class KeysBackupTest : InstrumentedTest { fun trustKeyBackupVersionWithRecoveryKeyTest() { // - Do an e2e backup to the homeserver with a recovery key // - And log Alice on a new device - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val stateObserver = StateObserver(testData.aliceSession2.cryptoService().keysBackupService()) @@ -458,7 +448,7 @@ class KeysBackupTest : InstrumentedTest { } // Wait for backup state to be ReadyToBackUp - waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) + mKeysBackupTestHelper.waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) // - Backup must be enabled on the new device, on the same version assertEquals(testData.prepareKeysBackupDataResult.version, testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion?.version) @@ -496,7 +486,7 @@ class KeysBackupTest : InstrumentedTest { fun trustKeyBackupVersionWithWrongRecoveryKeyTest() { // - Do an e2e backup to the homeserver with a recovery key // - And log Alice on a new device - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) val stateObserver = StateObserver(testData.aliceSession2.cryptoService().keysBackupService()) @@ -539,7 +529,7 @@ class KeysBackupTest : InstrumentedTest { // - Do an e2e backup to the homeserver with a password // - And log Alice on a new device - val testData = createKeysBackupScenarioWithPassword(password) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(password) val stateObserver = StateObserver(testData.aliceSession2.cryptoService().keysBackupService()) @@ -558,7 +548,7 @@ class KeysBackupTest : InstrumentedTest { } // Wait for backup state to be ReadyToBackUp - waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) + mKeysBackupTestHelper.waitForKeysBackupToBeInState(testData.aliceSession2, KeysBackupState.ReadyToBackUp) // - Backup must be enabled on the new device, on the same version assertEquals(testData.prepareKeysBackupDataResult.version, testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion?.version) @@ -599,7 +589,7 @@ class KeysBackupTest : InstrumentedTest { // - Do an e2e backup to the homeserver with a password // - And log Alice on a new device - val testData = createKeysBackupScenarioWithPassword(password) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(password) val stateObserver = StateObserver(testData.aliceSession2.cryptoService().keysBackupService()) @@ -634,7 +624,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun restoreKeysBackupWithAWrongRecoveryKeyTest() { - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // - Try to restore the e2e backup with a wrong recovery key val latch2 = CountDownLatch(1) @@ -669,7 +659,7 @@ class KeysBackupTest : InstrumentedTest { fun testBackupWithPassword() { val password = "password" - val testData = createKeysBackupScenarioWithPassword(password) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(password) // - Restore the e2e backup with the password val steps = ArrayList() @@ -709,7 +699,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(50, (steps[103] as StepProgressListener.Step.ImportingKey).progress) assertEquals(100, (steps[104] as StepProgressListener.Step.ImportingKey).progress) - checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) + mKeysBackupTestHelper.checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) testData.cleanUp(mTestHelper) } @@ -725,7 +715,7 @@ class KeysBackupTest : InstrumentedTest { val password = "password" val wrongPassword = "passw0rd" - val testData = createKeysBackupScenarioWithPassword(password) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(password) // - Try to restore the e2e backup with a wrong password val latch2 = CountDownLatch(1) @@ -760,7 +750,7 @@ class KeysBackupTest : InstrumentedTest { fun testUseRecoveryKeyToRestoreAPasswordBasedKeysBackup() { val password = "password" - val testData = createKeysBackupScenarioWithPassword(password) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(password) // - Restore the e2e backup with the recovery key. val importRoomKeysResult = mTestHelper.doSync { @@ -773,7 +763,7 @@ class KeysBackupTest : InstrumentedTest { ) } - checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) + mKeysBackupTestHelper.checkRestoreSuccess(testData, importRoomKeysResult.totalNumberOfKeys, importRoomKeysResult.successfullyNumberOfImportedKeys) testData.cleanUp(mTestHelper) } @@ -786,7 +776,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun testUsePasswordToRestoreARecoveryKeyBasedKeysBackup() { - val testData = createKeysBackupScenarioWithPassword(null) + val testData = mKeysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // - Try to restore the e2e backup with a password val latch2 = CountDownLatch(1) @@ -825,7 +815,7 @@ class KeysBackupTest : InstrumentedTest { val stateObserver = StateObserver(keysBackup) // - Do an e2e backup to the homeserver - prepareAndCreateKeysBackupData(keysBackup) + mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) // Get key backup version from the home server val keysVersionResult = mTestHelper.doSync { @@ -870,13 +860,13 @@ class KeysBackupTest : InstrumentedTest { assertFalse(keysBackup.isEnabled) - val keyBackupCreationInfo = prepareAndCreateKeysBackupData(keysBackup) + val keyBackupCreationInfo = mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) assertTrue(keysBackup.isEnabled) // - Restart alice session // - Log Alice on a new device - val aliceSession2 = mTestHelper.logIntoAccount(cryptoTestData.firstSession.myUserId, defaultSessionParamsWithInitialSync) + val aliceSession2 = mTestHelper.logIntoAccount(cryptoTestData.firstSession.myUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync) cryptoTestData.cleanUp(mTestHelper) @@ -950,7 +940,7 @@ class KeysBackupTest : InstrumentedTest { }) // - Make alice back up her keys to her homeserver - prepareAndCreateKeysBackupData(keysBackup) + mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) assertTrue(keysBackup.isEnabled) @@ -1000,7 +990,7 @@ class KeysBackupTest : InstrumentedTest { val stateObserver = StateObserver(keysBackup) // - Make alice back up her keys to her homeserver - prepareAndCreateKeysBackupData(keysBackup) + mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) // Wait for keys backup to finish by asking again to backup keys. mTestHelper.doSync { @@ -1012,7 +1002,7 @@ class KeysBackupTest : InstrumentedTest { val aliceUserId = cryptoTestData.firstSession.myUserId // - Log Alice on a new device - val aliceSession2 = mTestHelper.logIntoAccount(aliceUserId, defaultSessionParamsWithInitialSync) + val aliceSession2 = mTestHelper.logIntoAccount(aliceUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync) // - Post a message to have a new megolm session aliceSession2.cryptoService().setWarnOnUnknownDevices(false) @@ -1093,7 +1083,7 @@ class KeysBackupTest : InstrumentedTest { assertFalse(keysBackup.isEnabled) - val keyBackupCreationInfo = prepareAndCreateKeysBackupData(keysBackup) + val keyBackupCreationInfo = mKeysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) assertTrue(keysBackup.isEnabled) @@ -1106,169 +1096,4 @@ class KeysBackupTest : InstrumentedTest { stateObserver.stopAndCheckStates(null) cryptoTestData.cleanUp(mTestHelper) } - - /* ========================================================================================== - * Private - * ========================================================================================== */ - - /** - * As KeysBackup is doing asynchronous call to update its internal state, this method help to wait for the - * KeysBackup object to be in the specified state - */ - private fun waitForKeysBackupToBeInState(session: Session, state: KeysBackupState) { - // If already in the wanted state, return - if (session.cryptoService().keysBackupService().state == state) { - return - } - - // Else observe state changes - val latch = CountDownLatch(1) - - session.cryptoService().keysBackupService().addListener(object : KeysBackupStateListener { - override fun onStateChange(newState: KeysBackupState) { - if (newState == state) { - session.cryptoService().keysBackupService().removeListener(this) - latch.countDown() - } - } - }) - - mTestHelper.await(latch) - } - - private data class PrepareKeysBackupDataResult(val megolmBackupCreationInfo: MegolmBackupCreationInfo, - val version: String) - - private fun prepareAndCreateKeysBackupData(keysBackup: KeysBackupService, - password: String? = null): PrepareKeysBackupDataResult { - val stateObserver = StateObserver(keysBackup) - - val megolmBackupCreationInfo = mTestHelper.doSync { - keysBackup.prepareKeysBackupVersion(password, null, it) - } - - assertNotNull(megolmBackupCreationInfo) - - assertFalse(keysBackup.isEnabled) - - // Create the version - val keysVersion = mTestHelper.doSync { - keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) - } - - assertNotNull(keysVersion.version) - - // Backup must be enable now - assertTrue(keysBackup.isEnabled) - - stateObserver.stopAndCheckStates(null) - return PrepareKeysBackupDataResult(megolmBackupCreationInfo, keysVersion.version!!) - } - - private fun assertKeysEquals(keys1: MegolmSessionData?, keys2: MegolmSessionData?) { - assertNotNull(keys1) - assertNotNull(keys2) - - assertEquals(keys1?.algorithm, keys2?.algorithm) - assertEquals(keys1?.roomId, keys2?.roomId) - // No need to compare the shortcut - // assertEquals(keys1?.sender_claimed_ed25519_key, keys2?.sender_claimed_ed25519_key) - assertEquals(keys1?.senderKey, keys2?.senderKey) - assertEquals(keys1?.sessionId, keys2?.sessionId) - assertEquals(keys1?.sessionKey, keys2?.sessionKey) - - assertListEquals(keys1?.forwardingCurve25519KeyChain, keys2?.forwardingCurve25519KeyChain) - assertDictEquals(keys1?.senderClaimedKeys, keys2?.senderClaimedKeys) - } - - /** - * Data class to store result of [createKeysBackupScenarioWithPassword] - */ - private data class KeysBackupScenarioData(val cryptoTestData: CryptoTestData, - val aliceKeys: List, - val prepareKeysBackupDataResult: PrepareKeysBackupDataResult, - val aliceSession2: Session) { - fun cleanUp(testHelper: CommonTestHelper) { - cryptoTestData.cleanUp(testHelper) - testHelper.signOutAndClose(aliceSession2) - } - } - - /** - * Common initial condition - * - Do an e2e backup to the homeserver - * - Log Alice on a new device, and wait for its keysBackup object to be ready (in state NotTrusted) - * - * @param password optional password - */ - private fun createKeysBackupScenarioWithPassword(password: String?): KeysBackupScenarioData { - val cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() - - val cryptoStore = (cryptoTestData.firstSession.cryptoService().keysBackupService() as DefaultKeysBackupService).store - val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService() - - val stateObserver = StateObserver(keysBackup) - - val aliceKeys = cryptoStore.inboundGroupSessionsToBackup(100) - - // - Do an e2e backup to the homeserver - val prepareKeysBackupDataResult = prepareAndCreateKeysBackupData(keysBackup, password) - - var lastProgress = 0 - var lastTotal = 0 - mTestHelper.doSync { - keysBackup.backupAllGroupSessions(object : ProgressListener { - override fun onProgress(progress: Int, total: Int) { - lastProgress = progress - lastTotal = total - } - }, it) - } - - assertEquals(2, lastProgress) - assertEquals(2, lastTotal) - - val aliceUserId = cryptoTestData.firstSession.myUserId - - // - Log Alice on a new device - val aliceSession2 = mTestHelper.logIntoAccount(aliceUserId, defaultSessionParamsWithInitialSync) - - // Test check: aliceSession2 has no keys at login - assertEquals(0, aliceSession2.cryptoService().inboundGroupSessionsCount(false)) - - // Wait for backup state to be NotTrusted - waitForKeysBackupToBeInState(aliceSession2, KeysBackupState.NotTrusted) - - stateObserver.stopAndCheckStates(null) - - return KeysBackupScenarioData(cryptoTestData, - aliceKeys, - prepareKeysBackupDataResult, - aliceSession2) - } - - /** - * Common restore success check after [createKeysBackupScenarioWithPassword]: - * - Imported keys number must be correct - * - The new device must have the same count of megolm keys - * - Alice must have the same keys on both devices - */ - private fun checkRestoreSuccess(testData: KeysBackupScenarioData, - total: Int, - imported: Int) { - // - Imported keys number must be correct - assertEquals(testData.aliceKeys.size, total) - assertEquals(total, imported) - - // - The new device must have the same count of megolm keys - assertEquals(testData.aliceKeys.size, testData.aliceSession2.cryptoService().inboundGroupSessionsCount(false)) - - // - Alice must have the same keys on both devices - for (aliceKey1 in testData.aliceKeys) { - val aliceKey2 = (testData.aliceSession2.cryptoService().keysBackupService() as DefaultKeysBackupService).store - .getInboundGroupSession(aliceKey1.olmInboundGroupSession!!.sessionIdentifier(), aliceKey1.senderKey!!) - assertNotNull(aliceKey2) - assertKeysEquals(aliceKey1.exportKeys(), aliceKey2!!.exportKeys()) - } - } } diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestConstants.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestConstants.kt new file mode 100644 index 00000000000..0f3a23df3f6 --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestConstants.kt @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2020 New Vector 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. + */ + +package im.vector.matrix.android.internal.crypto.keysbackup + +import im.vector.matrix.android.common.SessionTestParams + +object KeysBackupTestConstants { + val defaultSessionParams = SessionTestParams(withInitialSync = false) + val defaultSessionParamsWithInitialSync = SessionTestParams(withInitialSync = true) +} diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestHelper.kt new file mode 100644 index 00000000000..bb1436b8d44 --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/KeysBackupTestHelper.kt @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2020 New Vector 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. + */ + +package im.vector.matrix.android.internal.crypto.keysbackup + +import im.vector.matrix.android.api.listeners.ProgressListener +import im.vector.matrix.android.api.session.Session +import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupService +import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupState +import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupStateListener +import im.vector.matrix.android.common.CommonTestHelper +import im.vector.matrix.android.common.CryptoTestHelper +import im.vector.matrix.android.common.assertDictEquals +import im.vector.matrix.android.common.assertListEquals +import im.vector.matrix.android.internal.crypto.MegolmSessionData +import im.vector.matrix.android.internal.crypto.keysbackup.model.MegolmBackupCreationInfo +import im.vector.matrix.android.internal.crypto.keysbackup.model.rest.KeysVersion +import org.junit.Assert +import java.util.concurrent.CountDownLatch + +class KeysBackupTestHelper( + private val mTestHelper: CommonTestHelper, + private val mCryptoTestHelper: CryptoTestHelper) { + + /** + * Common initial condition + * - Do an e2e backup to the homeserver + * - Log Alice on a new device, and wait for its keysBackup object to be ready (in state NotTrusted) + * + * @param password optional password + */ + fun createKeysBackupScenarioWithPassword(password: String?): KeysBackupScenarioData { + val cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() + + val cryptoStore = (cryptoTestData.firstSession.cryptoService().keysBackupService() as DefaultKeysBackupService).store + val keysBackup = cryptoTestData.firstSession.cryptoService().keysBackupService() + + val stateObserver = StateObserver(keysBackup) + + val aliceKeys = cryptoStore.inboundGroupSessionsToBackup(100) + + // - Do an e2e backup to the homeserver + val prepareKeysBackupDataResult = prepareAndCreateKeysBackupData(keysBackup, password) + + var lastProgress = 0 + var lastTotal = 0 + mTestHelper.doSync { + keysBackup.backupAllGroupSessions(object : ProgressListener { + override fun onProgress(progress: Int, total: Int) { + lastProgress = progress + lastTotal = total + } + }, it) + } + + Assert.assertEquals(2, lastProgress) + Assert.assertEquals(2, lastTotal) + + val aliceUserId = cryptoTestData.firstSession.myUserId + + // - Log Alice on a new device + val aliceSession2 = mTestHelper.logIntoAccount(aliceUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync) + + // Test check: aliceSession2 has no keys at login + Assert.assertEquals(0, aliceSession2.cryptoService().inboundGroupSessionsCount(false)) + + // Wait for backup state to be NotTrusted + waitForKeysBackupToBeInState(aliceSession2, KeysBackupState.NotTrusted) + + stateObserver.stopAndCheckStates(null) + + return KeysBackupScenarioData(cryptoTestData, + aliceKeys, + prepareKeysBackupDataResult, + aliceSession2) + } + + fun prepareAndCreateKeysBackupData(keysBackup: KeysBackupService, + password: String? = null): PrepareKeysBackupDataResult { + val stateObserver = StateObserver(keysBackup) + + val megolmBackupCreationInfo = mTestHelper.doSync { + keysBackup.prepareKeysBackupVersion(password, null, it) + } + + Assert.assertNotNull(megolmBackupCreationInfo) + + Assert.assertFalse(keysBackup.isEnabled) + + // Create the version + val keysVersion = mTestHelper.doSync { + keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) + } + + Assert.assertNotNull(keysVersion.version) + + // Backup must be enable now + Assert.assertTrue(keysBackup.isEnabled) + + stateObserver.stopAndCheckStates(null) + return PrepareKeysBackupDataResult(megolmBackupCreationInfo, keysVersion.version!!) + } + + /** + * As KeysBackup is doing asynchronous call to update its internal state, this method help to wait for the + * KeysBackup object to be in the specified state + */ + fun waitForKeysBackupToBeInState(session: Session, state: KeysBackupState) { + // If already in the wanted state, return + if (session.cryptoService().keysBackupService().state == state) { + return + } + + // Else observe state changes + val latch = CountDownLatch(1) + + session.cryptoService().keysBackupService().addListener(object : KeysBackupStateListener { + override fun onStateChange(newState: KeysBackupState) { + if (newState == state) { + session.cryptoService().keysBackupService().removeListener(this) + latch.countDown() + } + } + }) + + mTestHelper.await(latch) + } + + fun assertKeysEquals(keys1: MegolmSessionData?, keys2: MegolmSessionData?) { + Assert.assertNotNull(keys1) + Assert.assertNotNull(keys2) + + Assert.assertEquals(keys1?.algorithm, keys2?.algorithm) + Assert.assertEquals(keys1?.roomId, keys2?.roomId) + // No need to compare the shortcut + // assertEquals(keys1?.sender_claimed_ed25519_key, keys2?.sender_claimed_ed25519_key) + Assert.assertEquals(keys1?.senderKey, keys2?.senderKey) + Assert.assertEquals(keys1?.sessionId, keys2?.sessionId) + Assert.assertEquals(keys1?.sessionKey, keys2?.sessionKey) + + assertListEquals(keys1?.forwardingCurve25519KeyChain, keys2?.forwardingCurve25519KeyChain) + assertDictEquals(keys1?.senderClaimedKeys, keys2?.senderClaimedKeys) + } + + /** + * Common restore success check after [KeysBackupTestHelper.createKeysBackupScenarioWithPassword]: + * - Imported keys number must be correct + * - The new device must have the same count of megolm keys + * - Alice must have the same keys on both devices + */ + fun checkRestoreSuccess(testData: KeysBackupScenarioData, + total: Int, + imported: Int) { + // - Imported keys number must be correct + Assert.assertEquals(testData.aliceKeys.size, total) + Assert.assertEquals(total, imported) + + // - The new device must have the same count of megolm keys + Assert.assertEquals(testData.aliceKeys.size, testData.aliceSession2.cryptoService().inboundGroupSessionsCount(false)) + + // - Alice must have the same keys on both devices + for (aliceKey1 in testData.aliceKeys) { + val aliceKey2 = (testData.aliceSession2.cryptoService().keysBackupService() as DefaultKeysBackupService).store + .getInboundGroupSession(aliceKey1.olmInboundGroupSession!!.sessionIdentifier(), aliceKey1.senderKey!!) + Assert.assertNotNull(aliceKey2) + assertKeysEquals(aliceKey1.exportKeys(), aliceKey2!!.exportKeys()) + } + } +} diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt new file mode 100644 index 00000000000..91d00cbe21e --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/keysbackup/PrepareKeysBackupDataResult.kt @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2020 New Vector 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. + */ + +package im.vector.matrix.android.internal.crypto.keysbackup + +import im.vector.matrix.android.internal.crypto.keysbackup.model.MegolmBackupCreationInfo + +data class PrepareKeysBackupDataResult(val megolmBackupCreationInfo: MegolmBackupCreationInfo, + val version: String) From 41a8f4024198cba55e93fd297bed406aac1b6509 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 3 Mar 2020 18:22:44 +0100 Subject: [PATCH 02/18] Improve API --- .../matrix/android/api/session/room/timeline/Timeline.kt | 1 + .../matrix/android/internal/crypto/store/IMXCryptoStore.kt | 2 +- .../android/internal/crypto/store/db/RealmCryptoStore.kt | 6 +----- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/room/timeline/Timeline.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/room/timeline/Timeline.kt index eb4a9b59e4b..d7d6682046f 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/room/timeline/Timeline.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/room/timeline/Timeline.kt @@ -104,6 +104,7 @@ interface Timeline { interface Listener { /** * Call when the timeline has been updated through pagination or sync. + * The latest event is the first in the list * @param snapshot the most up to date snapshot */ fun onTimelineUpdated(snapshot: List) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt index a8f65e9219f..c5a89b10e70 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt @@ -262,7 +262,7 @@ internal interface IMXCryptoStore { * @param deviceKey the public key of the other device. * @return The Base64 end-to-end session, or null if not found */ - fun getDeviceSession(sessionId: String?, deviceKey: String?): OlmSessionWrapper? + fun getDeviceSession(sessionId: String, deviceKey: String): OlmSessionWrapper? /** * Retrieve the last used sessionId, regarding `lastReceivedMessageTs`, or null if no session exist diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/db/RealmCryptoStore.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/db/RealmCryptoStore.kt index bd51cf8539f..a6f3f5d5930 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/db/RealmCryptoStore.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/db/RealmCryptoStore.kt @@ -555,11 +555,7 @@ internal class RealmCryptoStore @Inject constructor( } } - override fun getDeviceSession(sessionId: String?, deviceKey: String?): OlmSessionWrapper? { - if (sessionId == null || deviceKey == null) { - return null - } - + override fun getDeviceSession(sessionId: String, deviceKey: String): OlmSessionWrapper? { val key = OlmSessionEntity.createPrimaryKey(sessionId, deviceKey) // If not in cache (or not found), try to read it from realm From 0cb43eef51786867f855f5e4c8c9c1f4118664e5 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 3 Mar 2020 18:23:31 +0100 Subject: [PATCH 03/18] Add test for Unwedging (before implementing it) --- .idea/dictionaries/bmarty.xml | 1 + .../matrix/android/common/CryptoTestHelper.kt | 64 ++----- .../android/internal/crypto/UnwedgingTest.kt | 174 ++++++++++++++++++ .../internal/crypto/DefaultCryptoService.kt | 8 + 4 files changed, 202 insertions(+), 45 deletions(-) create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt diff --git a/.idea/dictionaries/bmarty.xml b/.idea/dictionaries/bmarty.xml index 7e9a9e1b035..1f93d1feeed 100644 --- a/.idea/dictionaries/bmarty.xml +++ b/.idea/dictionaries/bmarty.xml @@ -25,6 +25,7 @@ signup ssss threepid + unwedging \ No newline at end of file diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt index 826c70a63f6..1084dc423d0 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt @@ -22,6 +22,7 @@ import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.api.session.events.model.Event import im.vector.matrix.android.api.session.events.model.EventType import im.vector.matrix.android.api.session.events.model.toContent +import im.vector.matrix.android.api.session.room.Room import im.vector.matrix.android.api.session.room.model.Membership import im.vector.matrix.android.api.session.room.model.RoomSummary import im.vector.matrix.android.api.session.room.model.create.CreateRoomParams @@ -40,7 +41,6 @@ import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue import java.util.HashMap import java.util.concurrent.CountDownLatch @@ -140,62 +140,36 @@ class CryptoTestHelper(private val mTestHelper: CommonTestHelper) { * @return Alice, Bob and Sam session */ fun doE2ETestWithAliceAndBobAndSamInARoom(): CryptoTestData { - val statuses = HashMap() - val cryptoTestData = doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId val room = aliceSession.getRoom(aliceRoomId)!! - val samSession = mTestHelper.createAccount(TestConstants.USER_SAM, defaultSessionParams) - - val lock1 = CountDownLatch(2) - -// val samEventListener = object : MXEventListener() { -// override fun onNewRoom(roomId: String) { -// if (TextUtils.equals(roomId, aliceRoomId)) { -// if (!statuses.containsKey("onNewRoom")) { -// statuses["onNewRoom"] = "onNewRoom" -// lock1.countDown() -// } -// } -// } -// } -// -// samSession.dataHandler.addListener(samEventListener) - - room.invite(samSession.myUserId, null, object : TestMatrixCallback(lock1) { - override fun onSuccess(data: Unit) { - statuses["invite"] = "invite" - super.onSuccess(data) - } - }) - - mTestHelper.await(lock1) - - assertTrue(statuses.containsKey("invite") && statuses.containsKey("onNewRoom")) - -// samSession.dataHandler.removeListener(samEventListener) + val samSession = createSamAccountAndInviteToTheRoom(room) - val lock2 = CountDownLatch(1) + // wait the initial sync + SystemClock.sleep(1000) - samSession.joinRoom(aliceRoomId, null, object : TestMatrixCallback(lock2) { - override fun onSuccess(data: Unit) { - statuses["joinRoom"] = "joinRoom" - super.onSuccess(data) - } - }) + return CryptoTestData(aliceSession, aliceRoomId, cryptoTestData.secondSession, samSession) + } - mTestHelper.await(lock2) - assertTrue(statuses.containsKey("joinRoom")) + /** + * Create Sam account and invite him in the room. He will accept the invitation + * @Return Sam session + */ + fun createSamAccountAndInviteToTheRoom(room: Room): Session { + val samSession = mTestHelper.createAccount(TestConstants.USER_SAM, defaultSessionParams) - // wait the initial sync - SystemClock.sleep(1000) + mTestHelper.doSync { + room.invite(samSession.myUserId, null, it) + } -// samSession.dataHandler.removeListener(samEventListener) + mTestHelper.doSync { + samSession.joinRoom(room.roomId, null, it) + } - return CryptoTestData(aliceSession, aliceRoomId, cryptoTestData.secondSession, samSession) + return samSession } /** diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt new file mode 100644 index 00000000000..ce5873b4517 --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2020 New Vector 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. + */ + +package im.vector.matrix.android.internal.crypto + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import im.vector.matrix.android.InstrumentedTest +import im.vector.matrix.android.api.session.events.model.EventType +import im.vector.matrix.android.api.session.room.timeline.Timeline +import im.vector.matrix.android.api.session.room.timeline.TimelineEvent +import im.vector.matrix.android.api.session.room.timeline.TimelineSettings +import im.vector.matrix.android.common.CommonTestHelper +import im.vector.matrix.android.common.CryptoTestHelper +import org.amshove.kluent.shouldBe +import org.amshove.kluent.shouldBeEqualTo +import org.junit.Before +import org.junit.FixMethodOrder +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.MethodSorters +import java.util.concurrent.CountDownLatch + +/** + * Ref: + * - https://github.com/matrix-org/matrix-doc/pull/1719 + * - https://matrix.org/docs/spec/client_server/latest#recovering-from-undecryptable-messages + * - https://github.com/matrix-org/matrix-js-sdk/pull/780 + * - https://github.com/matrix-org/matrix-ios-sdk/pull/778 + * - https://github.com/matrix-org/matrix-ios-sdk/pull/784 + */ +@RunWith(AndroidJUnit4::class) +@FixMethodOrder(MethodSorters.JVM) +class UnwedgingTest : InstrumentedTest { + + private lateinit var messagesReceivedByBob: List + private val mTestHelper = CommonTestHelper(context()) + private val mCryptoTestHelper = CryptoTestHelper(mTestHelper) + + @Before + fun init() { + messagesReceivedByBob = emptyList() + } + + /** + * - Alice & Bob in a e2e room + * - Alice sends a 1st message with a 1st megolm session + * - Store the olm session between A&B devices + * - Alice sends a 2nd message with a 2nd megolm session + * - Simulate Alice using a backup of her OS and make her crypto state like after the first message + * - Alice sends a 3rd message with a 3rd megolm session but a wedged olm session + * + * What Bob must see: + * -> No issue with the 2 first messages + * -> The third event must fail to decrypt at first because Bob the olm session is wedged + * -> This is automatically fixed after SDKs restarted the olm session + */ + @Test + fun testUnwedging() { + val cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + + val aliceSession = cryptoTestData.firstSession + val aliceRoomId = cryptoTestData.roomId + val bobSession = cryptoTestData.secondSession!! + + val aliceCryptoStore = (aliceSession.cryptoService() as DefaultCryptoService).cryptoStoreForTesting + + bobSession.cryptoService().setWarnOnUnknownDevices(false) + + aliceSession.cryptoService().setWarnOnUnknownDevices(false) + + val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! + val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! + + val bobTimeline = roomFromBobPOV.createTimeline(null, TimelineSettings(20)) + bobTimeline.start() + + var latch = CountDownLatch(1) + var bobEventsListener = createEventListener(latch, 1) + bobTimeline.addListener(bobEventsListener) + messagesReceivedByBob = emptyList() + + // - Alice sends a 1st message with a 1st megolm session + roomFromAlicePOV.sendTextMessage("First message") + + // Wait for the message to be received by Bob + mTestHelper.await(latch) + bobTimeline.removeListener(bobEventsListener) + + messagesReceivedByBob.size shouldBe 1 + + // - Store the olm session between A&B devices + // Let us pickle our session with bob here so we can later unpickle it + // and wedge our session. + val sessionIdsForBob = aliceCryptoStore.getDeviceSessionIds(bobSession.cryptoService().getMyDevice().identityKey()!!) + sessionIdsForBob!!.size shouldBe 1 + val olmSession = aliceCryptoStore.getDeviceSession(sessionIdsForBob.first(), bobSession.cryptoService().getMyDevice().identityKey()!!)!! + + // Sam join the room + val samSession = mCryptoTestHelper.createSamAccountAndInviteToTheRoom(roomFromAlicePOV) + + latch = CountDownLatch(1) + bobEventsListener = createEventListener(latch, 2) + bobTimeline.addListener(bobEventsListener) + messagesReceivedByBob = emptyList() + + // - Alice sends a 2nd message with a 2nd megolm session + roomFromAlicePOV.sendTextMessage("Second message") + + // Wait for the message to be received by Bob + mTestHelper.await(latch) + bobTimeline.removeListener(bobEventsListener) + + messagesReceivedByBob.size shouldBe 2 + + // Let us wedge the session now. Set crypto state like after the first message + aliceCryptoStore.storeSession(olmSession, bobSession.cryptoService().getMyDevice().identityKey()!!) + + latch = CountDownLatch(1) + bobEventsListener = createEventListener(latch, 3) + bobTimeline.addListener(bobEventsListener) + messagesReceivedByBob = emptyList() + + // - Alice sends a 3rd message with a 3rd megolm session but a wedged olm session + roomFromAlicePOV.sendTextMessage("Third message") + + // Wait for the message to be received by Bob + mTestHelper.await(latch) + bobTimeline.removeListener(bobEventsListener) + + messagesReceivedByBob.size shouldBe 3 + + messagesReceivedByBob[0].root.getClearType() shouldBeEqualTo EventType.ENCRYPTED + messagesReceivedByBob[1].root.getClearType() shouldBeEqualTo EventType.MESSAGE + messagesReceivedByBob[2].root.getClearType() shouldBeEqualTo EventType.MESSAGE + + bobTimeline.dispose() + + cryptoTestData.cleanUp(mTestHelper) + mTestHelper.signOutAndClose(samSession) + } + + private fun createEventListener(latch: CountDownLatch, expectedNumberOfMessages: Int): Timeline.Listener { + return object : Timeline.Listener { + override fun onTimelineFailure(throwable: Throwable) { + // noop + } + + override fun onNewTimelineEvents(eventIds: List) { + // noop + } + + override fun onTimelineUpdated(snapshot: List) { + messagesReceivedByBob = snapshot.filter { it.root.type == EventType.ENCRYPTED } + + if (messagesReceivedByBob.size == expectedNumberOfMessages) { + latch.countDown() + } + } + } + } +} diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index aceead8ea02..61a072ece62 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -21,6 +21,7 @@ package im.vector.matrix.android.internal.crypto import android.content.Context import android.os.Handler import android.os.Looper +import androidx.annotation.VisibleForTesting import androidx.lifecycle.LiveData import com.squareup.moshi.Types import com.zhuinden.monarchy.Monarchy @@ -1192,4 +1193,11 @@ internal class DefaultCryptoService @Inject constructor( override fun getGossipingEventsTrail(): List { return cryptoStore.getGossipingEventsTrail() } + + /* ========================================================================================== + * For test only + * ========================================================================================== */ + + @VisibleForTesting + val cryptoStoreForTesting = cryptoStore } From 00c239bc4212e06133cf3537ee6c2b0c572b75f9 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Wed, 4 Mar 2020 12:15:13 +0100 Subject: [PATCH 04/18] cleanup --- .../java/im/vector/matrix/android/common/CryptoTestHelper.kt | 1 - .../matrix/android/internal/crypto/store/IMXCryptoStore.kt | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt index 1084dc423d0..9278bed9183 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CryptoTestHelper.kt @@ -41,7 +41,6 @@ import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull -import java.util.HashMap import java.util.concurrent.CountDownLatch class CryptoTestHelper(private val mTestHelper: CommonTestHelper) { diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt index c5a89b10e70..0d1026b69f9 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/store/IMXCryptoStore.kt @@ -196,7 +196,8 @@ internal interface IMXCryptoStore { */ fun storeUserDevices(userId: String, devices: Map?) - fun storeUserCrossSigningKeys(userId: String, masterKey: CryptoCrossSigningKey?, + fun storeUserCrossSigningKeys(userId: String, + masterKey: CryptoCrossSigningKey?, selfSigningKey: CryptoCrossSigningKey?, userSigningKey: CryptoCrossSigningKey?) From 590024501875723c1a988cbeaa6c67e6baa73eab Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 10 Mar 2020 11:42:02 +0100 Subject: [PATCH 05/18] Make the test fail before unwedging implementation --- .../android/internal/crypto/UnwedgingTest.kt | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt index ce5873b4517..4a28a779866 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt @@ -87,6 +87,26 @@ class UnwedgingTest : InstrumentedTest { val bobTimeline = roomFromBobPOV.createTimeline(null, TimelineSettings(20)) bobTimeline.start() + val bobFinalLatch = CountDownLatch(1) + val bobHasThreeDecryptedEventsListener = object : Timeline.Listener { + override fun onTimelineFailure(throwable: Throwable) { + // noop + } + + override fun onNewTimelineEvents(eventIds: List) { + // noop + } + + override fun onTimelineUpdated(snapshot: List) { + val decryptedEventReceivedByBob = snapshot.filter { it.root.getClearType() == EventType.MESSAGE } + if (decryptedEventReceivedByBob.size == 3) { + bobFinalLatch.countDown() + } + } + } + bobTimeline.addListener(bobHasThreeDecryptedEventsListener) + + var latch = CountDownLatch(1) var bobEventsListener = createEventListener(latch, 1) bobTimeline.addListener(bobEventsListener) @@ -146,6 +166,10 @@ class UnwedgingTest : InstrumentedTest { messagesReceivedByBob[1].root.getClearType() shouldBeEqualTo EventType.MESSAGE messagesReceivedByBob[2].root.getClearType() shouldBeEqualTo EventType.MESSAGE + // Wait for all the message to be decrypted by bob + mTestHelper.await(bobFinalLatch) + bobTimeline.removeListener(bobHasThreeDecryptedEventsListener) + bobTimeline.dispose() cryptoTestData.cleanUp(mTestHelper) From 7924ef207c19985f6a54c9357ca2c1b36d8fcb38 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 10 Mar 2020 16:00:31 +0100 Subject: [PATCH 06/18] Add Javadoc --- .../model/rest/ForwardedRoomKeyContent.kt | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/ForwardedRoomKeyContent.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/ForwardedRoomKeyContent.kt index cf8652352ce..ea5fb26d83b 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/ForwardedRoomKeyContent.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/ForwardedRoomKeyContent.kt @@ -20,28 +20,53 @@ import com.squareup.moshi.JsonClass /** * Class representing the forward room key request body content + * Ref: https://matrix.org/docs/spec/client_server/latest#m-forwarded-room-key */ @JsonClass(generateAdapter = true) data class ForwardedRoomKeyContent( - + /** + * Required. The encryption algorithm the key in this event is to be used with. + */ @Json(name = "algorithm") val algorithm: String? = null, + /** + * Required. The room where the key is used. + */ @Json(name = "room_id") val roomId: String? = null, + /** + * Required. The Curve25519 key of the device which initiated the session originally. + */ @Json(name = "sender_key") val senderKey: String? = null, + /** + * Required. The ID of the session that the key is for. + */ @Json(name = "session_id") val sessionId: String? = null, + /** + * Required. The key to be exchanged. + */ @Json(name = "session_key") val sessionKey: String? = null, + /** + * Required. Chain of Curve25519 keys. It starts out empty, but each time the key is forwarded to another device, + * the previous sender in the chain is added to the end of the list. For example, if the key is forwarded + * from A to B to C, this field is empty between A and B, and contains A's Curve25519 key between B and C. + */ @Json(name = "forwarding_curve25519_key_chain") val forwardingCurve25519KeyChain: List? = null, + /** + * Required. The Ed25519 key of the device which initiated the session originally. It is 'claimed' because the + * receiving device has no way to tell that the original room_key actually came from a device which owns the + * private part of this key unless they have done device verification. + */ @Json(name = "sender_claimed_ed25519_key") val senderClaimedEd25519Key: String? = null ) From a42eb421783f25651463be1b9c8326a1ccc334a6 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 10 Mar 2020 16:13:46 +0100 Subject: [PATCH 07/18] Avoid injecting Credentials --- .../crypto/actions/MessageEncrypter.kt | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt index fae205e581c..9961f40b9a5 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt @@ -16,19 +16,24 @@ package im.vector.matrix.android.internal.crypto.actions -import im.vector.matrix.android.api.auth.data.Credentials +import im.vector.matrix.android.api.session.events.model.Content import im.vector.matrix.android.internal.crypto.MXCRYPTO_ALGORITHM_OLM import im.vector.matrix.android.internal.crypto.MXOlmDevice import im.vector.matrix.android.internal.crypto.model.CryptoDeviceInfo import im.vector.matrix.android.internal.crypto.model.rest.EncryptedMessage +import im.vector.matrix.android.internal.di.DeviceId +import im.vector.matrix.android.internal.di.UserId import im.vector.matrix.android.internal.util.JsonCanonicalizer import im.vector.matrix.android.internal.util.convertToUTF8 import timber.log.Timber import javax.inject.Inject -internal class MessageEncrypter @Inject constructor(private val credentials: Credentials, - private val olmDevice: MXOlmDevice) { - +internal class MessageEncrypter @Inject constructor( + @UserId + private val userId: String, + @DeviceId + private val deviceId: String?, + private val olmDevice: MXOlmDevice) { /** * Encrypt an event payload for a list of devices. * This method must be called from the getCryptoHandler() thread. @@ -37,13 +42,13 @@ internal class MessageEncrypter @Inject constructor(private val credentials: Cre * @param deviceInfos list of device infos to encrypt for. * @return the content for an m.room.encrypted event. */ - fun encryptMessage(payloadFields: Map, deviceInfos: List): EncryptedMessage { + fun encryptMessage(payloadFields: Content, deviceInfos: List): EncryptedMessage { val deviceInfoParticipantKey = deviceInfos.associateBy { it.identityKey()!! } val payloadJson = payloadFields.toMutableMap() - payloadJson["sender"] = credentials.userId - payloadJson["sender_device"] = credentials.deviceId!! + payloadJson["sender"] = userId + payloadJson["sender_device"] = deviceId!! // Include the Ed25519 key so that the recipient knows what // device this message came from. From 13cd13a42fa89b39dcb56251344271c4e19ccdd2 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Thu, 16 Apr 2020 17:28:04 +0200 Subject: [PATCH 08/18] Create RoomEncryptorsStore --- .../internal/crypto/DefaultCryptoService.kt | 27 +++---------- .../internal/crypto/RoomEncryptorsStore.kt | 38 +++++++++++++++++++ .../algorithms/megolm/MXMegolmEncryption.kt | 2 +- 3 files changed, 45 insertions(+), 22 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index 61a072ece62..e37af45a73e 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -122,7 +122,8 @@ internal class DefaultCryptoService @Inject constructor( private val myDeviceInfoHolder: Lazy, // the crypto store private val cryptoStore: IMXCryptoStore, - + // Room encryptors store + private val roomEncryptorsStore: RoomEncryptorsStore, // Olm device private val olmDevice: MXOlmDevice, // Set of parameters used to configure/customize the end-to-end crypto. @@ -172,8 +173,6 @@ internal class DefaultCryptoService @Inject constructor( private val uiHandler = Handler(Looper.getMainLooper()) - // MXEncrypting instance for each room. - private val roomEncryptors: MutableMap = HashMap() private val isStarting = AtomicBoolean(false) private val isStarted = AtomicBoolean(false) @@ -512,9 +511,7 @@ internal class DefaultCryptoService @Inject constructor( else -> olmEncryptionFactory.create(roomId) } - synchronized(roomEncryptors) { - roomEncryptors.put(roomId, alg) - } + roomEncryptorsStore.put(roomId, alg) // if encryption was not previously enabled in this room, we will have been // ignoring new device events for these users so far. We may well have @@ -596,16 +593,12 @@ internal class DefaultCryptoService @Inject constructor( internalStart(false) } val userIds = getRoomUserIds(roomId) - var alg = synchronized(roomEncryptors) { - roomEncryptors[roomId] - } + var alg = roomEncryptorsStore.get(roomId) if (alg == null) { val algorithm = getEncryptionAlgorithm(roomId) if (algorithm != null) { if (setEncryptionInRoom(roomId, algorithm, false, userIds)) { - synchronized(roomEncryptors) { - alg = roomEncryptors[roomId] - } + alg = roomEncryptorsStore.get(roomId) } } } @@ -836,16 +829,8 @@ internal class DefaultCryptoService @Inject constructor( * @param event the membership event causing the change */ private fun onRoomMembershipEvent(roomId: String, event: Event) { - val alg: IMXEncrypting? + roomEncryptorsStore.get(roomId) ?: /* No encrypting in this room */ return - synchronized(roomEncryptors) { - alg = roomEncryptors[roomId] - } - - if (null == alg) { - // No encrypting in this room - return - } event.stateKey?.let { userId -> val roomMember: RoomMemberSummary? = event.content.toModel() val membership = roomMember?.membership diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt new file mode 100644 index 00000000000..3b74e621672 --- /dev/null +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2020 New Vector 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. + */ + +package im.vector.matrix.android.internal.crypto + +import im.vector.matrix.android.internal.crypto.algorithms.IMXEncrypting +import javax.inject.Inject + +internal class RoomEncryptorsStore @Inject constructor() { + + // MXEncrypting instance for each room. + private val roomEncryptors = mutableMapOf() + + fun put(roomId: String, alg: IMXEncrypting) { + synchronized(roomEncryptors) { + roomEncryptors.put(roomId, alg) + } + } + + fun get(roomId: String): IMXEncrypting? { + return synchronized(roomEncryptors) { + roomEncryptors[roomId] + } + } +} diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt index a2d21c4f89a..0ce2269bdee 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt @@ -40,7 +40,7 @@ import timber.log.Timber internal class MXMegolmEncryption( // The id of the room we will be sending to. - private var roomId: String, + private val roomId: String, private val olmDevice: MXOlmDevice, private val defaultKeysBackupService: DefaultKeysBackupService, private val cryptoStore: IMXCryptoStore, From 6186c22e0263cf2004a5200045edfe52b439edfc Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Fri, 17 Apr 2020 10:01:16 +0200 Subject: [PATCH 09/18] improve code --- .../android/internal/crypto/actions/MessageEncrypter.kt | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt index 9961f40b9a5..c1cdbe59f9b 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/MessageEncrypter.kt @@ -58,11 +58,9 @@ internal class MessageEncrypter @Inject constructor( // homeserver signed by the ed25519 key this proves that // the curve25519 key and the ed25519 key are owned by // the same device. - val keysMap = HashMap() - keysMap["ed25519"] = olmDevice.deviceEd25519Key!! - payloadJson["keys"] = keysMap + payloadJson["keys"] = mapOf("ed25519" to olmDevice.deviceEd25519Key!!) - val ciphertext = HashMap() + val ciphertext = mutableMapOf() for ((deviceKey, deviceInfo) in deviceInfoParticipantKey) { val sessionId = olmDevice.getSessionId(deviceKey) From 4d296ddc091ad339ce08d7d35cf09fad02f5490c Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Fri, 17 Apr 2020 17:26:57 +0200 Subject: [PATCH 10/18] Avoid injecting credentials --- .../internal/crypto/DefaultCryptoService.kt | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index e37af45a73e..537dfc3d411 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -28,7 +28,6 @@ import com.zhuinden.monarchy.Monarchy import dagger.Lazy import im.vector.matrix.android.api.MatrixCallback import im.vector.matrix.android.api.NoOpMatrixCallback -import im.vector.matrix.android.api.auth.data.Credentials import im.vector.matrix.android.api.crypto.MXCryptoConfig import im.vector.matrix.android.api.failure.Failure import im.vector.matrix.android.api.listeners.ProgressListener @@ -79,7 +78,9 @@ import im.vector.matrix.android.internal.crypto.verification.DefaultVerification import im.vector.matrix.android.internal.database.model.EventEntity import im.vector.matrix.android.internal.database.model.EventEntityFields import im.vector.matrix.android.internal.database.query.whereType +import im.vector.matrix.android.internal.di.DeviceId import im.vector.matrix.android.internal.di.MoshiProvider +import im.vector.matrix.android.internal.di.UserId import im.vector.matrix.android.internal.extensions.foldToCallback import im.vector.matrix.android.internal.session.SessionScope import im.vector.matrix.android.internal.session.room.membership.LoadRoomMembersTask @@ -117,8 +118,10 @@ import kotlin.math.max internal class DefaultCryptoService @Inject constructor( // Olm Manager private val olmManager: OlmManager, - // The credentials, - private val credentials: Credentials, + @UserId + private val userId: String, + @DeviceId + private val deviceId: String?, private val myDeviceInfoHolder: Lazy, // the crypto store private val cryptoStore: IMXCryptoStore, @@ -199,7 +202,7 @@ internal class DefaultCryptoService @Inject constructor( this.callback = object : MatrixCallback { override fun onSuccess(data: Unit) { // bg refresh of crypto device - downloadKeys(listOf(credentials.userId), true, NoOpMatrixCallback()) + downloadKeys(listOf(userId), true, NoOpMatrixCallback()) callback.onSuccess(data) } @@ -398,7 +401,7 @@ internal class DefaultCryptoService @Inject constructor( } /** - * Provides the device information for a device id and a user Id + * Provides the device information for a user id and a device Id * * @param userId the user id * @param deviceId the device id @@ -746,7 +749,7 @@ internal class DefaultCryptoService @Inject constructor( } // Was that sent by us? - if (event.senderId != credentials.userId) { + if (event.senderId != userId) { Timber.e("## GOSSIP onSecretSend() : Ignore secret from other user ${event.senderId}") return } @@ -1164,7 +1167,7 @@ internal class DefaultCryptoService @Inject constructor( * ========================================================================================== */ override fun toString(): String { - return "DefaultCryptoService of " + credentials.userId + " (" + credentials.deviceId + ")" + return "DefaultCryptoService of $userId ($deviceId)" } override fun getOutgoingRoomKeyRequest(): List { From f989eed8b0d1bd4e5b1a412342104d00c14ea869 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Mon, 20 Apr 2020 15:37:00 +0200 Subject: [PATCH 11/18] Use @Throws(MXCryptoError::class) --- .../internal/crypto/DefaultCryptoService.kt | 1 + .../android/internal/crypto/MXOlmDevice.kt | 4 ++-- .../crypto/algorithms/IMXDecrypting.kt | 2 ++ .../algorithms/megolm/MXMegolmDecryption.kt | 2 ++ .../crypto/algorithms/olm/MXOlmDecryption.kt | 1 + .../crypto/model/rest/DummyContent.kt | 22 +++++++++++++++++++ 6 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/DummyContent.kt diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index 537dfc3d411..a52ad40a6e2 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -661,6 +661,7 @@ internal class DefaultCryptoService @Inject constructor( * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack. * @return the MXEventDecryptionResult data, or null in case of error */ + @Throws(MXCryptoError::class) private fun internalDecryptEvent(event: Event, timeline: String): MXEventDecryptionResult { val eventContent = event.content if (eventContent == null) { diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt index 86f0768a7d0..0351c183ceb 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt @@ -625,6 +625,7 @@ internal class MXOlmDevice @Inject constructor( * @param senderKey the base64-encoded curve25519 key of the sender. * @return the decrypting result. Nil if the sessionId is unknown. */ + @Throws(MXCryptoError::class) fun decryptGroupMessage(body: String, roomId: String, timeline: String?, @@ -662,8 +663,7 @@ internal class MXOlmDevice @Inject constructor( adapter.fromJson(payloadString) } catch (e: Exception) { Timber.e("## decryptGroupMessage() : fails to parse the payload") - throw - MXCryptoError.Base(MXCryptoError.ErrorType.BAD_DECRYPTED_FORMAT, MXCryptoError.BAD_DECRYPTED_FORMAT_TEXT_REASON) + throw MXCryptoError.Base(MXCryptoError.ErrorType.BAD_DECRYPTED_FORMAT, MXCryptoError.BAD_DECRYPTED_FORMAT_TEXT_REASON) } return OlmDecryptionResult( diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXDecrypting.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXDecrypting.kt index e9176ad6d95..0babb738423 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXDecrypting.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXDecrypting.kt @@ -17,6 +17,7 @@ package im.vector.matrix.android.internal.crypto.algorithms +import im.vector.matrix.android.api.session.crypto.MXCryptoError import im.vector.matrix.android.api.session.events.model.Event import im.vector.matrix.android.internal.crypto.IncomingRoomKeyRequest import im.vector.matrix.android.internal.crypto.IncomingSecretShareRequest @@ -35,6 +36,7 @@ internal interface IMXDecrypting { * @param timeline the id of the timeline where the event is decrypted. It is used to prevent replay attack. * @return the decryption information, or an error */ + @Throws(MXCryptoError::class) fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult /** diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt index 1d7a2765fa2..3e7ce4df064 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt @@ -63,6 +63,7 @@ internal class MXMegolmDecryption(private val userId: String, */ private var pendingEvents: MutableMap>> = HashMap() + @Throws(MXCryptoError::class) override fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult { // If cross signing is enabled, we don't send request until the keys are trusted // There could be a race effect here when xsigning is enabled, we should ensure that keys was downloaded once @@ -70,6 +71,7 @@ internal class MXMegolmDecryption(private val userId: String, return decryptEvent(event, timeline, requestOnFail) } + @Throws(MXCryptoError::class) private fun decryptEvent(event: Event, timeline: String, requestKeysOnFail: Boolean): MXEventDecryptionResult { if (event.roomId.isNullOrBlank()) { throw MXCryptoError.Base(MXCryptoError.ErrorType.MISSING_FIELDS, MXCryptoError.MISSING_FIELDS_REASON) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt index 0a8ef3993b8..8ef527fa058 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt @@ -38,6 +38,7 @@ internal class MXOlmDecryption( private val userId: String) : IMXDecrypting { + @Throws(MXCryptoError::class) override fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult { val olmEventContent = event.content.toModel() ?: run { Timber.e("## decryptEvent() : bad event format") diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/DummyContent.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/DummyContent.kt new file mode 100644 index 00000000000..b52354768db --- /dev/null +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/rest/DummyContent.kt @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2020 New Vector 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. + */ +package im.vector.matrix.android.internal.crypto.model.rest + +/** + * Class representing the dummy content + * Ref: https://matrix.org/docs/spec/client_server/latest#id82 + */ +typealias DummyContent = Unit From 91cf4b647d362e756fe309c577f289a46919d961 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Mon, 20 Apr 2020 15:37:23 +0200 Subject: [PATCH 12/18] var -> val --- .../android/internal/crypto/algorithms/olm/MXOlmEncryption.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt index 899e884e0d3..b3d26df8297 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt @@ -29,7 +29,7 @@ import im.vector.matrix.android.internal.crypto.model.CryptoDeviceInfo import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore internal class MXOlmEncryption( - private var roomId: String, + private val roomId: String, private val olmDevice: MXOlmDevice, private val cryptoStore: IMXCryptoStore, private val messageEncrypter: MessageEncrypter, From ddb00ba23a7d95e03d4026d8091fdb77ede45782 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Mon, 20 Apr 2020 15:55:26 +0200 Subject: [PATCH 13/18] Enable Timber log in integration tests --- .../java/im/vector/matrix/android/common/CommonTestHelper.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt index 3cf03fff53a..965255e0450 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt @@ -44,6 +44,7 @@ import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue +import timber.log.Timber import java.util.ArrayList import java.util.UUID import java.util.concurrent.CountDownLatch @@ -58,6 +59,8 @@ class CommonTestHelper(context: Context) { val matrix: Matrix init { + Timber.plant(Timber.DebugTree()) + Matrix.initialize(context, MatrixConfiguration("TestFlavor")) matrix = Matrix.getInstance(context) From 3615ca6b95def9adb37e652a451adc3f1b9a8de7 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Mon, 20 Apr 2020 16:02:29 +0200 Subject: [PATCH 14/18] VersionName can be null when running integration test --- .../vector/matrix/android/internal/network/UserAgentHolder.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/UserAgentHolder.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/UserAgentHolder.kt index 0f3da0c834d..15c91a629ac 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/UserAgentHolder.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/UserAgentHolder.kt @@ -51,7 +51,7 @@ internal class UserAgentHolder @Inject constructor(private val context: Context, appName = pm.getApplicationLabel(appInfo).toString() val pkgInfo = pm.getPackageInfo(context.applicationContext.packageName, 0) - appVersion = pkgInfo.versionName + appVersion = pkgInfo.versionName ?: "" // Use appPackageName instead of appName if appName contains any non-ASCII character if (!appName.matches("\\A\\p{ASCII}*\\z".toRegex())) { From a6368c473e57e6d92aaa24bb4ae4ad7294d81e3d Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Mon, 20 Apr 2020 17:44:45 +0200 Subject: [PATCH 15/18] Restart broken Olm sessions ([MSC1719](https://github.com/matrix-org/matrix-doc/pull/1719)) --- CHANGES.md | 1 + .../android/internal/crypto/UnwedgingTest.kt | 6 ++- .../api/session/events/model/EventType.kt | 3 ++ .../internal/crypto/DefaultCryptoService.kt | 52 +++++++++++++++++- .../crypto/IncomingGossipingRequestManager.kt | 53 +++++++++++++++---- .../internal/crypto/RoomEncryptorsStore.kt | 2 + .../EnsureOlmSessionsForDevicesAction.kt | 11 ++-- .../crypto/algorithms/IMXEncrypting.kt | 16 ++++++ .../algorithms/megolm/MXMegolmDecryption.kt | 22 ++++++++ .../algorithms/megolm/MXMegolmEncryption.kt | 45 ++++++++++++++++ .../crypto/algorithms/olm/MXOlmEncryption.kt | 5 ++ .../model/OlmInboundGroupSessionWrapper.kt | 7 ++- 12 files changed, 202 insertions(+), 21 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0c1d209f614..dc5d6f4a962 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -22,6 +22,7 @@ Improvements 🙌: - Emoji Verification | It's not the same butterfly! (#1220) - Cross-Signing | Composer decoration: shields (#1077) - Cross-Signing | Migrate existing keybackup to cross signing with 4S from mobile (#1197) + - Restart broken Olm sessions ([MSC1719](https://github.com/matrix-org/matrix-doc/pull/1719)) Bugfix 🐛: - Fix summary notification staying after "mark as read" diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt index 4a28a779866..123c8a5c88c 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt @@ -27,10 +27,12 @@ import im.vector.matrix.android.common.CryptoTestHelper import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeEqualTo import org.junit.Before +import org.junit.BeforeClass import org.junit.FixMethodOrder import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters +import timber.log.Timber import java.util.concurrent.CountDownLatch /** @@ -99,13 +101,13 @@ class UnwedgingTest : InstrumentedTest { override fun onTimelineUpdated(snapshot: List) { val decryptedEventReceivedByBob = snapshot.filter { it.root.getClearType() == EventType.MESSAGE } + Timber.d("Bob can now decrypt ${decryptedEventReceivedByBob.size} messages") if (decryptedEventReceivedByBob.size == 3) { bobFinalLatch.countDown() } } } bobTimeline.addListener(bobHasThreeDecryptedEventsListener) - var latch = CountDownLatch(1) var bobEventsListener = createEventListener(latch, 1) @@ -128,7 +130,7 @@ class UnwedgingTest : InstrumentedTest { sessionIdsForBob!!.size shouldBe 1 val olmSession = aliceCryptoStore.getDeviceSession(sessionIdsForBob.first(), bobSession.cryptoService().getMyDevice().identityKey()!!)!! - // Sam join the room + // Sam join the room, so it will force a new session creation val samSession = mCryptoTestHelper.createSamAccountAndInviteToTheRoom(roomFromAlicePOV) latch = CountDownLatch(1) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/EventType.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/EventType.kt index 9a3107a8cae..3cdd4335169 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/EventType.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/events/model/EventType.kt @@ -81,6 +81,9 @@ object EventType { // Relation Events const val REACTION = "m.reaction" + // Unwedging + internal const val DUMMY = "m.dummy" + private val STATE_EVENTS = listOf( STATE_ROOM_NAME, STATE_ROOM_TOPIC, diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index a52ad40a6e2..476af38ce78 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -48,6 +48,7 @@ import im.vector.matrix.android.api.session.room.model.RoomMemberSummary import im.vector.matrix.android.internal.crypto.actions.MegolmSessionDataImporter import im.vector.matrix.android.internal.crypto.actions.SetDeviceVerificationAction import im.vector.matrix.android.internal.crypto.algorithms.IMXEncrypting +import im.vector.matrix.android.internal.crypto.algorithms.megolm.MXMegolmDecryption import im.vector.matrix.android.internal.crypto.algorithms.megolm.MXMegolmEncryptionFactory import im.vector.matrix.android.internal.crypto.algorithms.olm.MXOlmEncryptionFactory import im.vector.matrix.android.internal.crypto.crosssigning.DefaultCrossSigningService @@ -179,6 +180,10 @@ internal class DefaultCryptoService @Inject constructor( private val isStarting = AtomicBoolean(false) private val isStarted = AtomicBoolean(false) + // The date of the last time we forced establishment + // of a new session for each user:device. + private val lastNewSessionForcedDates = MXUsersDevicesMap() + fun onStateEvent(roomId: String, event: Event) { when { event.getClearType() == EventType.STATE_ROOM_ENCRYPTION -> onRoomEncryptionEvent(roomId, event) @@ -675,11 +680,52 @@ internal class DefaultCryptoService @Inject constructor( Timber.e("## decryptEvent() : $reason") throw MXCryptoError.Base(MXCryptoError.ErrorType.UNABLE_TO_DECRYPT, reason) } else { - return alg.decryptEvent(event, timeline) + try { + return alg.decryptEvent(event, timeline) + } catch (mxCryptoError: MXCryptoError) { + if (mxCryptoError is MXCryptoError.Base + && mxCryptoError.errorType == MXCryptoError.ErrorType.BAD_ENCRYPTED_MESSAGE + && alg is MXMegolmDecryption) { + // TODO Do it on decryption thread like on iOS? + markOlmSessionForUnwedging(event, alg) + } + throw mxCryptoError + } } } } + private fun markOlmSessionForUnwedging(event: Event, mxMegolmDecryption: MXMegolmDecryption) { + val senderId = event.senderId ?: return + val encryptedMessage = event.content.toModel() ?: return + val deviceKey = encryptedMessage.senderKey ?: return + encryptedMessage.algorithm?.takeIf { it == MXCRYPTO_ALGORITHM_MEGOLM } ?: return + + if (senderId == userId + && deviceKey == olmDevice.deviceCurve25519Key) { + Timber.d("[MXCrypto] markOlmSessionForUnwedging: Do not unwedge ourselves") + return + } + + val lastForcedDate = lastNewSessionForcedDates.getObject(senderId, deviceKey) ?: 0 + val now = System.currentTimeMillis() + if (now - lastForcedDate < CRYPTO_MIN_FORCE_SESSION_PERIOD_MILLIS) { + Timber.d("[MXCrypto] markOlmSessionForUnwedging: New session already forced with device at $lastForcedDate. Not forcing another") + return + } + + // Establish a new olm session with this device since we're failing to decrypt messages + // on a current session. + val deviceInfo = getDeviceInfo(senderId, deviceKey) ?: return Unit.also { + Timber.d("[MXCrypto] markOlmSessionForUnwedging: Couldn't find device for identity key $deviceKey: not re-establishing session") + } + + Timber.d("[MXCrypto] markOlmSessionForUnwedging from $senderId:${deviceInfo.deviceId}") + lastNewSessionForcedDates.setObject(senderId, deviceKey, now) + + mxMegolmDecryption.markOlmSessionForUnwedging(senderId, deviceInfo) + } + /** * Reset replay attack data for the given timeline. * @@ -1189,4 +1235,8 @@ internal class DefaultCryptoService @Inject constructor( @VisibleForTesting val cryptoStoreForTesting = cryptoStore + + companion object { + const val CRYPTO_MIN_FORCE_SESSION_PERIOD_MILLIS = 3_600_000 // one hour + } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt index da596960dde..b17143d93d6 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt @@ -32,7 +32,10 @@ import im.vector.matrix.android.internal.crypto.model.rest.GossipingToDeviceObje import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.di.SessionId import im.vector.matrix.android.internal.session.SessionScope +import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers import im.vector.matrix.android.internal.worker.WorkerParamsFactory +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject @@ -43,7 +46,10 @@ internal class IncomingGossipingRequestManager @Inject constructor( private val cryptoStore: IMXCryptoStore, private val cryptoConfig: MXCryptoConfig, private val gossipingWorkManager: GossipingWorkManager, - private val roomDecryptorProvider: RoomDecryptorProvider) { + private val roomEncryptorsStore: RoomEncryptorsStore, + private val roomDecryptorProvider: RoomDecryptorProvider, + private val coroutineDispatchers: MatrixCoroutineDispatchers, + private val cryptoCoroutineScope: CoroutineScope) { // list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations // we received in the current sync. @@ -178,17 +184,42 @@ internal class IncomingGossipingRequestManager @Inject constructor( } private fun processIncomingRoomKeyRequest(request: IncomingRoomKeyRequest) { - val userId = request.userId - val deviceId = request.deviceId - val body = request.requestBody - val roomId = body!!.roomId - val alg = body.algorithm + val userId = request.userId ?: return + val deviceId = request.deviceId ?: return + val body = request.requestBody ?: return + val roomId = body.roomId ?: return + val alg = body.algorithm ?: return Timber.v("## GOSSIP processIncomingRoomKeyRequest from $userId:$deviceId for $roomId / ${body.sessionId} id ${request.requestId}") - if (userId == null || credentials.userId != userId) { - // TODO: determine if we sent this device the keys already: in - Timber.w("## GOSSIP processReceivedGossipingRequests() : Ignoring room key request from other user for now") - cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) + if (credentials.userId != userId) { + Timber.w("## GOSSIP processReceivedGossipingRequests() : room key request from other user") + val senderKey = body.senderKey ?: return Unit + .also { Timber.w("missing senderKey") } + .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } + val sessionId = body.sessionId ?: return Unit + .also { Timber.w("missing sessionId") } + .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } + + if (alg != MXCRYPTO_ALGORITHM_MEGOLM) { + return Unit + .also { Timber.w("Only megolm is accepted here") } + .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } + } + + val roomEncryptor = roomEncryptorsStore.get(roomId) ?: return Unit + .also { Timber.w("no room Encryptor") } + .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } + + cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { + val isSuccess = roomEncryptor.reshareKey(sessionId, userId, deviceId, senderKey) + + if (isSuccess) { + cryptoStore.updateGossipingRequestState(request, GossipingRequestState.ACCEPTED) + } else { + cryptoStore.updateGossipingRequestState(request, GossipingRequestState.UNABLE_TO_PROCESS) + } + } + cryptoStore.updateGossipingRequestState(request, GossipingRequestState.RE_REQUESTED) return } // TODO: should we queue up requests we don't yet have keys for, in case they turn up later? @@ -219,7 +250,7 @@ internal class IncomingGossipingRequestManager @Inject constructor( cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } // if the device is verified already, share the keys - val device = cryptoStore.getUserDevice(userId, deviceId!!) + val device = cryptoStore.getUserDevice(userId, deviceId) if (device != null) { if (device.isVerified) { Timber.v("## GOSSIP processReceivedGossipingRequests() : device is already verified: sharing keys") diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt index 3b74e621672..52a324d68d8 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/RoomEncryptorsStore.kt @@ -17,8 +17,10 @@ package im.vector.matrix.android.internal.crypto import im.vector.matrix.android.internal.crypto.algorithms.IMXEncrypting +import im.vector.matrix.android.internal.session.SessionScope import javax.inject.Inject +@SessionScope internal class RoomEncryptorsStore @Inject constructor() { // MXEncrypting instance for each room. diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt index e1cac0d75fd..d856331189f 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt @@ -25,10 +25,11 @@ import im.vector.matrix.android.internal.crypto.tasks.ClaimOneTimeKeysForUsersDe import timber.log.Timber import javax.inject.Inject -internal class EnsureOlmSessionsForDevicesAction @Inject constructor(private val olmDevice: MXOlmDevice, - private val oneTimeKeysForUsersDeviceTask: ClaimOneTimeKeysForUsersDeviceTask) { +internal class EnsureOlmSessionsForDevicesAction @Inject constructor( + private val olmDevice: MXOlmDevice, + private val oneTimeKeysForUsersDeviceTask: ClaimOneTimeKeysForUsersDeviceTask) { - suspend fun handle(devicesByUser: Map>): MXUsersDevicesMap { + suspend fun handle(devicesByUser: Map>, force: Boolean = false): MXUsersDevicesMap { val devicesWithoutSession = ArrayList() val results = MXUsersDevicesMap() @@ -40,7 +41,7 @@ internal class EnsureOlmSessionsForDevicesAction @Inject constructor(private val val sessionId = olmDevice.getSessionId(key!!) - if (sessionId.isNullOrEmpty()) { + if (sessionId.isNullOrEmpty() || force) { devicesWithoutSession.add(deviceInfo) } @@ -80,7 +81,7 @@ internal class EnsureOlmSessionsForDevicesAction @Inject constructor(private val if (null != deviceIds) { for (deviceId in deviceIds) { val olmSessionResult = results.getObject(userId, deviceId) - if (olmSessionResult!!.sessionId != null) { + if (olmSessionResult!!.sessionId != null && !force) { // We already have a result for this device continue } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt index 555ce9dfd44..65119362bc2 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt @@ -33,4 +33,20 @@ internal interface IMXEncrypting { * @return the encrypted content */ suspend fun encryptEventContent(eventContent: Content, eventType: String, userIds: List): Content + + /** + * Re-shares a session key with devices if the key has already been + * sent to them. + * + * @param sessionId The id of the outbound session to share. + * @param userId The id of the user who owns the target device. + * @param deviceId The id of the target device. + * @param senderKey The key of the originating device for the session. + * + * @return true in case of success + */ + suspend fun reshareKey(sessionId: String, + userId: String, + deviceId: String, + senderKey: String): Boolean } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt index 3e7ce4df064..815a4f7d125 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt @@ -31,6 +31,7 @@ import im.vector.matrix.android.internal.crypto.actions.EnsureOlmSessionsForDevi import im.vector.matrix.android.internal.crypto.actions.MessageEncrypter import im.vector.matrix.android.internal.crypto.algorithms.IMXDecrypting import im.vector.matrix.android.internal.crypto.keysbackup.DefaultKeysBackupService +import im.vector.matrix.android.internal.crypto.model.CryptoDeviceInfo import im.vector.matrix.android.internal.crypto.model.MXUsersDevicesMap import im.vector.matrix.android.internal.crypto.model.event.EncryptedEventContent import im.vector.matrix.android.internal.crypto.model.event.RoomKeyContent @@ -346,4 +347,25 @@ internal class MXMegolmDecryption(private val userId: String, } } } + + fun markOlmSessionForUnwedging(senderId: String, deviceInfo: CryptoDeviceInfo) { + cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { + ensureOlmSessionsForDevicesAction.handle(mapOf(senderId to listOf(deviceInfo)), force = true) + + // Now send a blank message on that session so the other side knows about it. + // (The keyshare request is sent in the clear so that won't do) + // We send this first such that, as long as the toDevice messages arrive in the + // same order we sent them, the other end will get this first, set up the new session, + // then get the keyshare request and send the key over this new session (because it + // is the session it has most recently received a message on). + val payloadJson = mapOf("type" to EventType.DUMMY) + + val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo)) + val sendToDeviceMap = MXUsersDevicesMap() + sendToDeviceMap.setObject(senderId, deviceInfo.deviceId, encodedPayload) + Timber.v("## markOlmSessionForUnwedging() : sending to $senderId:${deviceInfo.deviceId}") + val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap) + sendToDeviceTask.execute(sendToDeviceParams) + } + } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt index 0ce2269bdee..addb8c2f76c 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt @@ -305,4 +305,49 @@ internal class MXMegolmEncryption( throw MXCryptoError.UnknownDevice(unknownDevices) } } + + override suspend fun reshareKey(sessionId: String, + userId: String, + deviceId: String, + senderKey: String): Boolean { + Timber.d("[MXMegolmEncryption] reshareKey: $sessionId to $userId:$deviceId") + val deviceInfo = cryptoStore.getUserDevice(userId, deviceId) ?: return false + .also { Timber.w("Device not found") } + + // Get the chain index of the key we previously sent this device + val chainIndex = outboundSession?.sharedWithDevices?.getObject(userId, deviceId)?.toLong() ?: return false + .also { Timber.w("[MXMegolmEncryption] reshareKey : ERROR : Never share megolm with this device") } + + val devicesByUser = mapOf(userId to listOf(deviceInfo)) + val usersDeviceMap = ensureOlmSessionsForDevicesAction.handle(devicesByUser) + val olmSessionResult = usersDeviceMap.getObject(userId, deviceId) + olmSessionResult?.sessionId + ?: // no session with this device, probably because there were no one-time keys. + // ensureOlmSessionsForDevicesAction has already done the logging, so just skip it. + return false + + Timber.d("[MXMegolmEncryption] reshareKey: sharing keys for session $senderKey|$sessionId:$chainIndex with device $userId:$deviceId") + + val payloadJson = mutableMapOf("type" to EventType.FORWARDED_ROOM_KEY) + + runCatching { olmDevice.getInboundGroupSession(sessionId, senderKey, roomId) } + .fold( + { + // TODO + payloadJson["content"] = it.exportKeys(chainIndex) ?: "" + }, + { + // TODO + } + + ) + + val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo)) + val sendToDeviceMap = MXUsersDevicesMap() + sendToDeviceMap.setObject(userId, deviceId, encodedPayload) + Timber.v("## shareKeysWithDevice() : sending to $userId:$deviceId") + val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap) + sendToDeviceTask.execute(sendToDeviceParams) + return true + } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt index b3d26df8297..b1181fc067e 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt @@ -78,4 +78,9 @@ internal class MXOlmEncryption( deviceListManager.downloadKeys(users, false) ensureOlmSessionsForUsersAction.handle(users) } + + override suspend fun reshareKey(sessionId: String, userId: String, deviceId: String, senderKey: String): Boolean { + // No need for olm + return false + } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/OlmInboundGroupSessionWrapper.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/OlmInboundGroupSessionWrapper.kt index cf1a3b237af..9be08d9f2d2 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/OlmInboundGroupSessionWrapper.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/OlmInboundGroupSessionWrapper.kt @@ -103,10 +103,11 @@ class OlmInboundGroupSessionWrapper : Serializable { /** * Export the inbound group session keys + * @param index the index to export. If null, the first known index will be used * * @return the inbound group session as MegolmSessionData if the operation succeeds */ - fun exportKeys(): MegolmSessionData? { + fun exportKeys(index: Long? = null): MegolmSessionData? { return try { if (null == forwardingCurve25519KeyChain) { forwardingCurve25519KeyChain = ArrayList() @@ -116,6 +117,8 @@ class OlmInboundGroupSessionWrapper : Serializable { return null } + val wantedIndex = index ?: olmInboundGroupSession!!.firstKnownIndex + MegolmSessionData( senderClaimedEd25519Key = keysClaimed?.get("ed25519"), forwardingCurve25519KeyChain = ArrayList(forwardingCurve25519KeyChain!!), @@ -123,7 +126,7 @@ class OlmInboundGroupSessionWrapper : Serializable { senderClaimedKeys = keysClaimed, roomId = roomId, sessionId = olmInboundGroupSession!!.sessionIdentifier(), - sessionKey = olmInboundGroupSession!!.export(olmInboundGroupSession!!.firstKnownIndex), + sessionKey = olmInboundGroupSession!!.export(wantedIndex), algorithm = MXCRYPTO_ALGORITHM_MEGOLM ) } catch (e: Exception) { From 9b320ed3c78de5590e96785c8100325eddff962f Mon Sep 17 00:00:00 2001 From: Valere Date: Wed, 22 Apr 2020 15:40:59 +0200 Subject: [PATCH 16/18] Fix unwedging --- .../android/internal/crypto/UnwedgingTest.kt | 92 +++++++--- .../api/session/crypto/CryptoService.kt | 2 + .../internal/crypto/DefaultCryptoService.kt | 167 +++++++++++------- .../internal/crypto/DeviceListManager.kt | 58 +++--- .../crypto/IncomingGossipingRequestManager.kt | 42 ++--- .../android/internal/crypto/MXOlmDevice.kt | 2 + .../crypto/OutgoingGossipingRequestManager.kt | 10 +- .../EnsureOlmSessionsForDevicesAction.kt | 12 +- .../crypto/algorithms/IMXEncrypting.kt | 14 ++ .../algorithms/megolm/MXMegolmDecryption.kt | 45 ++--- .../algorithms/megolm/MXMegolmEncryption.kt | 27 ++- .../crypto/algorithms/olm/MXOlmEncryption.kt | 4 + .../session/sync/CryptoSyncHandler.kt | 14 +- .../vector/riotx/features/command/Command.kt | 1 + .../riotx/features/command/CommandParser.kt | 3 + .../riotx/features/command/ParsedCommand.kt | 1 + .../home/room/detail/RoomDetailViewModel.kt | 3 + vector/src/main/res/values/strings_riotX.xml | 2 +- 18 files changed, 304 insertions(+), 195 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt index 123c8a5c88c..7f75d7d6fd8 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt @@ -18,20 +18,29 @@ package im.vector.matrix.android.internal.crypto import androidx.test.ext.junit.runners.AndroidJUnit4 import im.vector.matrix.android.InstrumentedTest +import im.vector.matrix.android.api.extensions.tryThis +import im.vector.matrix.android.api.session.crypto.MXCryptoError import im.vector.matrix.android.api.session.events.model.EventType +import im.vector.matrix.android.api.session.events.model.toModel import im.vector.matrix.android.api.session.room.timeline.Timeline import im.vector.matrix.android.api.session.room.timeline.TimelineEvent import im.vector.matrix.android.api.session.room.timeline.TimelineSettings import im.vector.matrix.android.common.CommonTestHelper import im.vector.matrix.android.common.CryptoTestHelper +import im.vector.matrix.android.common.TestConstants +import im.vector.matrix.android.internal.crypto.model.OlmSessionWrapper +import im.vector.matrix.android.internal.crypto.model.event.EncryptedEventContent +import im.vector.matrix.android.internal.crypto.model.rest.UserPasswordAuth +import im.vector.matrix.android.internal.crypto.store.db.deserializeFromRealm +import im.vector.matrix.android.internal.crypto.store.db.serializeForRealm import org.amshove.kluent.shouldBe -import org.amshove.kluent.shouldBeEqualTo +import org.junit.Assert import org.junit.Before -import org.junit.BeforeClass import org.junit.FixMethodOrder import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters +import org.matrix.olm.OlmSession import timber.log.Timber import java.util.concurrent.CountDownLatch @@ -79,9 +88,8 @@ class UnwedgingTest : InstrumentedTest { val aliceCryptoStore = (aliceSession.cryptoService() as DefaultCryptoService).cryptoStoreForTesting - bobSession.cryptoService().setWarnOnUnknownDevices(false) - - aliceSession.cryptoService().setWarnOnUnknownDevices(false) + //bobSession.cryptoService().setWarnOnUnknownDevices(false) + //aliceSession.cryptoService().setWarnOnUnknownDevices(false) val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! @@ -100,10 +108,12 @@ class UnwedgingTest : InstrumentedTest { } override fun onTimelineUpdated(snapshot: List) { - val decryptedEventReceivedByBob = snapshot.filter { it.root.getClearType() == EventType.MESSAGE } + val decryptedEventReceivedByBob = snapshot.filter { it.root.type == EventType.ENCRYPTED } Timber.d("Bob can now decrypt ${decryptedEventReceivedByBob.size} messages") if (decryptedEventReceivedByBob.size == 3) { - bobFinalLatch.countDown() + if (decryptedEventReceivedByBob[0].root.mCryptoError == MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) { + bobFinalLatch.countDown() + } } } } @@ -122,6 +132,7 @@ class UnwedgingTest : InstrumentedTest { bobTimeline.removeListener(bobEventsListener) messagesReceivedByBob.size shouldBe 1 + val firstMessageSession = messagesReceivedByBob[0].root.content.toModel()!!.sessionId!! // - Store the olm session between A&B devices // Let us pickle our session with bob here so we can later unpickle it @@ -130,14 +141,17 @@ class UnwedgingTest : InstrumentedTest { sessionIdsForBob!!.size shouldBe 1 val olmSession = aliceCryptoStore.getDeviceSession(sessionIdsForBob.first(), bobSession.cryptoService().getMyDevice().identityKey()!!)!! - // Sam join the room, so it will force a new session creation - val samSession = mCryptoTestHelper.createSamAccountAndInviteToTheRoom(roomFromAlicePOV) + val oldSession = serializeForRealm(olmSession.olmSession) + + aliceSession.cryptoService().discardOutbundSession(roomFromAlicePOV.roomId) + Thread.sleep(6_000) latch = CountDownLatch(1) bobEventsListener = createEventListener(latch, 2) bobTimeline.addListener(bobEventsListener) messagesReceivedByBob = emptyList() + Timber.i("## CRYPTO | testUnwedging: Alice sends a 2nd message with a 2nd megolm session") // - Alice sends a 2nd message with a 2nd megolm session roomFromAlicePOV.sendTextMessage("Second message") @@ -146,36 +160,70 @@ class UnwedgingTest : InstrumentedTest { bobTimeline.removeListener(bobEventsListener) messagesReceivedByBob.size shouldBe 2 + // Session should have changed + val secondMessageSession = messagesReceivedByBob[0].root.content.toModel()!!.sessionId!! + Assert.assertNotEquals(firstMessageSession, secondMessageSession) // Let us wedge the session now. Set crypto state like after the first message - aliceCryptoStore.storeSession(olmSession, bobSession.cryptoService().getMyDevice().identityKey()!!) + Timber.i("## CRYPTO | testUnwedging: wedge the session now. Set crypto state like after the first message") - latch = CountDownLatch(1) - bobEventsListener = createEventListener(latch, 3) - bobTimeline.addListener(bobEventsListener) - messagesReceivedByBob = emptyList() + aliceCryptoStore.storeSession(OlmSessionWrapper(deserializeFromRealm(oldSession)!!), bobSession.cryptoService().getMyDevice().identityKey()!!) + Thread.sleep(6_000) - // - Alice sends a 3rd message with a 3rd megolm session but a wedged olm session - roomFromAlicePOV.sendTextMessage("Third message") + // Force new session, and key share + aliceSession.cryptoService().discardOutbundSession(roomFromAlicePOV.roomId) // Wait for the message to be received by Bob - mTestHelper.await(latch) + mTestHelper.waitWithLatch { + bobEventsListener = createEventListener(it, 3) + bobTimeline.addListener(bobEventsListener) + messagesReceivedByBob = emptyList() + + Timber.i("## CRYPTO | testUnwedging: Alice sends a 3rd message with a 3rd megolm session but a wedged olm session") + // - Alice sends a 3rd message with a 3rd megolm session but a wedged olm session + roomFromAlicePOV.sendTextMessage("Third message") + // Bob should not be able to decrypt, because the session key could not be sent + } bobTimeline.removeListener(bobEventsListener) messagesReceivedByBob.size shouldBe 3 - messagesReceivedByBob[0].root.getClearType() shouldBeEqualTo EventType.ENCRYPTED - messagesReceivedByBob[1].root.getClearType() shouldBeEqualTo EventType.MESSAGE - messagesReceivedByBob[2].root.getClearType() shouldBeEqualTo EventType.MESSAGE + val thirdMessageSession = messagesReceivedByBob[0].root.content.toModel()!!.sessionId!! + Timber.i("## CRYPTO | testUnwedging: third message session ID $thirdMessageSession") + Assert.assertNotEquals(secondMessageSession, thirdMessageSession) - // Wait for all the message to be decrypted by bob + Assert.assertEquals(EventType.ENCRYPTED, messagesReceivedByBob[0].root.getClearType()) + Assert.assertEquals(EventType.MESSAGE, messagesReceivedByBob[1].root.getClearType()) + Assert.assertEquals(EventType.MESSAGE, messagesReceivedByBob[2].root.getClearType()) + // Bob Should not be able to decrypt last message, because session could not be sent as the olm channel was wedged mTestHelper.await(bobFinalLatch) bobTimeline.removeListener(bobHasThreeDecryptedEventsListener) + // It's a trick to force key request on fail to decrypt + mTestHelper.doSync { + bobSession.cryptoService().crossSigningService() + .initializeCrossSigning(UserPasswordAuth( + user = bobSession.myUserId, + password = TestConstants.PASSWORD + ), it) + } + + // Wait until we received back the key + mTestHelper.waitWithLatch { + mTestHelper.retryPeriodicallyWithLatch(it) { + // we should get back the key and be able to decrypt + val result = tryThis { + bobSession.cryptoService().decryptEvent(messagesReceivedByBob[0].root, "") + } + Timber.i("## CRYPTO | testUnwedging: decrypt result ${result?.clearEvent}") + result != null + } + } + + bobTimeline.dispose() cryptoTestData.cleanUp(mTestHelper) - mTestHelper.signOutAndClose(samSession) } private fun createEventListener(latch: CountDownLatch, expectedNumberOfMessages: Int): Timeline.Listener { diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/crypto/CryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/crypto/CryptoService.kt index ab8417b5425..a923b2cc3d0 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/crypto/CryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/crypto/CryptoService.kt @@ -111,6 +111,8 @@ interface CryptoService { roomId: String, callback: MatrixCallback) + fun discardOutbundSession(roomId: String) + @Throws(MXCryptoError::class) fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index 476af38ce78..e865998fa9d 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -45,10 +45,11 @@ import im.vector.matrix.android.api.session.room.model.Membership import im.vector.matrix.android.api.session.room.model.RoomHistoryVisibility import im.vector.matrix.android.api.session.room.model.RoomHistoryVisibilityContent import im.vector.matrix.android.api.session.room.model.RoomMemberSummary +import im.vector.matrix.android.internal.crypto.actions.EnsureOlmSessionsForDevicesAction import im.vector.matrix.android.internal.crypto.actions.MegolmSessionDataImporter +import im.vector.matrix.android.internal.crypto.actions.MessageEncrypter import im.vector.matrix.android.internal.crypto.actions.SetDeviceVerificationAction import im.vector.matrix.android.internal.crypto.algorithms.IMXEncrypting -import im.vector.matrix.android.internal.crypto.algorithms.megolm.MXMegolmDecryption import im.vector.matrix.android.internal.crypto.algorithms.megolm.MXMegolmEncryptionFactory import im.vector.matrix.android.internal.crypto.algorithms.olm.MXOlmEncryptionFactory import im.vector.matrix.android.internal.crypto.crosssigning.DefaultCrossSigningService @@ -60,6 +61,7 @@ import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo import im.vector.matrix.android.internal.crypto.model.MXEncryptEventContentResult import im.vector.matrix.android.internal.crypto.model.MXUsersDevicesMap import im.vector.matrix.android.internal.crypto.model.event.EncryptedEventContent +import im.vector.matrix.android.internal.crypto.model.event.OlmEventContent import im.vector.matrix.android.internal.crypto.model.event.RoomKeyContent import im.vector.matrix.android.internal.crypto.model.event.SecretSendEventContent import im.vector.matrix.android.internal.crypto.model.rest.DeviceInfo @@ -73,6 +75,7 @@ import im.vector.matrix.android.internal.crypto.tasks.DeleteDeviceTask import im.vector.matrix.android.internal.crypto.tasks.DeleteDeviceWithUserPasswordTask import im.vector.matrix.android.internal.crypto.tasks.GetDeviceInfoTask import im.vector.matrix.android.internal.crypto.tasks.GetDevicesTask +import im.vector.matrix.android.internal.crypto.tasks.SendToDeviceTask import im.vector.matrix.android.internal.crypto.tasks.SetDeviceNameTask import im.vector.matrix.android.internal.crypto.tasks.UploadKeysTask import im.vector.matrix.android.internal.crypto.verification.DefaultVerificationService @@ -168,7 +171,10 @@ internal class DefaultCryptoService @Inject constructor( private val monarchy: Monarchy, private val coroutineDispatchers: MatrixCoroutineDispatchers, private val taskExecutor: TaskExecutor, - private val cryptoCoroutineScope: CoroutineScope + private val cryptoCoroutineScope: CoroutineScope, + private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction, + private val sendToDeviceTask: SendToDeviceTask, + private val messageEncrypter: MessageEncrypter ) : CryptoService { init { @@ -501,14 +507,14 @@ internal class DefaultCryptoService @Inject constructor( val existingAlgorithm = cryptoStore.getRoomAlgorithm(roomId) if (!existingAlgorithm.isNullOrEmpty() && existingAlgorithm != algorithm) { - Timber.e("## setEncryptionInRoom() : Ignoring m.room.encryption event which requests a change of config in $roomId") + Timber.e("## CRYPTO | setEncryptionInRoom() : Ignoring m.room.encryption event which requests a change of config in $roomId") return false } val encryptingClass = MXCryptoAlgorithms.hasEncryptorClassForAlgorithm(algorithm) if (!encryptingClass) { - Timber.e("## setEncryptionInRoom() : Unable to encrypt room $roomId with $algorithm") + Timber.e("## CRYPTO | setEncryptionInRoom() : Unable to encrypt room $roomId with $algorithm") return false } @@ -597,7 +603,7 @@ internal class DefaultCryptoService @Inject constructor( callback: MatrixCallback) { cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { if (!isStarted()) { - Timber.v("## encryptEventContent() : wait after e2e init") + Timber.v("## CRYPTO | encryptEventContent() : wait after e2e init") internalStart(false) } val userIds = getRoomUserIds(roomId) @@ -613,22 +619,28 @@ internal class DefaultCryptoService @Inject constructor( val safeAlgorithm = alg if (safeAlgorithm != null) { val t0 = System.currentTimeMillis() - Timber.v("## encryptEventContent() starts") + Timber.v("## CRYPTO | encryptEventContent() starts") runCatching { val content = safeAlgorithm.encryptEventContent(eventContent, eventType, userIds) - Timber.v("## encryptEventContent() : succeeds after ${System.currentTimeMillis() - t0} ms") + Timber.v("## CRYPTO | encryptEventContent() : succeeds after ${System.currentTimeMillis() - t0} ms") MXEncryptEventContentResult(content, EventType.ENCRYPTED) }.foldToCallback(callback) } else { val algorithm = getEncryptionAlgorithm(roomId) val reason = String.format(MXCryptoError.UNABLE_TO_ENCRYPT_REASON, algorithm ?: MXCryptoError.NO_MORE_ALGORITHM_REASON) - Timber.e("## encryptEventContent() : $reason") + Timber.e("## CRYPTO | encryptEventContent() : $reason") callback.onFailure(Failure.CryptoError(MXCryptoError.Base(MXCryptoError.ErrorType.UNABLE_TO_ENCRYPT, reason))) } } } + override fun discardOutbundSession(roomId: String) { + cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { + roomEncryptorsStore.get(roomId)?.discardSessionKey() + } + } + /** * Decrypt an event * @@ -670,24 +682,35 @@ internal class DefaultCryptoService @Inject constructor( private fun internalDecryptEvent(event: Event, timeline: String): MXEventDecryptionResult { val eventContent = event.content if (eventContent == null) { - Timber.e("## decryptEvent : empty event content") + Timber.e("## CRYPTO | decryptEvent : empty event content") throw MXCryptoError.Base(MXCryptoError.ErrorType.BAD_ENCRYPTED_MESSAGE, MXCryptoError.BAD_ENCRYPTED_MESSAGE_REASON) } else { val algorithm = eventContent["algorithm"]?.toString() val alg = roomDecryptorProvider.getOrCreateRoomDecryptor(event.roomId, algorithm) if (alg == null) { val reason = String.format(MXCryptoError.UNABLE_TO_DECRYPT_REASON, event.eventId, algorithm) - Timber.e("## decryptEvent() : $reason") + Timber.e("## CRYPTO | decryptEvent() : $reason") throw MXCryptoError.Base(MXCryptoError.ErrorType.UNABLE_TO_DECRYPT, reason) } else { try { return alg.decryptEvent(event, timeline) } catch (mxCryptoError: MXCryptoError) { - if (mxCryptoError is MXCryptoError.Base - && mxCryptoError.errorType == MXCryptoError.ErrorType.BAD_ENCRYPTED_MESSAGE - && alg is MXMegolmDecryption) { - // TODO Do it on decryption thread like on iOS? - markOlmSessionForUnwedging(event, alg) + Timber.d("## CRYPTO | internalDecryptEvent : Failed to decrypt ${event.eventId} reason: $mxCryptoError") + if (algorithm == MXCRYPTO_ALGORITHM_OLM) { + if (mxCryptoError is MXCryptoError.Base + && mxCryptoError.errorType == MXCryptoError.ErrorType.BAD_ENCRYPTED_MESSAGE) { + // need to find sending device + val olmContent = event.content.toModel() + cryptoStore.getUserDevices(event.senderId ?: "") + ?.values + ?.firstOrNull { it.identityKey() == olmContent?.senderKey } + ?.let { + markOlmSessionForUnwedging(event.senderId ?: "", it) + } + ?: run { + Timber.v("## CRYPTO | markOlmSessionForUnwedging() : Failed to find sender crypto device") + } + } } throw mxCryptoError } @@ -695,36 +718,37 @@ internal class DefaultCryptoService @Inject constructor( } } - private fun markOlmSessionForUnwedging(event: Event, mxMegolmDecryption: MXMegolmDecryption) { - val senderId = event.senderId ?: return - val encryptedMessage = event.content.toModel() ?: return - val deviceKey = encryptedMessage.senderKey ?: return - encryptedMessage.algorithm?.takeIf { it == MXCRYPTO_ALGORITHM_MEGOLM } ?: return - - if (senderId == userId - && deviceKey == olmDevice.deviceCurve25519Key) { - Timber.d("[MXCrypto] markOlmSessionForUnwedging: Do not unwedge ourselves") - return - } - - val lastForcedDate = lastNewSessionForcedDates.getObject(senderId, deviceKey) ?: 0 - val now = System.currentTimeMillis() - if (now - lastForcedDate < CRYPTO_MIN_FORCE_SESSION_PERIOD_MILLIS) { - Timber.d("[MXCrypto] markOlmSessionForUnwedging: New session already forced with device at $lastForcedDate. Not forcing another") - return - } - - // Establish a new olm session with this device since we're failing to decrypt messages - // on a current session. - val deviceInfo = getDeviceInfo(senderId, deviceKey) ?: return Unit.also { - Timber.d("[MXCrypto] markOlmSessionForUnwedging: Couldn't find device for identity key $deviceKey: not re-establishing session") - } - - Timber.d("[MXCrypto] markOlmSessionForUnwedging from $senderId:${deviceInfo.deviceId}") - lastNewSessionForcedDates.setObject(senderId, deviceKey, now) - - mxMegolmDecryption.markOlmSessionForUnwedging(senderId, deviceInfo) - } +// private fun markOlmSessionForUnwedging(event: Event, mxMegolmDecryption: MXMegolmDecryption) { +// Timber.d("## CRYPTO |  markOlmSessionForUnwedging: ${event.eventId}") +// val senderId = event.senderId ?: return +// val encryptedMessage = event.content.toModel() ?: return +// val deviceKey = encryptedMessage.senderKey ?: return +// encryptedMessage.algorithm?.takeIf { it == MXCRYPTO_ALGORITHM_MEGOLM } ?: return +// +// if (senderId == userId +// && deviceKey == olmDevice.deviceCurve25519Key) { +// Timber.d("## CRYPTO |  markOlmSessionForUnwedging: Do not unwedge ourselves") +// return +// } +// +// val lastForcedDate = lastNewSessionForcedDates.getObject(senderId, deviceKey) ?: 0 +// val now = System.currentTimeMillis() +// if (now - lastForcedDate < CRYPTO_MIN_FORCE_SESSION_PERIOD_MILLIS) { +// Timber.d("## CRYPTO | markOlmSessionForUnwedging: New session already forced with device at $lastForcedDate. Not forcing another") +// return +// } +// +// // Establish a new olm session with this device since we're failing to decrypt messages +// // on a current session. +// val deviceInfo = getDeviceInfo(senderId, deviceKey) ?: return Unit.also { +// Timber.d("## CRYPTO | markOlmSessionForUnwedging: Couldn't find device for identity key $deviceKey: not re-establishing session") +// } +// +// Timber.d("## CRYPTO | markOlmSessionForUnwedging from $senderId:${deviceInfo.deviceId}") +// lastNewSessionForcedDates.setObject(senderId, deviceKey, now) +// +// mxMegolmDecryption.markOlmSessionForUnwedging(senderId, deviceInfo) +// } /** * Reset replay attack data for the given timeline. @@ -774,30 +798,30 @@ internal class DefaultCryptoService @Inject constructor( */ private fun onRoomKeyEvent(event: Event) { val roomKeyContent = event.getClearContent().toModel() ?: return - Timber.v("## GOSSIP onRoomKeyEvent() : type<${event.type}> , sessionId<${roomKeyContent.sessionId}>") + Timber.v("## CRYPTO | GOSSIP onRoomKeyEvent() : type<${event.type}> , sessionId<${roomKeyContent.sessionId}>") if (roomKeyContent.roomId.isNullOrEmpty() || roomKeyContent.algorithm.isNullOrEmpty()) { - Timber.e("## GOSSIP onRoomKeyEvent() : missing fields") + Timber.e("## CRYPTO | GOSSIP onRoomKeyEvent() : missing fields") return } val alg = roomDecryptorProvider.getOrCreateRoomDecryptor(roomKeyContent.roomId, roomKeyContent.algorithm) if (alg == null) { - Timber.e("## GOSSIP onRoomKeyEvent() : Unable to handle keys for ${roomKeyContent.algorithm}") + Timber.e("## CRYPTO | GOSSIP onRoomKeyEvent() : Unable to handle keys for ${roomKeyContent.algorithm}") return } alg.onRoomKeyEvent(event, keysBackupService) } private fun onSecretSendReceived(event: Event) { - Timber.i("## GOSSIP onSecretSend() : onSecretSendReceived ${event.content?.get("sender_key")}") + Timber.i("## CRYPTO | GOSSIP onSecretSend() : onSecretSendReceived ${event.content?.get("sender_key")}") if (!event.isEncrypted()) { // secret send messages must be encrypted - Timber.e("## GOSSIP onSecretSend() :Received unencrypted secret send event") + Timber.e("## CRYPTO | GOSSIP onSecretSend() :Received unencrypted secret send event") return } // Was that sent by us? if (event.senderId != userId) { - Timber.e("## GOSSIP onSecretSend() : Ignore secret from other user ${event.senderId}") + Timber.e("## CRYPTO | GOSSIP onSecretSend() : Ignore secret from other user ${event.senderId}") return } @@ -807,13 +831,13 @@ internal class DefaultCryptoService @Inject constructor( .getOutgoingSecretKeyRequests().firstOrNull { it.requestId == secretContent.requestId } if (existingRequest == null) { - Timber.i("## GOSSIP onSecretSend() : Ignore secret that was not requested: ${secretContent.requestId}") + Timber.i("## CRYPTO | GOSSIP onSecretSend() : Ignore secret that was not requested: ${secretContent.requestId}") return } if (!handleSDKLevelGossip(existingRequest.secretName, secretContent.secretValue)) { // TODO Ask to application layer? - Timber.v("## onSecretSend() : secret not handled by SDK") + Timber.v("## CRYPTO | onSecretSend() : secret not handled by SDK") } } @@ -849,7 +873,7 @@ internal class DefaultCryptoService @Inject constructor( try { loadRoomMembersTask.execute(params) } catch (throwable: Throwable) { - Timber.e(throwable, "## onRoomEncryptionEvent ERROR FAILED TO SETUP CRYPTO ") + Timber.e(throwable, "## CRYPTO | onRoomEncryptionEvent ERROR FAILED TO SETUP CRYPTO ") } finally { val userIds = getRoomUserIds(roomId) setEncryptionInRoom(roomId, event.content?.get("algorithm")?.toString(), true, userIds) @@ -974,13 +998,13 @@ internal class DefaultCryptoService @Inject constructor( cryptoCoroutineScope.launch(coroutineDispatchers.main) { runCatching { withContext(coroutineDispatchers.crypto) { - Timber.v("## importRoomKeys starts") + Timber.v("## CRYPTO | importRoomKeys starts") val t0 = System.currentTimeMillis() val roomKeys = MXMegolmExportEncryption.decryptMegolmKeyFile(roomKeysAsArray, password) val t1 = System.currentTimeMillis() - Timber.v("## importRoomKeys : decryptMegolmKeyFile done in ${t1 - t0} ms") + Timber.v("## CRYPTO | importRoomKeys : decryptMegolmKeyFile done in ${t1 - t0} ms") val importedSessions = MoshiProvider.providesMoshi() .adapter>(Types.newParameterizedType(List::class.java, MegolmSessionData::class.java)) @@ -988,7 +1012,7 @@ internal class DefaultCryptoService @Inject constructor( val t2 = System.currentTimeMillis() - Timber.v("## importRoomKeys : JSON parsing ${t2 - t1} ms") + Timber.v("## CRYPTO | importRoomKeys : JSON parsing ${t2 - t1} ms") if (importedSessions == null) { throw Exception("Error") @@ -1123,7 +1147,7 @@ internal class DefaultCryptoService @Inject constructor( */ override fun reRequestRoomKeyForEvent(event: Event) { val wireContent = event.content.toModel() ?: return Unit.also { - Timber.e("## reRequestRoomKeyForEvent Failed to re-request key, null content") + Timber.e("## CRYPTO | reRequestRoomKeyForEvent Failed to re-request key, null content") } val requestBody = RoomKeyRequestBody( @@ -1138,18 +1162,18 @@ internal class DefaultCryptoService @Inject constructor( override fun requestRoomKeyForEvent(event: Event) { val wireContent = event.content.toModel() ?: return Unit.also { - Timber.e("## requestRoomKeyForEvent Failed to request key, null content eventId: ${event.eventId}") + Timber.e("## CRYPTO | requestRoomKeyForEvent Failed to request key, null content eventId: ${event.eventId}") } cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { if (!isStarted()) { - Timber.v("## requestRoomKeyForEvent() : wait after e2e init") + Timber.v("## CRYPTO | requestRoomKeyForEvent() : wait after e2e init") internalStart(false) } roomDecryptorProvider .getOrCreateRoomDecryptor(event.roomId, wireContent.algorithm) ?.requestKeysForEvent(event) ?: run { - Timber.v("## requestRoomKeyForEvent() : No room decryptor for roomId:${event.roomId} algorithm:${wireContent.algorithm}") + Timber.v("## CRYPTO | requestRoomKeyForEvent() : No room decryptor for roomId:${event.roomId} algorithm:${wireContent.algorithm}") } } } @@ -1172,6 +1196,27 @@ internal class DefaultCryptoService @Inject constructor( incomingGossipingRequestManager.removeRoomKeysRequestListener(listener) } + private fun markOlmSessionForUnwedging(senderId: String, deviceInfo: CryptoDeviceInfo) { + cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { + ensureOlmSessionsForDevicesAction.handle(mapOf(senderId to listOf(deviceInfo)), force = true) + + // Now send a blank message on that session so the other side knows about it. + // (The keyshare request is sent in the clear so that won't do) + // We send this first such that, as long as the toDevice messages arrive in the + // same order we sent them, the other end will get this first, set up the new session, + // then get the keyshare request and send the key over this new session (because it + // is the session it has most recently received a message on). + val payloadJson = mapOf("type" to EventType.DUMMY) + + val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo)) + val sendToDeviceMap = MXUsersDevicesMap() + sendToDeviceMap.setObject(senderId, deviceInfo.deviceId, encodedPayload) + Timber.v("## CRYPTO | markOlmSessionForUnwedging() : sending to $senderId:${deviceInfo.deviceId}") + val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap) + sendToDeviceTask.execute(sendToDeviceParams) + } + } + /** * Provides the list of unknown devices * diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DeviceListManager.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DeviceListManager.kt index 37a5ee18e1b..680539d0576 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DeviceListManager.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DeviceListManager.kt @@ -108,7 +108,7 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM res = !notReadyToRetryHS.contains(userId.substringAfterLast(':')) } } catch (e: Exception) { - Timber.e(e, "## canRetryKeysDownload() failed") + Timber.e(e, "## CRYPTO | canRetryKeysDownload() failed") } } @@ -137,7 +137,7 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM for (userId in userIds) { if (!deviceTrackingStatuses.containsKey(userId) || TRACKING_STATUS_NOT_TRACKED == deviceTrackingStatuses[userId]) { - Timber.v("## startTrackingDeviceList() : Now tracking device list for $userId") + Timber.v("## CRYPTO | startTrackingDeviceList() : Now tracking device list for $userId") deviceTrackingStatuses[userId] = TRACKING_STATUS_PENDING_DOWNLOAD isUpdated = true } @@ -161,7 +161,7 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM for (userId in changed) { if (deviceTrackingStatuses.containsKey(userId)) { - Timber.v("## invalidateUserDeviceList() : Marking device list outdated for $userId") + Timber.v("## CRYPTO | invalidateUserDeviceList() : Marking device list outdated for $userId") deviceTrackingStatuses[userId] = TRACKING_STATUS_PENDING_DOWNLOAD isUpdated = true } @@ -169,7 +169,7 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM for (userId in left) { if (deviceTrackingStatuses.containsKey(userId)) { - Timber.v("## invalidateUserDeviceList() : No longer tracking device list for $userId") + Timber.v("## CRYPTO | invalidateUserDeviceList() : No longer tracking device list for $userId") deviceTrackingStatuses[userId] = TRACKING_STATUS_NOT_TRACKED isUpdated = true } @@ -259,7 +259,7 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM * @param forceDownload Always download the keys even if cached. */ suspend fun downloadKeys(userIds: List?, forceDownload: Boolean): MXUsersDevicesMap { - Timber.v("## downloadKeys() : forceDownload $forceDownload : $userIds") + Timber.v("## CRYPTO | downloadKeys() : forceDownload $forceDownload : $userIds") // Map from userId -> deviceId -> MXDeviceInfo val stored = MXUsersDevicesMap() @@ -288,13 +288,13 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM } } return if (downloadUsers.isEmpty()) { - Timber.v("## downloadKeys() : no new user device") + Timber.v("## CRYPTO | downloadKeys() : no new user device") stored } else { - Timber.v("## downloadKeys() : starts") + Timber.v("## CRYPTO | downloadKeys() : starts") val t0 = System.currentTimeMillis() val result = doKeyDownloadForUsers(downloadUsers) - Timber.v("## downloadKeys() : doKeyDownloadForUsers succeeds after ${System.currentTimeMillis() - t0} ms") + Timber.v("## CRYPTO | downloadKeys() : doKeyDownloadForUsers succeeds after ${System.currentTimeMillis() - t0} ms") result.also { it.addEntriesFromMap(stored) } @@ -307,7 +307,7 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM * @param downloadUsers the user ids list */ private suspend fun doKeyDownloadForUsers(downloadUsers: List): MXUsersDevicesMap { - Timber.v("## doKeyDownloadForUsers() : doKeyDownloadForUsers $downloadUsers") + Timber.v("## CRYPTO | doKeyDownloadForUsers() : doKeyDownloadForUsers $downloadUsers") // get the user ids which did not already trigger a keys download val filteredUsers = downloadUsers.filter { MatrixPatterns.isUserId(it) } if (filteredUsers.isEmpty()) { @@ -318,16 +318,16 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM val response = try { downloadKeysForUsersTask.execute(params) } catch (throwable: Throwable) { - Timber.e(throwable, "##doKeyDownloadForUsers(): error") + Timber.e(throwable, "## CRYPTO | doKeyDownloadForUsers(): error") onKeysDownloadFailed(filteredUsers) throw throwable } - Timber.v("## doKeyDownloadForUsers() : Got keys for " + filteredUsers.size + " users") + Timber.v("## CRYPTO | doKeyDownloadForUsers() : Got keys for " + filteredUsers.size + " users") for (userId in filteredUsers) { // al devices = val models = response.deviceKeys?.get(userId)?.mapValues { entry -> CryptoInfoMapper.map(entry.value) } - Timber.v("## doKeyDownloadForUsers() : Got keys for $userId : $models") + Timber.v("## CRYPTO | doKeyDownloadForUsers() : Got keys for $userId : $models") if (!models.isNullOrEmpty()) { val workingCopy = models.toMutableMap() for ((deviceId, deviceInfo) in models) { @@ -361,13 +361,13 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM // Handle cross signing keys update val masterKey = response.masterKeys?.get(userId)?.toCryptoModel().also { - Timber.v("## CrossSigning : Got keys for $userId : MSK ${it?.unpaddedBase64PublicKey}") + Timber.v("## CRYPTO | CrossSigning : Got keys for $userId : MSK ${it?.unpaddedBase64PublicKey}") } val selfSigningKey = response.selfSigningKeys?.get(userId)?.toCryptoModel()?.also { - Timber.v("## CrossSigning : Got keys for $userId : SSK ${it.unpaddedBase64PublicKey}") + Timber.v("## CRYPTO | CrossSigning : Got keys for $userId : SSK ${it.unpaddedBase64PublicKey}") } val userSigningKey = response.userSigningKeys?.get(userId)?.toCryptoModel()?.also { - Timber.v("## CrossSigning : Got keys for $userId : USK ${it.unpaddedBase64PublicKey}") + Timber.v("## CRYPTO | CrossSigning : Got keys for $userId : USK ${it.unpaddedBase64PublicKey}") } cryptoStore.storeUserCrossSigningKeys( userId, @@ -395,28 +395,28 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM */ private fun validateDeviceKeys(deviceKeys: CryptoDeviceInfo?, userId: String, deviceId: String, previouslyStoredDeviceKeys: CryptoDeviceInfo?): Boolean { if (null == deviceKeys) { - Timber.e("## validateDeviceKeys() : deviceKeys is null from $userId:$deviceId") + Timber.e("## CRYPTO | validateDeviceKeys() : deviceKeys is null from $userId:$deviceId") return false } if (null == deviceKeys.keys) { - Timber.e("## validateDeviceKeys() : deviceKeys.keys is null from $userId:$deviceId") + Timber.e("## CRYPTO | validateDeviceKeys() : deviceKeys.keys is null from $userId:$deviceId") return false } if (null == deviceKeys.signatures) { - Timber.e("## validateDeviceKeys() : deviceKeys.signatures is null from $userId:$deviceId") + Timber.e("## CRYPTO | validateDeviceKeys() : deviceKeys.signatures is null from $userId:$deviceId") return false } // Check that the user_id and device_id in the received deviceKeys are correct if (deviceKeys.userId != userId) { - Timber.e("## validateDeviceKeys() : Mismatched user_id ${deviceKeys.userId} from $userId:$deviceId") + Timber.e("## CRYPTO | validateDeviceKeys() : Mismatched user_id ${deviceKeys.userId} from $userId:$deviceId") return false } if (deviceKeys.deviceId != deviceId) { - Timber.e("## validateDeviceKeys() : Mismatched device_id ${deviceKeys.deviceId} from $userId:$deviceId") + Timber.e("## CRYPTO | validateDeviceKeys() : Mismatched device_id ${deviceKeys.deviceId} from $userId:$deviceId") return false } @@ -424,21 +424,21 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM val signKey = deviceKeys.keys[signKeyId] if (null == signKey) { - Timber.e("## validateDeviceKeys() : Device $userId:${deviceKeys.deviceId} has no ed25519 key") + Timber.e("## CRYPTO | validateDeviceKeys() : Device $userId:${deviceKeys.deviceId} has no ed25519 key") return false } val signatureMap = deviceKeys.signatures[userId] if (null == signatureMap) { - Timber.e("## validateDeviceKeys() : Device $userId:${deviceKeys.deviceId} has no map for $userId") + Timber.e("## CRYPTO | validateDeviceKeys() : Device $userId:${deviceKeys.deviceId} has no map for $userId") return false } val signature = signatureMap[signKeyId] if (null == signature) { - Timber.e("## validateDeviceKeys() : Device $userId:${deviceKeys.deviceId} is not signed") + Timber.e("## CRYPTO | validateDeviceKeys() : Device $userId:${deviceKeys.deviceId} is not signed") return false } @@ -453,7 +453,7 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM } if (!isVerified) { - Timber.e("## validateDeviceKeys() : Unable to verify signature on device " + userId + ":" + Timber.e("## CRYPTO | validateDeviceKeys() : Unable to verify signature on device " + userId + ":" + deviceKeys.deviceId + " with error " + errorMessage) return false } @@ -464,12 +464,12 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM // best off sticking with the original keys. // // Should we warn the user about it somehow? - Timber.e("## validateDeviceKeys() : WARNING:Ed25519 key for device " + userId + ":" + Timber.e("## CRYPTO | validateDeviceKeys() : WARNING:Ed25519 key for device " + userId + ":" + deviceKeys.deviceId + " has changed : " + previouslyStoredDeviceKeys.fingerprint() + " -> " + signKey) - Timber.e("## validateDeviceKeys() : $previouslyStoredDeviceKeys -> $deviceKeys") - Timber.e("## validateDeviceKeys() : ${previouslyStoredDeviceKeys.keys} -> ${deviceKeys.keys}") + Timber.e("## CRYPTO | validateDeviceKeys() : $previouslyStoredDeviceKeys -> $deviceKeys") + Timber.e("## CRYPTO | validateDeviceKeys() : ${previouslyStoredDeviceKeys.keys} -> ${deviceKeys.keys}") return false } @@ -501,10 +501,10 @@ internal class DeviceListManager @Inject constructor(private val cryptoStore: IM doKeyDownloadForUsers(users) }.fold( { - Timber.v("## refreshOutdatedDeviceLists() : done") + Timber.v("## CRYPTO | refreshOutdatedDeviceLists() : done") }, { - Timber.e(it, "## refreshOutdatedDeviceLists() : ERROR updating device keys for users $users") + Timber.e(it, "## CRYPTO | refreshOutdatedDeviceLists() : ERROR updating device keys for users $users") } ) } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt index b17143d93d6..38f81ba47de 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/IncomingGossipingRequestManager.kt @@ -96,7 +96,7 @@ internal class IncomingGossipingRequestManager @Inject constructor( * @param event the announcement event. */ fun onGossipingRequestEvent(event: Event) { - Timber.v("## GOSSIP onGossipingRequestEvent type ${event.type} from user ${event.senderId}") + Timber.v("## CRYPTO | GOSSIP onGossipingRequestEvent type ${event.type} from user ${event.senderId}") val roomKeyShare = event.getClearContent().toModel() val ageLocalTs = event.unsignedData?.age?.let { System.currentTimeMillis() - it } when (roomKeyShare?.action) { @@ -161,7 +161,7 @@ internal class IncomingGossipingRequestManager @Inject constructor( } receivedRequestCancellations?.forEach { request -> - Timber.v("## GOSSIP processReceivedGossipingRequests() : m.room_key_request cancellation $request") + Timber.v("## CRYPTO | GOSSIP processReceivedGossipingRequests() : m.room_key_request cancellation $request") // we should probably only notify the app of cancellations we told it // about, but we don't currently have a record of that, so we just pass // everything through. @@ -190,9 +190,9 @@ internal class IncomingGossipingRequestManager @Inject constructor( val roomId = body.roomId ?: return val alg = body.algorithm ?: return - Timber.v("## GOSSIP processIncomingRoomKeyRequest from $userId:$deviceId for $roomId / ${body.sessionId} id ${request.requestId}") + Timber.v("## CRYPTO | GOSSIP processIncomingRoomKeyRequest from $userId:$deviceId for $roomId / ${body.sessionId} id ${request.requestId}") if (credentials.userId != userId) { - Timber.w("## GOSSIP processReceivedGossipingRequests() : room key request from other user") + Timber.w("## CRYPTO | GOSSIP processReceivedGossipingRequests() : room key request from other user") val senderKey = body.senderKey ?: return Unit .also { Timber.w("missing senderKey") } .also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } @@ -227,18 +227,18 @@ internal class IncomingGossipingRequestManager @Inject constructor( // the keys for the requested events, and can drop the requests. val decryptor = roomDecryptorProvider.getRoomDecryptor(roomId, alg) if (null == decryptor) { - Timber.w("## GOSSIP processReceivedGossipingRequests() : room key request for unknown $alg in room $roomId") + Timber.w("## CRYPTO | GOSSIP processReceivedGossipingRequests() : room key request for unknown $alg in room $roomId") cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) return } if (!decryptor.hasKeysForKeyRequest(request)) { - Timber.w("## GOSSIP processReceivedGossipingRequests() : room key request for unknown session ${body.sessionId!!}") + Timber.w("## CRYPTO | GOSSIP processReceivedGossipingRequests() : room key request for unknown session ${body.sessionId!!}") cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) return } if (credentials.deviceId == deviceId && credentials.userId == userId) { - Timber.v("## GOSSIP processReceivedGossipingRequests() : oneself device - ignored") + Timber.v("## CRYPTO | GOSSIP processReceivedGossipingRequests() : oneself device - ignored") cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) return } @@ -253,13 +253,13 @@ internal class IncomingGossipingRequestManager @Inject constructor( val device = cryptoStore.getUserDevice(userId, deviceId) if (device != null) { if (device.isVerified) { - Timber.v("## GOSSIP processReceivedGossipingRequests() : device is already verified: sharing keys") + Timber.v("## CRYPTO | GOSSIP processReceivedGossipingRequests() : device is already verified: sharing keys") request.share?.run() return } if (device.isBlocked) { - Timber.v("## GOSSIP processReceivedGossipingRequests() : device is blocked -> ignored") + Timber.v("## CRYPTO | GOSSIP processReceivedGossipingRequests() : device is blocked -> ignored") cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) return } @@ -267,7 +267,7 @@ internal class IncomingGossipingRequestManager @Inject constructor( // As per config we automatically discard untrusted devices request if (cryptoConfig.discardRoomKeyRequestsFromUntrustedDevices) { - Timber.v("## processReceivedGossipingRequests() : discardRoomKeyRequestsFromUntrustedDevices") + Timber.v("## CRYPTO | processReceivedGossipingRequests() : discardRoomKeyRequestsFromUntrustedDevices") // At this point the device is unknown, we don't want to bother user with that cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) return @@ -280,30 +280,30 @@ internal class IncomingGossipingRequestManager @Inject constructor( private fun processIncomingSecretShareRequest(request: IncomingSecretShareRequest) { val secretName = request.secretName ?: return Unit.also { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) - Timber.v("## GOSSIP processIncomingSecretShareRequest() : Missing secret name") + Timber.v("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Missing secret name") } val userId = request.userId if (userId == null || credentials.userId != userId) { - Timber.e("## GOSSIP processIncomingSecretShareRequest() : Ignoring secret share request from other users") + Timber.e("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Ignoring secret share request from other users") cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) return } val deviceId = request.deviceId ?: return Unit.also { - Timber.e("## GOSSIP processIncomingSecretShareRequest() : Malformed request, no ") + Timber.e("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Malformed request, no ") cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } val device = cryptoStore.getUserDevice(userId, deviceId) ?: return Unit.also { - Timber.e("## GOSSIP processIncomingSecretShareRequest() : Received secret share request from unknown device ${request.deviceId}") + Timber.e("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Received secret share request from unknown device ${request.deviceId}") cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } if (!device.isVerified || device.isBlocked) { - Timber.v("## GOSSIP processIncomingSecretShareRequest() : Ignoring secret share request from untrusted/blocked session $device") + Timber.v("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Ignoring secret share request from untrusted/blocked session $device") cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) return } @@ -320,7 +320,7 @@ internal class IncomingGossipingRequestManager @Inject constructor( } else -> null }?.let { secretValue -> - Timber.i("## GOSSIP processIncomingSecretShareRequest() : Sharing secret $secretName with $device locally trusted") + Timber.i("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Sharing secret $secretName with $device locally trusted") if (isDeviceLocallyVerified == true && hasBeenVerifiedLessThanFiveMinutesFromNow(deviceId)) { val params = SendGossipWorker.Params( sessionId = sessionId, @@ -332,13 +332,13 @@ internal class IncomingGossipingRequestManager @Inject constructor( val workRequest = gossipingWorkManager.createWork(WorkerParamsFactory.toData(params), true) gossipingWorkManager.postWork(workRequest) } else { - Timber.v("## GOSSIP processIncomingSecretShareRequest() : Can't share secret $secretName with $device, verification too old") + Timber.v("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : Can't share secret $secretName with $device, verification too old") cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) } return } - Timber.v("## GOSSIP processIncomingSecretShareRequest() : $secretName unknown at SDK level, asking to app layer") + Timber.v("## CRYPTO | GOSSIP processIncomingSecretShareRequest() : $secretName unknown at SDK level, asking to app layer") request.ignore = Runnable { cryptoStore.updateGossipingRequestState(request, GossipingRequestState.REJECTED) @@ -372,7 +372,7 @@ internal class IncomingGossipingRequestManager @Inject constructor( try { listener.onRoomKeyRequest(request) } catch (e: Exception) { - Timber.e(e, "## onRoomKeyRequest() failed") + Timber.e(e, "## CRYPTO | onRoomKeyRequest() failed") } } } @@ -389,7 +389,7 @@ internal class IncomingGossipingRequestManager @Inject constructor( return } } catch (e: Exception) { - Timber.e(e, "## GOSSIP onRoomKeyRequest() failed") + Timber.e(e, "## CRYPTO | GOSSIP onRoomKeyRequest() failed") } } } @@ -408,7 +408,7 @@ internal class IncomingGossipingRequestManager @Inject constructor( try { listener.onRoomKeyRequestCancellation(request) } catch (e: Exception) { - Timber.e(e, "## GOSSIP onRoomKeyRequestCancellation() failed") + Timber.e(e, "## CRYPTO | GOSSIP onRoomKeyRequestCancellation() failed") } } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt index 0351c183ceb..d6d8b06b5fc 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/MXOlmDevice.kt @@ -342,6 +342,8 @@ internal class MXOlmDevice @Inject constructor( } catch (e: Exception) { Timber.e(e, "## encryptMessage() : failed") } + } else { + Timber.e("## encryptMessage() : Failed to encrypt unknown session $sessionId") } return res diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/OutgoingGossipingRequestManager.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/OutgoingGossipingRequestManager.kt index c06f10b106c..eb1c07cb924 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/OutgoingGossipingRequestManager.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/OutgoingGossipingRequestManager.kt @@ -55,7 +55,7 @@ internal class OutgoingGossipingRequestManager @Inject constructor( cryptoStore.getOrAddOutgoingRoomKeyRequest(requestBody, recipients)?.let { // Don't resend if it's already done, you need to cancel first (reRequest) if (it.state == OutgoingGossipingRequestState.SENDING || it.state == OutgoingGossipingRequestState.SENT) { - Timber.v("## GOSSIP sendOutgoingRoomKeyRequest() : we already request for that session: $it") + Timber.v("## CRYPTO - GOSSIP sendOutgoingRoomKeyRequest() : we already request for that session: $it") return@launch } @@ -72,7 +72,7 @@ internal class OutgoingGossipingRequestManager @Inject constructor( cryptoStore.getOrAddOutgoingSecretShareRequest(secretName, recipients)?.let { // TODO check if there is already one that is being sent? if (it.state == OutgoingGossipingRequestState.SENDING || it.state == OutgoingGossipingRequestState.SENT) { - Timber.v("## GOSSIP sendSecretShareRequest() : we already request for that session: $it") + Timber.v("## CRYPTO - GOSSIP sendSecretShareRequest() : we already request for that session: $it") return@launch } @@ -113,7 +113,7 @@ internal class OutgoingGossipingRequestManager @Inject constructor( val req = cryptoStore.getOutgoingRoomKeyRequest(requestBody) ?: // no request was made for this key return Unit.also { - Timber.v("## GOSSIP cancelRoomKeyRequest() Unknown request") + Timber.v("## CRYPTO - GOSSIP cancelRoomKeyRequest() Unknown request $requestBody") } sendOutgoingRoomKeyRequestCancellation(req, andResend) @@ -125,7 +125,7 @@ internal class OutgoingGossipingRequestManager @Inject constructor( * @param request the request */ private fun sendOutgoingGossipingRequest(request: OutgoingGossipingRequest) { - Timber.v("## GOSSIP sendOutgoingRoomKeyRequest() : Requesting keys $request") + Timber.v("## CRYPTO - GOSSIP sendOutgoingRoomKeyRequest() : Requesting keys $request") val params = SendGossipRequestWorker.Params( sessionId = sessionId, @@ -143,7 +143,7 @@ internal class OutgoingGossipingRequestManager @Inject constructor( * @param request the request */ private fun sendOutgoingRoomKeyRequestCancellation(request: OutgoingRoomKeyRequest, resend: Boolean = false) { - Timber.v("$request") + Timber.v("## CRYPTO - sendOutgoingRoomKeyRequestCancellation $request") val params = CancelGossipRequestWorker.Params.fromRequest(sessionId, request) cryptoStore.updateOutgoingGossipingRequestState(request.requestId, OutgoingGossipingRequestState.CANCELLING) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt index d856331189f..e630d14eab8 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/actions/EnsureOlmSessionsForDevicesAction.kt @@ -69,11 +69,11 @@ internal class EnsureOlmSessionsForDevicesAction @Inject constructor( // // That should eventually resolve itself, but it's poor form. - Timber.v("## claimOneTimeKeysForUsersDevices() : $usersDevicesToClaim") + Timber.v("## CRYPTO | claimOneTimeKeysForUsersDevices() : $usersDevicesToClaim") val claimParams = ClaimOneTimeKeysForUsersDeviceTask.Params(usersDevicesToClaim) val oneTimeKeys = oneTimeKeysForUsersDeviceTask.execute(claimParams) - Timber.v("## claimOneTimeKeysForUsersDevices() : keysClaimResponse.oneTimeKeys: $oneTimeKeys") + Timber.v("## CRYPTO | claimOneTimeKeysForUsersDevices() : keysClaimResponse.oneTimeKeys: $oneTimeKeys") for ((userId, deviceInfos) in devicesByUser) { for (deviceInfo in deviceInfos) { var oneTimeKey: MXKey? = null @@ -90,7 +90,7 @@ internal class EnsureOlmSessionsForDevicesAction @Inject constructor( oneTimeKey = key } if (oneTimeKey == null) { - Timber.v("## ensureOlmSessionsForDevices() : No one-time keys " + oneTimeKeyAlgorithm + Timber.v("## CRYPTO | ensureOlmSessionsForDevices() : No one-time keys " + oneTimeKeyAlgorithm + " for device " + userId + " : " + deviceId) continue } @@ -126,14 +126,14 @@ internal class EnsureOlmSessionsForDevicesAction @Inject constructor( sessionId = olmDevice.createOutboundSession(deviceInfo.identityKey()!!, oneTimeKey.value) if (!sessionId.isNullOrEmpty()) { - Timber.v("## verifyKeyAndStartSession() : Started new sessionid " + sessionId + Timber.v("## CRYPTO | verifyKeyAndStartSession() : Started new sessionid " + sessionId + " for device " + deviceInfo + "(theirOneTimeKey: " + oneTimeKey.value + ")") } else { // Possibly a bad key - Timber.e("## verifyKeyAndStartSession() : Error starting session with device $userId:$deviceId") + Timber.e("## CRYPTO | verifyKeyAndStartSession() : Error starting session with device $userId:$deviceId") } } else { - Timber.e("## verifyKeyAndStartSession() : Unable to verify signature on one-time key for device " + userId + Timber.e("## CRYPTO | verifyKeyAndStartSession() : Unable to verify signature on one-time key for device " + userId + ":" + deviceId + " Error " + errorMessage) } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt index 65119362bc2..ddf605def4a 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/IMXEncrypting.kt @@ -34,6 +34,20 @@ internal interface IMXEncrypting { */ suspend fun encryptEventContent(eventContent: Content, eventType: String, userIds: List): Content + /** + * In Megolm, each recipient maintains a record of the ratchet value which allows + * them to decrypt any messages sent in the session after the corresponding point + * in the conversation. If this value is compromised, an attacker can similarly + * decrypt past messages which were encrypted by a key derived from the + * compromised or subsequent ratchet values. This gives 'partial' forward + * secrecy. + * + * To mitigate this issue, the application should offer the user the option to + * discard historical conversations, by winding forward any stored ratchet values, + * or discarding sessions altogether. + */ + fun discardSessionKey() + /** * Re-shares a session key with devices if the key has already been * sent to them. diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt index 815a4f7d125..59ffa5f8748 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt @@ -31,7 +31,6 @@ import im.vector.matrix.android.internal.crypto.actions.EnsureOlmSessionsForDevi import im.vector.matrix.android.internal.crypto.actions.MessageEncrypter import im.vector.matrix.android.internal.crypto.algorithms.IMXDecrypting import im.vector.matrix.android.internal.crypto.keysbackup.DefaultKeysBackupService -import im.vector.matrix.android.internal.crypto.model.CryptoDeviceInfo import im.vector.matrix.android.internal.crypto.model.MXUsersDevicesMap import im.vector.matrix.android.internal.crypto.model.event.EncryptedEventContent import im.vector.matrix.android.internal.crypto.model.event.RoomKeyContent @@ -74,6 +73,7 @@ internal class MXMegolmDecryption(private val userId: String, @Throws(MXCryptoError::class) private fun decryptEvent(event: Event, timeline: String, requestKeysOnFail: Boolean): MXEventDecryptionResult { + Timber.v("## CRYPTO | decryptEvent ${event.eventId} , requestKeysOnFail:$requestKeysOnFail") if (event.roomId.isNullOrBlank()) { throw MXCryptoError.Base(MXCryptoError.ErrorType.MISSING_FIELDS, MXCryptoError.MISSING_FIELDS_REASON) } @@ -191,7 +191,7 @@ internal class MXMegolmDecryption(private val userId: String, val events = timeline.getOrPut(timelineId) { ArrayList() } if (event !in events) { - Timber.v("## addEventToPendingList() : add Event ${event.eventId} in room id ${event.roomId}") + Timber.v("## CRYPTO | addEventToPendingList() : add Event ${event.eventId} in room id ${event.roomId}") events.add(event) } } @@ -202,6 +202,7 @@ internal class MXMegolmDecryption(private val userId: String, * @param event the key event. */ override fun onRoomKeyEvent(event: Event, defaultKeysBackupService: DefaultKeysBackupService) { + Timber.v("## CRYPTO | onRoomKeyEvent()") var exportFormat = false val roomKeyContent = event.getClearContent().toModel() ?: return @@ -210,11 +211,11 @@ internal class MXMegolmDecryption(private val userId: String, val forwardingCurve25519KeyChain: MutableList = ArrayList() if (roomKeyContent.roomId.isNullOrEmpty() || roomKeyContent.sessionId.isNullOrEmpty() || roomKeyContent.sessionKey.isNullOrEmpty()) { - Timber.e("## onRoomKeyEvent() : Key event is missing fields") + Timber.e("## CRYPTO | onRoomKeyEvent() : Key event is missing fields") return } if (event.getClearType() == EventType.FORWARDED_ROOM_KEY) { - Timber.v("## onRoomKeyEvent(), forward adding key : roomId ${roomKeyContent.roomId}" + + Timber.v("## CRYPTO | onRoomKeyEvent(), forward adding key : roomId ${roomKeyContent.roomId}" + " sessionId ${roomKeyContent.sessionId} sessionKey ${roomKeyContent.sessionKey}") val forwardedRoomKeyContent = event.getClearContent().toModel() ?: return @@ -224,7 +225,7 @@ internal class MXMegolmDecryption(private val userId: String, } if (senderKey == null) { - Timber.e("## onRoomKeyEvent() : event is missing sender_key field") + Timber.e("## CRYPTO | onRoomKeyEvent() : event is missing sender_key field") return } @@ -233,18 +234,18 @@ internal class MXMegolmDecryption(private val userId: String, exportFormat = true senderKey = forwardedRoomKeyContent.senderKey if (null == senderKey) { - Timber.e("## onRoomKeyEvent() : forwarded_room_key event is missing sender_key field") + Timber.e("## CRYPTO | onRoomKeyEvent() : forwarded_room_key event is missing sender_key field") return } if (null == forwardedRoomKeyContent.senderClaimedEd25519Key) { - Timber.e("## forwarded_room_key_event is missing sender_claimed_ed25519_key field") + Timber.e("## CRYPTO | forwarded_room_key_event is missing sender_claimed_ed25519_key field") return } keysClaimed["ed25519"] = forwardedRoomKeyContent.senderClaimedEd25519Key } else { - Timber.v("## onRoomKeyEvent(), Adding key : roomId " + roomKeyContent.roomId + " sessionId " + roomKeyContent.sessionId + Timber.v("## CRYPTO | onRoomKeyEvent(), Adding key : roomId " + roomKeyContent.roomId + " sessionId " + roomKeyContent.sessionId + " sessionKey " + roomKeyContent.sessionKey) // from " + event); if (null == senderKey) { @@ -256,6 +257,7 @@ internal class MXMegolmDecryption(private val userId: String, keysClaimed = event.getKeysClaimed().toMutableMap() } + Timber.e("## CRYPTO | onRoomKeyEvent addInboundGroupSession ${roomKeyContent.sessionId}") val added = olmDevice.addInboundGroupSession(roomKeyContent.sessionId, roomKeyContent.sessionKey, roomKeyContent.roomId, @@ -287,7 +289,7 @@ internal class MXMegolmDecryption(private val userId: String, * @param sessionId the session id */ override fun onNewSession(senderKey: String, sessionId: String) { - Timber.v("ON NEW SESSION $sessionId - $senderKey") + Timber.v(" CRYPTO | ON NEW SESSION $sessionId - $senderKey") newSessionListener?.onNewSession(null, senderKey, sessionId) } @@ -321,7 +323,7 @@ internal class MXMegolmDecryption(private val userId: String, // were no one-time keys. return@mapCatching } - Timber.v("## shareKeysWithDevice() : sharing keys for session" + + Timber.v("## CRYPTO | shareKeysWithDevice() : sharing keys for session" + " ${body.senderKey}|${body.sessionId} with device $userId:$deviceId") val payloadJson = mutableMapOf("type" to EventType.FORWARDED_ROOM_KEY) @@ -340,32 +342,11 @@ internal class MXMegolmDecryption(private val userId: String, val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo)) val sendToDeviceMap = MXUsersDevicesMap() sendToDeviceMap.setObject(userId, deviceId, encodedPayload) - Timber.v("## shareKeysWithDevice() : sending to $userId:$deviceId") + Timber.v("## CRYPTO | shareKeysWithDevice() : sending to $userId:$deviceId") val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap) sendToDeviceTask.execute(sendToDeviceParams) } } } } - - fun markOlmSessionForUnwedging(senderId: String, deviceInfo: CryptoDeviceInfo) { - cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { - ensureOlmSessionsForDevicesAction.handle(mapOf(senderId to listOf(deviceInfo)), force = true) - - // Now send a blank message on that session so the other side knows about it. - // (The keyshare request is sent in the clear so that won't do) - // We send this first such that, as long as the toDevice messages arrive in the - // same order we sent them, the other end will get this first, set up the new session, - // then get the keyshare request and send the key over this new session (because it - // is the session it has most recently received a message on). - val payloadJson = mapOf("type" to EventType.DUMMY) - - val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo)) - val sendToDeviceMap = MXUsersDevicesMap() - sendToDeviceMap.setObject(senderId, deviceInfo.deviceId, encodedPayload) - Timber.v("## markOlmSessionForUnwedging() : sending to $senderId:${deviceInfo.deviceId}") - val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap) - sendToDeviceTask.execute(sendToDeviceParams) - } - } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt index addb8c2f76c..3800e3c4f24 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmEncryption.kt @@ -66,17 +66,25 @@ internal class MXMegolmEncryption( override suspend fun encryptEventContent(eventContent: Content, eventType: String, userIds: List): Content { + val ts = System.currentTimeMillis() + Timber.v("## CRYPTO | encryptEventContent : getDevicesInRoom") val devices = getDevicesInRoom(userIds) + Timber.v("## CRYPTO | encryptEventContent ${System.currentTimeMillis() - ts}: getDevicesInRoom ${devices.map}") val outboundSession = ensureOutboundSession(devices) return encryptContent(outboundSession, eventType, eventContent) } + override fun discardSessionKey() { + outboundSession = null + } + /** * Prepare a new session. * * @return the session description */ private fun prepareNewSessionInRoom(): MXOutboundSessionInfo { + Timber.v("## CRYPTO | prepareNewSessionInRoom() ") val sessionId = olmDevice.createOutboundGroupSession() val keysClaimedMap = HashMap() @@ -96,6 +104,7 @@ internal class MXMegolmEncryption( * @param devicesInRoom the devices list */ private suspend fun ensureOutboundSession(devicesInRoom: MXUsersDevicesMap): MXOutboundSessionInfo { + Timber.v("## CRYPTO | ensureOutboundSession start") var session = outboundSession if (session == null // Need to make a brand new session? @@ -132,7 +141,7 @@ internal class MXMegolmEncryption( devicesByUsers: Map>) { // nothing to send, the task is done if (devicesByUsers.isEmpty()) { - Timber.v("## shareKey() : nothing more to do") + Timber.v("## CRYPTO | shareKey() : nothing more to do") return } // reduce the map size to avoid request timeout when there are too many devices (Users size * devices per user) @@ -145,7 +154,7 @@ internal class MXMegolmEncryption( break } } - Timber.v("## shareKey() ; userId ${subMap.keys}") + Timber.v("## CRYPTO | shareKey() ; sessionId<${session.sessionId}> userId ${subMap.keys}") shareUserDevicesKey(session, subMap) val remainingDevices = devicesByUsers - subMap.keys shareKey(session, remainingDevices) @@ -174,10 +183,10 @@ internal class MXMegolmEncryption( payload["content"] = submap var t0 = System.currentTimeMillis() - Timber.v("## shareUserDevicesKey() : starts") + Timber.v("## CRYPTO | shareUserDevicesKey() : starts") val results = ensureOlmSessionsForDevicesAction.handle(devicesByUser) - Timber.v("## shareUserDevicesKey() : ensureOlmSessionsForDevices succeeds after " + Timber.v("## CRYPTO | shareUserDevicesKey() : ensureOlmSessionsForDevices succeeds after " + (System.currentTimeMillis() - t0) + " ms") val contentMap = MXUsersDevicesMap() var haveTargets = false @@ -200,17 +209,17 @@ internal class MXMegolmEncryption( // so just skip it. continue } - Timber.v("## shareUserDevicesKey() : Sharing keys with device $userId:$deviceID") + Timber.v("## CRYPTO | shareUserDevicesKey() : Sharing keys with device $userId:$deviceID") contentMap.setObject(userId, deviceID, messageEncrypter.encryptMessage(payload, listOf(sessionResult.deviceInfo))) haveTargets = true } } if (haveTargets) { t0 = System.currentTimeMillis() - Timber.v("## shareUserDevicesKey() : has target") + Timber.v("## CRYPTO | shareUserDevicesKey() : has target") val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, contentMap) sendToDeviceTask.execute(sendToDeviceParams) - Timber.v("## shareUserDevicesKey() : sendToDevice succeeds after " + Timber.v("## CRYPTO | shareUserDevicesKey() : sendToDevice succeeds after " + (System.currentTimeMillis() - t0) + " ms") // Add the devices we have shared with to session.sharedWithDevices. @@ -224,7 +233,7 @@ internal class MXMegolmEncryption( } } } else { - Timber.v("## shareUserDevicesKey() : no need to sharekey") + Timber.v("## CRYPTO | shareUserDevicesKey() : no need to sharekey") } } @@ -345,7 +354,7 @@ internal class MXMegolmEncryption( val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo)) val sendToDeviceMap = MXUsersDevicesMap() sendToDeviceMap.setObject(userId, deviceId, encodedPayload) - Timber.v("## shareKeysWithDevice() : sending to $userId:$deviceId") + Timber.v("## CRYPTO | CRYPTO | shareKeysWithDevice() : sending to $userId:$deviceId") val sendToDeviceParams = SendToDeviceTask.Params(EventType.ENCRYPTED, sendToDeviceMap) sendToDeviceTask.execute(sendToDeviceParams) return true diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt index b1181fc067e..a9b84a8e48b 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmEncryption.kt @@ -79,6 +79,10 @@ internal class MXOlmEncryption( ensureOlmSessionsForUsersAction.handle(users) } + override fun discardSessionKey() { + // No need for olm + } + override suspend fun reshareKey(sessionId: String, userId: String, deviceId: String, senderKey: String): Boolean { // No need for olm return false diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/sync/CryptoSyncHandler.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/sync/CryptoSyncHandler.kt index 10e7ceb692c..86ca561dfe2 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/sync/CryptoSyncHandler.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/sync/CryptoSyncHandler.kt @@ -39,10 +39,10 @@ internal class CryptoSyncHandler @Inject constructor(private val cryptoService: toDevice.events?.forEachIndexed { index, event -> initialSyncProgressService?.reportProgress(((index / total.toFloat()) * 100).toInt()) // Decrypt event if necessary - decryptEvent(event, null) + decryptToDeviceEvent(event, null) if (event.getClearType() == EventType.MESSAGE && event.getClearContent()?.toModel()?.msgType == "m.bad.encrypted") { - Timber.e("## handleToDeviceEvent() : Warning: Unable to decrypt to-device event : ${event.content}") + Timber.e("## CRYPTO | handleToDeviceEvent() : Warning: Unable to decrypt to-device event : ${event.content}") } else { verificationService.onToDeviceEvent(event) cryptoService.onToDeviceEvent(event) @@ -61,28 +61,24 @@ internal class CryptoSyncHandler @Inject constructor(private val cryptoService: * @param timelineId the timeline identifier * @return true if the event has been decrypted */ - private fun decryptEvent(event: Event, timelineId: String?): Boolean { + private fun decryptToDeviceEvent(event: Event, timelineId: String?): Boolean { + Timber.v("## CRYPTO | decryptToDeviceEvent") if (event.getClearType() == EventType.ENCRYPTED) { var result: MXEventDecryptionResult? = null try { result = cryptoService.decryptEvent(event, timelineId ?: "") } catch (exception: MXCryptoError) { event.mCryptoError = (exception as? MXCryptoError.Base)?.errorType // setCryptoError(exception.cryptoError) + Timber.e("## CRYPTO | Failed to decrypt to device event: ${event.mCryptoError ?: exception}") } if (null != result) { -// event.mxDecryptionResult = MXDecryptionResult( -// payload = result.clearEvent, -// keysClaimed = map -// ) - // TODO persist that? event.mxDecryptionResult = OlmDecryptionResult( payload = result.clearEvent, senderKey = result.senderCurve25519Key, keysClaimed = result.claimedEd25519Key?.let { mapOf("ed25519" to it) }, forwardingCurve25519KeyChain = result.forwardingCurve25519KeyChain ) -// event.setClearData(result) return true } } diff --git a/vector/src/main/java/im/vector/riotx/features/command/Command.kt b/vector/src/main/java/im/vector/riotx/features/command/Command.kt index 72f686c2c8f..ebfea570446 100644 --- a/vector/src/main/java/im/vector/riotx/features/command/Command.kt +++ b/vector/src/main/java/im/vector/riotx/features/command/Command.kt @@ -44,6 +44,7 @@ enum class Command(val command: String, val parameters: String, @StringRes val d POLL("/poll", "Question | Option 1 | Option 2 ...", R.string.command_description_poll), SHRUG("/shrug", "", R.string.command_description_shrug), PLAIN("/plain", "", R.string.command_description_plain), + DISCARD_SESSION("/discardsession", "", R.string.command_description_discard_session), // TODO temporary command VERIFY_USER("/verify", "", R.string.command_description_verify); diff --git a/vector/src/main/java/im/vector/riotx/features/command/CommandParser.kt b/vector/src/main/java/im/vector/riotx/features/command/CommandParser.kt index 875fe926105..e7d2e9a62b0 100644 --- a/vector/src/main/java/im/vector/riotx/features/command/CommandParser.kt +++ b/vector/src/main/java/im/vector/riotx/features/command/CommandParser.kt @@ -281,6 +281,9 @@ object CommandParser { ParsedCommand.ErrorSyntax(Command.POLL) } } + Command.DISCARD_SESSION.command -> { + ParsedCommand.DiscardSession + } else -> { // Unknown command ParsedCommand.ErrorUnknownSlashCommand(slashCommand) diff --git a/vector/src/main/java/im/vector/riotx/features/command/ParsedCommand.kt b/vector/src/main/java/im/vector/riotx/features/command/ParsedCommand.kt index e4fee27ee6f..63e016b0b60 100644 --- a/vector/src/main/java/im/vector/riotx/features/command/ParsedCommand.kt +++ b/vector/src/main/java/im/vector/riotx/features/command/ParsedCommand.kt @@ -52,4 +52,5 @@ sealed class ParsedCommand { class SendShrug(val message: CharSequence) : ParsedCommand() class VerifyUser(val userId: String) : ParsedCommand() class SendPoll(val question: String, val options: List) : ParsedCommand() + object DiscardSession: ParsedCommand() } diff --git a/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt b/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt index cef172da73f..73b03a77520 100644 --- a/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt +++ b/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt @@ -447,6 +447,9 @@ class RoomDetailViewModel @AssistedInject constructor( // TODO _viewEvents.post(RoomDetailViewEvents.SlashCommandNotImplemented) } + is ParsedCommand.DiscardSession -> { + session.cryptoService().discardOutbundSession(room.roomId) + } }.exhaustive } is SendMode.EDIT -> { diff --git a/vector/src/main/res/values/strings_riotX.xml b/vector/src/main/res/values/strings_riotX.xml index 3e23f61acf0..a25d3bbe356 100644 --- a/vector/src/main/res/values/strings_riotX.xml +++ b/vector/src/main/res/values/strings_riotX.xml @@ -6,7 +6,7 @@ - + Forces the current outbound group session in an encrypted room to be discarded From d0f776a9cf8db2544ce2e60fb4ca3ddab44e24bf Mon Sep 17 00:00:00 2001 From: Valere Date: Wed, 22 Apr 2020 16:41:34 +0200 Subject: [PATCH 17/18] Discard session command only encrypted room --- .../java/im/vector/riotx/features/command/Command.kt | 2 +- .../features/home/room/detail/RoomDetailViewModel.kt | 12 +++++++++++- vector/src/main/res/values/strings_riotX.xml | 1 + 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/vector/src/main/java/im/vector/riotx/features/command/Command.kt b/vector/src/main/java/im/vector/riotx/features/command/Command.kt index ebfea570446..4046880ebd6 100644 --- a/vector/src/main/java/im/vector/riotx/features/command/Command.kt +++ b/vector/src/main/java/im/vector/riotx/features/command/Command.kt @@ -44,7 +44,7 @@ enum class Command(val command: String, val parameters: String, @StringRes val d POLL("/poll", "Question | Option 1 | Option 2 ...", R.string.command_description_poll), SHRUG("/shrug", "", R.string.command_description_shrug), PLAIN("/plain", "", R.string.command_description_plain), - DISCARD_SESSION("/discardsession", "", R.string.command_description_discard_session), + DISCARD_SESSION("/discardsession","", R.string.command_description_discard_session), // TODO temporary command VERIFY_USER("/verify", "", R.string.command_description_verify); diff --git a/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt b/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt index 73b03a77520..1d74751de53 100644 --- a/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt +++ b/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt @@ -448,7 +448,17 @@ class RoomDetailViewModel @AssistedInject constructor( _viewEvents.post(RoomDetailViewEvents.SlashCommandNotImplemented) } is ParsedCommand.DiscardSession -> { - session.cryptoService().discardOutbundSession(room.roomId) + if (room.isEncrypted()) { + session.cryptoService().discardOutbundSession(room.roomId) + _viewEvents.post(RoomDetailViewEvents.SlashCommandHandled()) + popDraft() + } else { + _viewEvents.post(RoomDetailViewEvents.SlashCommandHandled()) + _viewEvents.post( + RoomDetailViewEvents + .ShowMessage(stringProvider.getString(R.string.command_description_discard_session_not_handled)) + ) + } } }.exhaustive } diff --git a/vector/src/main/res/values/strings_riotX.xml b/vector/src/main/res/values/strings_riotX.xml index a25d3bbe356..580144c26d5 100644 --- a/vector/src/main/res/values/strings_riotX.xml +++ b/vector/src/main/res/values/strings_riotX.xml @@ -7,6 +7,7 @@ Forces the current outbound group session in an encrypted room to be discarded + Only supported in encrypted rooms From e37dd547b8debc08bcdd191b78b682abe0b79ade Mon Sep 17 00:00:00 2001 From: Valere Date: Wed, 22 Apr 2020 18:50:59 +0200 Subject: [PATCH 18/18] code review --- .../android/internal/crypto/UnwedgingTest.kt | 9 ++-- .../api/session/crypto/CryptoService.kt | 2 +- .../internal/crypto/DefaultCryptoService.kt | 46 ++++++------------- .../vector/riotx/features/command/Command.kt | 2 +- .../home/room/detail/RoomDetailViewModel.kt | 2 +- 5 files changed, 20 insertions(+), 41 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt index 7f75d7d6fd8..6391c0392cb 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/internal/crypto/UnwedgingTest.kt @@ -88,8 +88,8 @@ class UnwedgingTest : InstrumentedTest { val aliceCryptoStore = (aliceSession.cryptoService() as DefaultCryptoService).cryptoStoreForTesting - //bobSession.cryptoService().setWarnOnUnknownDevices(false) - //aliceSession.cryptoService().setWarnOnUnknownDevices(false) + // bobSession.cryptoService().setWarnOnUnknownDevices(false) + // aliceSession.cryptoService().setWarnOnUnknownDevices(false) val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! @@ -143,7 +143,7 @@ class UnwedgingTest : InstrumentedTest { val oldSession = serializeForRealm(olmSession.olmSession) - aliceSession.cryptoService().discardOutbundSession(roomFromAlicePOV.roomId) + aliceSession.cryptoService().discardOutboundSession(roomFromAlicePOV.roomId) Thread.sleep(6_000) latch = CountDownLatch(1) @@ -171,7 +171,7 @@ class UnwedgingTest : InstrumentedTest { Thread.sleep(6_000) // Force new session, and key share - aliceSession.cryptoService().discardOutbundSession(roomFromAlicePOV.roomId) + aliceSession.cryptoService().discardOutboundSession(roomFromAlicePOV.roomId) // Wait for the message to be received by Bob mTestHelper.waitWithLatch { @@ -220,7 +220,6 @@ class UnwedgingTest : InstrumentedTest { } } - bobTimeline.dispose() cryptoTestData.cleanUp(mTestHelper) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/crypto/CryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/crypto/CryptoService.kt index a923b2cc3d0..e6fbaaf9a69 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/crypto/CryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/crypto/CryptoService.kt @@ -111,7 +111,7 @@ interface CryptoService { roomId: String, callback: MatrixCallback) - fun discardOutbundSession(roomId: String) + fun discardOutboundSession(roomId: String) @Throws(MXCryptoError::class) fun decryptEvent(event: Event, timeline: String): MXEventDecryptionResult diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt index e865998fa9d..a7898149580 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/DefaultCryptoService.kt @@ -635,7 +635,7 @@ internal class DefaultCryptoService @Inject constructor( } } - override fun discardOutbundSession(roomId: String) { + override fun discardOutboundSession(roomId: String) { cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { roomEncryptorsStore.get(roomId)?.discardSessionKey() } @@ -718,38 +718,6 @@ internal class DefaultCryptoService @Inject constructor( } } -// private fun markOlmSessionForUnwedging(event: Event, mxMegolmDecryption: MXMegolmDecryption) { -// Timber.d("## CRYPTO |  markOlmSessionForUnwedging: ${event.eventId}") -// val senderId = event.senderId ?: return -// val encryptedMessage = event.content.toModel() ?: return -// val deviceKey = encryptedMessage.senderKey ?: return -// encryptedMessage.algorithm?.takeIf { it == MXCRYPTO_ALGORITHM_MEGOLM } ?: return -// -// if (senderId == userId -// && deviceKey == olmDevice.deviceCurve25519Key) { -// Timber.d("## CRYPTO |  markOlmSessionForUnwedging: Do not unwedge ourselves") -// return -// } -// -// val lastForcedDate = lastNewSessionForcedDates.getObject(senderId, deviceKey) ?: 0 -// val now = System.currentTimeMillis() -// if (now - lastForcedDate < CRYPTO_MIN_FORCE_SESSION_PERIOD_MILLIS) { -// Timber.d("## CRYPTO | markOlmSessionForUnwedging: New session already forced with device at $lastForcedDate. Not forcing another") -// return -// } -// -// // Establish a new olm session with this device since we're failing to decrypt messages -// // on a current session. -// val deviceInfo = getDeviceInfo(senderId, deviceKey) ?: return Unit.also { -// Timber.d("## CRYPTO | markOlmSessionForUnwedging: Couldn't find device for identity key $deviceKey: not re-establishing session") -// } -// -// Timber.d("## CRYPTO | markOlmSessionForUnwedging from $senderId:${deviceInfo.deviceId}") -// lastNewSessionForcedDates.setObject(senderId, deviceKey, now) -// -// mxMegolmDecryption.markOlmSessionForUnwedging(senderId, deviceInfo) -// } - /** * Reset replay attack data for the given timeline. * @@ -1197,6 +1165,18 @@ internal class DefaultCryptoService @Inject constructor( } private fun markOlmSessionForUnwedging(senderId: String, deviceInfo: CryptoDeviceInfo) { + val deviceKey = deviceInfo.identityKey() + + val lastForcedDate = lastNewSessionForcedDates.getObject(senderId, deviceKey) ?: 0 + val now = System.currentTimeMillis() + if (now - lastForcedDate < CRYPTO_MIN_FORCE_SESSION_PERIOD_MILLIS) { + Timber.d("## CRYPTO | markOlmSessionForUnwedging: New session already forced with device at $lastForcedDate. Not forcing another") + return + } + + Timber.d("## CRYPTO | markOlmSessionForUnwedging from $senderId:${deviceInfo.deviceId}") + lastNewSessionForcedDates.setObject(senderId, deviceKey, now) + cryptoCoroutineScope.launch(coroutineDispatchers.crypto) { ensureOlmSessionsForDevicesAction.handle(mapOf(senderId to listOf(deviceInfo)), force = true) diff --git a/vector/src/main/java/im/vector/riotx/features/command/Command.kt b/vector/src/main/java/im/vector/riotx/features/command/Command.kt index 4046880ebd6..d98ebcfa736 100644 --- a/vector/src/main/java/im/vector/riotx/features/command/Command.kt +++ b/vector/src/main/java/im/vector/riotx/features/command/Command.kt @@ -44,7 +44,7 @@ enum class Command(val command: String, val parameters: String, @StringRes val d POLL("/poll", "Question | Option 1 | Option 2 ...", R.string.command_description_poll), SHRUG("/shrug", "", R.string.command_description_shrug), PLAIN("/plain", "", R.string.command_description_plain), - DISCARD_SESSION("/discardsession","", R.string.command_description_discard_session), + DISCARD_SESSION("/discardsession", "", R.string.command_description_discard_session), // TODO temporary command VERIFY_USER("/verify", "", R.string.command_description_verify); diff --git a/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt b/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt index 1d74751de53..d0dcac6ecc8 100644 --- a/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt +++ b/vector/src/main/java/im/vector/riotx/features/home/room/detail/RoomDetailViewModel.kt @@ -449,7 +449,7 @@ class RoomDetailViewModel @AssistedInject constructor( } is ParsedCommand.DiscardSession -> { if (room.isEncrypted()) { - session.cryptoService().discardOutbundSession(room.roomId) + session.cryptoService().discardOutboundSession(room.roomId) _viewEvents.post(RoomDetailViewEvents.SlashCommandHandled()) popDraft() } else {