Rename class members and class name for code clarity

This commit is contained in:
Benoit Marty 2019-06-11 13:32:09 +02:00
parent 2e39a678db
commit f6c36670c3
36 changed files with 346 additions and 422 deletions

View File

@ -16,7 +16,7 @@
package im.vector.matrix.android.internal.crypto package im.vector.matrix.android.internal.crypto
import im.vector.matrix.android.internal.crypto.model.MXOlmSession import im.vector.matrix.android.internal.crypto.model.OlmSessionWrapper
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import org.junit.Assert.* import org.junit.Assert.*
import org.junit.Test import org.junit.Test
@ -67,9 +67,9 @@ class CryptoStoreTest {
} }
val sessionId1 = olmSession1.sessionIdentifier() val sessionId1 = olmSession1.sessionIdentifier()
val mxOlmSession1 = MXOlmSession(olmSession1) val olmSessionWrapper1 = OlmSessionWrapper(olmSession1)
cryptoStore.storeSession(mxOlmSession1, DUMMY_DEVICE_KEY) cryptoStore.storeSession(olmSessionWrapper1, DUMMY_DEVICE_KEY)
assertEquals(sessionId1, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY)) assertEquals(sessionId1, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))
@ -84,25 +84,25 @@ class CryptoStoreTest {
} }
val sessionId2 = olmSession2.sessionIdentifier() val sessionId2 = olmSession2.sessionIdentifier()
val mxOlmSession2 = MXOlmSession(olmSession2) val olmSessionWrapper2 = OlmSessionWrapper(olmSession2)
cryptoStore.storeSession(mxOlmSession2, DUMMY_DEVICE_KEY) cryptoStore.storeSession(olmSessionWrapper2, DUMMY_DEVICE_KEY)
// Ensure sessionIds are distinct // Ensure sessionIds are distinct
assertNotEquals(sessionId1, sessionId2) assertNotEquals(sessionId1, sessionId2)
// Note: we cannot be sure what will be the result of getLastUsedSessionId() here // Note: we cannot be sure what will be the result of getLastUsedSessionId() here
mxOlmSession2.onMessageReceived() olmSessionWrapper2.onMessageReceived()
cryptoStore.storeSession(mxOlmSession2, DUMMY_DEVICE_KEY) cryptoStore.storeSession(olmSessionWrapper2, DUMMY_DEVICE_KEY)
// sessionId2 is returned now // sessionId2 is returned now
assertEquals(sessionId2, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY)) assertEquals(sessionId2, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))
Thread.sleep(2) Thread.sleep(2)
mxOlmSession1.onMessageReceived() olmSessionWrapper1.onMessageReceived()
cryptoStore.storeSession(mxOlmSession1, DUMMY_DEVICE_KEY) cryptoStore.storeSession(olmSessionWrapper1, DUMMY_DEVICE_KEY)
// sessionId1 is returned now // sessionId1 is returned now
assertEquals(sessionId1, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY)) assertEquals(sessionId1, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))

View File

@ -49,7 +49,7 @@ interface KeysBackupService {
fun restoreKeysWithRecoveryKey(keysVersionResult: KeysVersionResult, recoveryKey: String, roomId: String?, sessionId: String?, stepProgressListener: StepProgressListener?, callback: MatrixCallback<ImportRoomKeysResult>) fun restoreKeysWithRecoveryKey(keysVersionResult: KeysVersionResult, recoveryKey: String, roomId: String?, sessionId: String?, stepProgressListener: StepProgressListener?, callback: MatrixCallback<ImportRoomKeysResult>)
fun restoreKeyBackupWithPassword(keysBackupVersion: KeysVersionResult, password: String, roomId: String?, sessionId: String?, stepProgressListener: StepProgressListener?, callback: MatrixCallback<ImportRoomKeysResult>) fun restoreKeyBackupWithPassword(keysBackupVersion: KeysVersionResult, password: String, roomId: String?, sessionId: String?, stepProgressListener: StepProgressListener?, callback: MatrixCallback<ImportRoomKeysResult>)
val mKeysBackupVersion: KeysVersionResult? val keysBackupVersion: KeysVersionResult?
val currentBackupVersion: String? val currentBackupVersion: String?
val isEnabled: Boolean val isEnabled: Boolean
val isStucked: Boolean val isStucked: Boolean

View File

@ -151,9 +151,6 @@ internal class CryptoManager(
} }
} }
// initialization callbacks
private val mInitializationCallbacks = ArrayList<MatrixCallback<Unit>>()
override fun setDeviceName(deviceId: String, deviceName: String, callback: MatrixCallback<Unit>) { override fun setDeviceName(deviceId: String, deviceName: String, callback: MatrixCallback<Unit>) {
setDeviceNameTask setDeviceNameTask
.configureWith(SetDeviceNameTask.Params(deviceId, deviceName)) .configureWith(SetDeviceNameTask.Params(deviceId, deviceName))
@ -491,7 +488,7 @@ internal class CryptoManager(
} }
fun isEncryptionEnabledForInvitedUser(): Boolean { fun isEncryptionEnabledForInvitedUser(): Boolean {
return cryptoConfig.mEnableEncryptionForInvitedMembers return cryptoConfig.enableEncryptionForInvitedMembers
} }
override fun getEncryptionAlgorithm(roomId: String): String? { override fun getEncryptionAlgorithm(roomId: String): String? {
@ -732,7 +729,7 @@ internal class CryptoManager(
deviceListManager.startTrackingDeviceList(Arrays.asList(userId)) deviceListManager.startTrackingDeviceList(Arrays.asList(userId))
} else if (membership == Membership.INVITE } else if (membership == Membership.INVITE
&& shouldEncryptForInvitedMembers(roomId) && shouldEncryptForInvitedMembers(roomId)
&& cryptoConfig.mEnableEncryptionForInvitedMembers) { && cryptoConfig.enableEncryptionForInvitedMembers) {
// track the deviceList for this invited user. // track the deviceList for this invited user.
// Caution: there's a big edge case here in that federated servers do not // Caution: there's a big edge case here in that federated servers do not
// know what other servers are in the room at the time they've been invited. // know what other servers are in the room at the time they've been invited.

View File

@ -23,5 +23,5 @@ data class MXCryptoConfig(
// Tell whether the encryption of the event content is enabled for the invited members. // Tell whether the encryption of the event content is enabled for the invited members.
// By default, we encrypt messages only for the joined members. // By default, we encrypt messages only for the joined members.
// The encryption for the invited members will be blocked if the history visibility is "joined". // The encryption for the invited members will be blocked if the history visibility is "joined".
var mEnableEncryptionForInvitedMembers: Boolean = false var enableEncryptionForInvitedMembers: Boolean = false
) )

View File

@ -41,8 +41,8 @@ object MXEncryptedAttachments {
* Define the result of an encryption file * Define the result of an encryption file
*/ */
data class EncryptionResult( data class EncryptionResult(
var mEncryptedFileInfo: EncryptedFileInfo, var encryptedFileInfo: EncryptedFileInfo,
var mEncryptedStream: InputStream var encryptedStream: InputStream
) )
/*** /***
@ -98,7 +98,7 @@ object MXEncryptedAttachments {
outStream.write(encodedBytes) outStream.write(encodedBytes)
val result = EncryptionResult( val result = EncryptionResult(
mEncryptedFileInfo = EncryptedFileInfo( encryptedFileInfo = EncryptedFileInfo(
url = null, url = null,
mimetype = mimetype, mimetype = mimetype,
key = EncryptedFileKey( key = EncryptedFileKey(
@ -112,7 +112,7 @@ object MXEncryptedAttachments {
hashes = mapOf("sha256" to base64ToUnpaddedBase64(Base64.encodeToString(messageDigest.digest(), Base64.DEFAULT))!!), hashes = mapOf("sha256" to base64ToUnpaddedBase64(Base64.encodeToString(messageDigest.digest(), Base64.DEFAULT))!!),
v = "v2" v = "v2"
), ),
mEncryptedStream = ByteArrayInputStream(outStream.toByteArray()) encryptedStream = ByteArrayInputStream(outStream.toByteArray())
) )
outStream.close() outStream.close()

View File

@ -22,8 +22,8 @@ import im.vector.matrix.android.api.session.crypto.MXCryptoError
import im.vector.matrix.android.api.util.JSON_DICT_PARAMETERIZED_TYPE import im.vector.matrix.android.api.util.JSON_DICT_PARAMETERIZED_TYPE
import im.vector.matrix.android.api.util.JsonDict import im.vector.matrix.android.api.util.JsonDict
import im.vector.matrix.android.internal.crypto.algorithms.MXDecryptionResult import im.vector.matrix.android.internal.crypto.algorithms.MXDecryptionResult
import im.vector.matrix.android.internal.crypto.model.MXOlmInboundGroupSession2 import im.vector.matrix.android.internal.crypto.model.OlmInboundGroupSessionWrapper
import im.vector.matrix.android.internal.crypto.model.MXOlmSession import im.vector.matrix.android.internal.crypto.model.OlmSessionWrapper
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.di.MoshiProvider import im.vector.matrix.android.internal.di.MoshiProvider
import im.vector.matrix.android.internal.util.convertFromUTF8 import im.vector.matrix.android.internal.util.convertFromUTF8
@ -206,14 +206,14 @@ internal class MXOlmDevice(
olmSession = OlmSession() olmSession = OlmSession()
olmSession.initOutboundSession(olmAccount!!, theirIdentityKey, theirOneTimeKey) olmSession.initOutboundSession(olmAccount!!, theirIdentityKey, theirOneTimeKey)
val mxOlmSession = MXOlmSession(olmSession, 0) val olmSessionWrapper = OlmSessionWrapper(olmSession, 0)
// Pretend we've received a message at this point, otherwise // Pretend we've received a message at this point, otherwise
// if we try to send a message to the device, it won't use // if we try to send a message to the device, it won't use
// this session // this session
mxOlmSession.onMessageReceived() olmSessionWrapper.onMessageReceived()
store.storeSession(mxOlmSession, theirIdentityKey) store.storeSession(olmSessionWrapper, theirIdentityKey)
val sessionIdentifier = olmSession.sessionIdentifier() val sessionIdentifier = olmSession.sessionIdentifier()
@ -278,11 +278,11 @@ internal class MXOlmDevice(
try { try {
payloadString = olmSession.decryptMessage(olmMessage) payloadString = olmSession.decryptMessage(olmMessage)
val mxOlmSession = MXOlmSession(olmSession, 0) val olmSessionWrapper = OlmSessionWrapper(olmSession, 0)
// This counts as a received message: set last received message time to now // This counts as a received message: set last received message time to now
mxOlmSession.onMessageReceived() olmSessionWrapper.onMessageReceived()
store.storeSession(mxOlmSession, theirDeviceIdentityKey) store.storeSession(olmSessionWrapper, theirDeviceIdentityKey)
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e, "## createInboundSession() : decryptMessage failed") Timber.e(e, "## createInboundSession() : decryptMessage failed")
} }
@ -340,15 +340,15 @@ internal class MXOlmDevice(
fun encryptMessage(theirDeviceIdentityKey: String, sessionId: String, payloadString: String): Map<String, Any>? { fun encryptMessage(theirDeviceIdentityKey: String, sessionId: String, payloadString: String): Map<String, Any>? {
var res: MutableMap<String, Any>? = null var res: MutableMap<String, Any>? = null
val olmMessage: OlmMessage val olmMessage: OlmMessage
val mxOlmSession = getSessionForDevice(theirDeviceIdentityKey, sessionId) val olmSessionWrapper = getSessionForDevice(theirDeviceIdentityKey, sessionId)
if (mxOlmSession != null) { if (olmSessionWrapper != null) {
try { try {
Timber.v("## encryptMessage() : olmSession.sessionIdentifier: $sessionId") Timber.v("## encryptMessage() : olmSession.sessionIdentifier: $sessionId")
//Timber.v("## encryptMessage() : payloadString: " + payloadString); //Timber.v("## encryptMessage() : payloadString: " + payloadString);
olmMessage = mxOlmSession.olmSession.encryptMessage(payloadString) olmMessage = olmSessionWrapper.olmSession.encryptMessage(payloadString)
store.storeSession(mxOlmSession, theirDeviceIdentityKey) store.storeSession(olmSessionWrapper, theirDeviceIdentityKey)
res = HashMap() res = HashMap()
res["body"] = olmMessage.mCipherText res["body"] = olmMessage.mCipherText
@ -374,17 +374,17 @@ internal class MXOlmDevice(
fun decryptMessage(ciphertext: String, messageType: Int, sessionId: String, theirDeviceIdentityKey: String): String? { fun decryptMessage(ciphertext: String, messageType: Int, sessionId: String, theirDeviceIdentityKey: String): String? {
var payloadString: String? = null var payloadString: String? = null
val mxOlmSession = getSessionForDevice(theirDeviceIdentityKey, sessionId) val olmSessionWrapper = getSessionForDevice(theirDeviceIdentityKey, sessionId)
if (null != mxOlmSession) { if (null != olmSessionWrapper) {
val olmMessage = OlmMessage() val olmMessage = OlmMessage()
olmMessage.mCipherText = ciphertext olmMessage.mCipherText = ciphertext
olmMessage.mType = messageType.toLong() olmMessage.mType = messageType.toLong()
try { try {
payloadString = mxOlmSession.olmSession.decryptMessage(olmMessage) payloadString = olmSessionWrapper.olmSession.decryptMessage(olmMessage)
mxOlmSession.onMessageReceived() olmSessionWrapper.onMessageReceived()
store.storeSession(mxOlmSession, theirDeviceIdentityKey) store.storeSession(olmSessionWrapper, theirDeviceIdentityKey)
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e, "## decryptMessage() : decryptMessage failed " + e.message) Timber.e(e, "## decryptMessage() : decryptMessage failed " + e.message)
} }
@ -408,8 +408,8 @@ internal class MXOlmDevice(
return false return false
} }
val mxOlmSession = getSessionForDevice(theirDeviceIdentityKey, sessionId) val olmSessionWrapper = getSessionForDevice(theirDeviceIdentityKey, sessionId)
return null != mxOlmSession && mxOlmSession.olmSession.matchesInboundSession(ciphertext) return null != olmSessionWrapper && olmSessionWrapper.olmSession.matchesInboundSession(ciphertext)
} }
@ -506,7 +506,7 @@ internal class MXOlmDevice(
keysClaimed: Map<String, String>, keysClaimed: Map<String, String>,
exportFormat: Boolean): Boolean { exportFormat: Boolean): Boolean {
val existingInboundSession = getInboundGroupSession(sessionId, senderKey, roomId) val existingInboundSession = getInboundGroupSession(sessionId, senderKey, roomId)
val session = MXOlmInboundGroupSession2(sessionKey, exportFormat) val session = OlmInboundGroupSessionWrapper(sessionKey, exportFormat)
if (null != existingInboundSession) { if (null != existingInboundSession) {
// If we already have this session, consider updating it // If we already have this session, consider updating it
@ -517,35 +517,35 @@ internal class MXOlmDevice(
//If our existing session is better we keep it //If our existing session is better we keep it
if (newKnownFirstIndex != null && existingFirstKnown <= newKnownFirstIndex) { if (newKnownFirstIndex != null && existingFirstKnown <= newKnownFirstIndex) {
if (session.mSession != null) { if (session.olmInboundGroupSession != null) {
session.mSession!!.releaseSession() session.olmInboundGroupSession!!.releaseSession()
} }
return false return false
} }
} }
// sanity check // sanity check
if (null == session.mSession) { if (null == session.olmInboundGroupSession) {
Timber.e("## addInboundGroupSession : invalid session") Timber.e("## addInboundGroupSession : invalid session")
return false return false
} }
try { try {
if (!TextUtils.equals(session.mSession!!.sessionIdentifier(), sessionId)) { if (!TextUtils.equals(session.olmInboundGroupSession!!.sessionIdentifier(), sessionId)) {
Timber.e("## addInboundGroupSession : ERROR: Mismatched group session ID from senderKey: $senderKey") Timber.e("## addInboundGroupSession : ERROR: Mismatched group session ID from senderKey: $senderKey")
session.mSession!!.releaseSession() session.olmInboundGroupSession!!.releaseSession()
return false return false
} }
} catch (e: Exception) { } catch (e: Exception) {
session.mSession!!.releaseSession() session.olmInboundGroupSession!!.releaseSession()
Timber.e(e, "## addInboundGroupSession : sessionIdentifier() failed") Timber.e(e, "## addInboundGroupSession : sessionIdentifier() failed")
return false return false
} }
session.mSenderKey = senderKey session.senderKey = senderKey
session.mRoomId = roomId session.roomId = roomId
session.mKeysClaimed = keysClaimed session.keysClaimed = keysClaimed
session.mForwardingCurve25519KeyChain = forwardingCurve25519KeyChain session.forwardingCurve25519KeyChain = forwardingCurve25519KeyChain
store.storeInboundGroupSessions(listOf(session)) store.storeInboundGroupSessions(listOf(session))
@ -558,8 +558,8 @@ internal class MXOlmDevice(
* @param megolmSessionsData the megolm sessions data * @param megolmSessionsData the megolm sessions data
* @return the successfully imported sessions. * @return the successfully imported sessions.
*/ */
fun importInboundGroupSessions(megolmSessionsData: List<MegolmSessionData>): List<MXOlmInboundGroupSession2> { fun importInboundGroupSessions(megolmSessionsData: List<MegolmSessionData>): List<OlmInboundGroupSessionWrapper> {
val sessions = ArrayList<MXOlmInboundGroupSession2>(megolmSessionsData.size) val sessions = ArrayList<OlmInboundGroupSessionWrapper>(megolmSessionsData.size)
for (megolmSessionData in megolmSessionsData) { for (megolmSessionData in megolmSessionsData) {
@ -567,29 +567,29 @@ internal class MXOlmDevice(
val senderKey = megolmSessionData.senderKey val senderKey = megolmSessionData.senderKey
val roomId = megolmSessionData.roomId val roomId = megolmSessionData.roomId
var session: MXOlmInboundGroupSession2? = null var session: OlmInboundGroupSessionWrapper? = null
try { try {
session = MXOlmInboundGroupSession2(megolmSessionData) session = OlmInboundGroupSessionWrapper(megolmSessionData)
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e, "## importInboundGroupSession() : Update for megolm session $senderKey/$sessionId") Timber.e(e, "## importInboundGroupSession() : Update for megolm session $senderKey/$sessionId")
} }
// sanity check // sanity check
if (null == session || null == session.mSession) { if (null == session || null == session.olmInboundGroupSession) {
Timber.e("## importInboundGroupSession : invalid session") Timber.e("## importInboundGroupSession : invalid session")
continue continue
} }
try { try {
if (!TextUtils.equals(session.mSession!!.sessionIdentifier(), sessionId)) { if (!TextUtils.equals(session.olmInboundGroupSession!!.sessionIdentifier(), sessionId)) {
Timber.e("## importInboundGroupSession : ERROR: Mismatched group session ID from senderKey: " + senderKey!!) Timber.e("## importInboundGroupSession : ERROR: Mismatched group session ID from senderKey: " + senderKey!!)
if (session.mSession != null) session.mSession!!.releaseSession() if (session.olmInboundGroupSession != null) session.olmInboundGroupSession!!.releaseSession()
continue continue
} }
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e, "## importInboundGroupSession : sessionIdentifier() failed") Timber.e(e, "## importInboundGroupSession : sessionIdentifier() failed")
session.mSession!!.releaseSession() session.olmInboundGroupSession!!.releaseSession()
continue continue
} }
@ -601,7 +601,7 @@ internal class MXOlmDevice(
// For now we just ignore updates. TODO: implement something here // For now we just ignore updates. TODO: implement something here
if (existingOlmSession.firstKnownIndex!! <= session.firstKnownIndex!!) { if (existingOlmSession.firstKnownIndex!! <= session.firstKnownIndex!!) {
//Ignore this, keep existing //Ignore this, keep existing
session.mSession!!.releaseSession() session.olmInboundGroupSession!!.releaseSession()
continue continue
} }
} }
@ -648,11 +648,11 @@ internal class MXOlmDevice(
if (null != session) { if (null != session) {
// Check that the room id matches the original one for the session. This stops // Check that the room id matches the original one for the session. This stops
// the HS pretending a message was targeting a different room. // the HS pretending a message was targeting a different room.
if (TextUtils.equals(roomId, session.mRoomId)) { if (TextUtils.equals(roomId, session.roomId)) {
var errorMessage = "" var errorMessage = ""
var decryptResult: OlmInboundGroupSession.DecryptMessageResult? = null var decryptResult: OlmInboundGroupSession.DecryptMessageResult? = null
try { try {
decryptResult = session.mSession!!.decryptMessage(body) decryptResult = session.olmInboundGroupSession!!.decryptMessage(body)
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e, "## decryptGroupMessage () : decryptMessage failed") Timber.e(e, "## decryptGroupMessage () : decryptMessage failed")
errorMessage = e.message ?: "" errorMessage = e.message ?: ""
@ -692,15 +692,15 @@ internal class MXOlmDevice(
return null return null
} }
result.keysClaimed = session.mKeysClaimed result.keysClaimed = session.keysClaimed
result.senderKey = senderKey result.senderKey = senderKey
result.forwardingCurve25519KeyChain = session.mForwardingCurve25519KeyChain result.forwardingCurve25519KeyChain = session.forwardingCurve25519KeyChain
} else { } else {
Timber.e("## decryptGroupMessage() : failed to decode the message") Timber.e("## decryptGroupMessage() : failed to decode the message")
throw MXDecryptionException(MXCryptoError(MXCryptoError.OLM_ERROR_CODE, errorMessage, null)) throw MXDecryptionException(MXCryptoError(MXCryptoError.OLM_ERROR_CODE, errorMessage, null))
} }
} else { } else {
val reason = String.format(MXCryptoError.INBOUND_SESSION_MISMATCH_ROOM_ID_REASON, roomId, session.mRoomId) val reason = String.format(MXCryptoError.INBOUND_SESSION_MISMATCH_ROOM_ID_REASON, roomId, session.roomId)
Timber.e("## decryptGroupMessage() : $reason") Timber.e("## decryptGroupMessage() : $reason")
throw MXDecryptionException(MXCryptoError(MXCryptoError.INBOUND_SESSION_MISMATCH_ROOM_ID_ERROR_CODE, throw MXDecryptionException(MXCryptoError(MXCryptoError.INBOUND_SESSION_MISMATCH_ROOM_ID_ERROR_CODE,
MXCryptoError.UNABLE_TO_DECRYPT, reason)) MXCryptoError.UNABLE_TO_DECRYPT, reason))
@ -757,7 +757,7 @@ internal class MXOlmDevice(
* @param sessionId the session Id * @param sessionId the session Id
* @return the olm session * @return the olm session
*/ */
private fun getSessionForDevice(theirDeviceIdentityKey: String, sessionId: String): MXOlmSession? { private fun getSessionForDevice(theirDeviceIdentityKey: String, sessionId: String): OlmSessionWrapper? {
// sanity check // sanity check
return if (!TextUtils.isEmpty(theirDeviceIdentityKey) && !TextUtils.isEmpty(sessionId)) { return if (!TextUtils.isEmpty(theirDeviceIdentityKey) && !TextUtils.isEmpty(sessionId)) {
store.getDeviceSession(sessionId, theirDeviceIdentityKey) store.getDeviceSession(sessionId, theirDeviceIdentityKey)
@ -774,7 +774,7 @@ internal class MXOlmDevice(
* @param senderKey the base64-encoded curve25519 key of the sender. * @param senderKey the base64-encoded curve25519 key of the sender.
* @return the inbound group session. * @return the inbound group session.
*/ */
fun getInboundGroupSession(sessionId: String?, senderKey: String?, roomId: String?): MXOlmInboundGroupSession2? { fun getInboundGroupSession(sessionId: String?, senderKey: String?, roomId: String?): OlmInboundGroupSessionWrapper? {
inboundGroupSessionWithIdError = null inboundGroupSessionWithIdError = null
val session = store.getInboundGroupSession(sessionId!!, senderKey!!) val session = store.getInboundGroupSession(sessionId!!, senderKey!!)
@ -782,8 +782,8 @@ internal class MXOlmDevice(
if (null != session) { if (null != session) {
// Check that the room id matches the original one for the session. This stops // Check that the room id matches the original one for the session. This stops
// the HS pretending a message was targeting a different room. // the HS pretending a message was targeting a different room.
if (!TextUtils.equals(roomId, session.mRoomId)) { if (!TextUtils.equals(roomId, session.roomId)) {
val errorDescription = String.format(MXCryptoError.INBOUND_SESSION_MISMATCH_ROOM_ID_REASON, roomId, session.mRoomId) val errorDescription = String.format(MXCryptoError.INBOUND_SESSION_MISMATCH_ROOM_ID_REASON, roomId, session.roomId)
Timber.e("## getInboundGroupSession() : $errorDescription") Timber.e("## getInboundGroupSession() : $errorDescription")
inboundGroupSessionWithIdError = MXCryptoError(MXCryptoError.INBOUND_SESSION_MISMATCH_ROOM_ID_ERROR_CODE, inboundGroupSessionWithIdError = MXCryptoError(MXCryptoError.INBOUND_SESSION_MISMATCH_ROOM_ID_ERROR_CODE,
MXCryptoError.UNABLE_TO_DECRYPT, errorDescription) MXCryptoError.UNABLE_TO_DECRYPT, errorDescription)

View File

@ -19,8 +19,8 @@ package im.vector.matrix.android.internal.crypto
import im.vector.matrix.android.api.auth.data.Credentials import im.vector.matrix.android.api.auth.data.Credentials
import java.util.* import java.util.*
internal class ObjectSigner(private val mCredentials: Credentials, internal class ObjectSigner(private val credentials: Credentials,
private val mOlmDevice: MXOlmDevice) { private val olmDevice: MXOlmDevice) {
/** /**
* Sign Object * Sign Object
@ -42,9 +42,9 @@ internal class ObjectSigner(private val mCredentials: Credentials,
val content = HashMap<String, String>() val content = HashMap<String, String>()
content["ed25519:" + mCredentials.deviceId] = mOlmDevice.signMessage(strToSign)!! content["ed25519:" + credentials.deviceId] = olmDevice.signMessage(strToSign)!!
result[mCredentials.userId] = content result[credentials.userId] = content
return result return result
} }

View File

@ -18,16 +18,12 @@ package im.vector.matrix.android.internal.crypto.actions
import android.text.TextUtils import android.text.TextUtils
import arrow.core.Try import arrow.core.Try
import im.vector.matrix.android.api.MatrixCallback
import im.vector.matrix.android.internal.crypto.MXOlmDevice import im.vector.matrix.android.internal.crypto.MXOlmDevice
import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo
import im.vector.matrix.android.internal.crypto.model.MXKey import im.vector.matrix.android.internal.crypto.model.MXKey
import im.vector.matrix.android.internal.crypto.model.MXOlmSessionResult import im.vector.matrix.android.internal.crypto.model.MXOlmSessionResult
import im.vector.matrix.android.internal.crypto.model.MXUsersDevicesMap import im.vector.matrix.android.internal.crypto.model.MXUsersDevicesMap
import im.vector.matrix.android.internal.crypto.tasks.ClaimOneTimeKeysForUsersDeviceTask import im.vector.matrix.android.internal.crypto.tasks.ClaimOneTimeKeysForUsersDeviceTask
import im.vector.matrix.android.internal.task.TaskExecutor
import im.vector.matrix.android.internal.task.configureWith
import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers
import timber.log.Timber import timber.log.Timber
import java.util.* import java.util.*
@ -94,7 +90,7 @@ internal class EnsureOlmSessionsForDevicesAction(private val olmDevice: MXOlmDev
if (null != deviceIds) { if (null != deviceIds) {
for (deviceId in deviceIds) { for (deviceId in deviceIds) {
val olmSessionResult = results.getObject(deviceId, userId) val olmSessionResult = results.getObject(deviceId, userId)
if (olmSessionResult!!.mSessionId != null) { if (olmSessionResult!!.sessionId != null) {
// We already have a result for this device // We already have a result for this device
continue continue
} }
@ -108,7 +104,7 @@ internal class EnsureOlmSessionsForDevicesAction(private val olmDevice: MXOlmDev
continue continue
} }
// Update the result for this device in results // Update the result for this device in results
olmSessionResult.mSessionId = verifyKeyAndStartSession(oneTimeKey, userId, deviceInfo) olmSessionResult.sessionId = verifyKeyAndStartSession(oneTimeKey, userId, deviceInfo)
} }
} }
} }

View File

@ -28,10 +28,10 @@ import im.vector.matrix.android.internal.crypto.model.rest.RoomKeyRequestBody
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import timber.log.Timber import timber.log.Timber
internal class MegolmSessionDataImporter(private val mOlmDevice: MXOlmDevice, internal class MegolmSessionDataImporter(private val olmDevice: MXOlmDevice,
private val roomDecryptorProvider: RoomDecryptorProvider, private val roomDecryptorProvider: RoomDecryptorProvider,
private val mOutgoingRoomKeyRequestManager: OutgoingRoomKeyRequestManager, private val outgoingRoomKeyRequestManager: OutgoingRoomKeyRequestManager,
private val mCryptoStore: IMXCryptoStore) { private val cryptoStore: IMXCryptoStore) {
/** /**
* Import a list of megolm session keys. * Import a list of megolm session keys.
@ -57,7 +57,7 @@ internal class MegolmSessionDataImporter(private val mOlmDevice: MXOlmDevice,
progressListener.onProgress(0, 100) progressListener.onProgress(0, 100)
} }
} }
val sessions = mOlmDevice.importInboundGroupSessions(megolmSessionsData) val olmInboundGroupSessionWrappers = olmDevice.importInboundGroupSessions(megolmSessionsData)
for (megolmSessionData in megolmSessionsData) { for (megolmSessionData in megolmSessionsData) {
cpt++ cpt++
@ -80,7 +80,7 @@ internal class MegolmSessionDataImporter(private val mOlmDevice: MXOlmDevice,
roomKeyRequestBody.senderKey = megolmSessionData.senderKey roomKeyRequestBody.senderKey = megolmSessionData.senderKey
roomKeyRequestBody.sessionId = megolmSessionData.sessionId roomKeyRequestBody.sessionId = megolmSessionData.sessionId
mOutgoingRoomKeyRequestManager.cancelRoomKeyRequest(roomKeyRequestBody) outgoingRoomKeyRequestManager.cancelRoomKeyRequest(roomKeyRequestBody)
// Have another go at decrypting events sent with this session // Have another go at decrypting events sent with this session
decrypting.onNewSession(megolmSessionData.senderKey!!, sessionId!!) decrypting.onNewSession(megolmSessionData.senderKey!!, sessionId!!)
@ -104,7 +104,7 @@ internal class MegolmSessionDataImporter(private val mOlmDevice: MXOlmDevice,
// Do not back up the key if it comes from a backup recovery // Do not back up the key if it comes from a backup recovery
if (fromBackup) { if (fromBackup) {
mCryptoStore.markBackupDoneForInboundGroupSessions(sessions) cryptoStore.markBackupDoneForInboundGroupSessions(olmInboundGroupSessionWrappers)
} }
val t1 = System.currentTimeMillis() val t1 = System.currentTimeMillis()

View File

@ -27,8 +27,8 @@ import im.vector.matrix.android.internal.util.convertToUTF8
import timber.log.Timber import timber.log.Timber
import java.util.* import java.util.*
internal class MessageEncrypter(private val mCredentials: Credentials, internal class MessageEncrypter(private val credentials: Credentials,
private val mOlmDevice: MXOlmDevice) { private val olmDevice: MXOlmDevice) {
/** /**
* Encrypt an event payload for a list of devices. * Encrypt an event payload for a list of devices.
@ -49,8 +49,8 @@ internal class MessageEncrypter(private val mCredentials: Credentials,
val payloadJson = HashMap(payloadFields) val payloadJson = HashMap(payloadFields)
payloadJson["sender"] = mCredentials.userId payloadJson["sender"] = credentials.userId
payloadJson["sender_device"] = mCredentials.deviceId payloadJson["sender_device"] = credentials.deviceId
// Include the Ed25519 key so that the recipient knows what // Include the Ed25519 key so that the recipient knows what
// device this message came from. // device this message came from.
@ -61,13 +61,13 @@ internal class MessageEncrypter(private val mCredentials: Credentials,
// the curve25519 key and the ed25519 key are owned by // the curve25519 key and the ed25519 key are owned by
// the same device. // the same device.
val keysMap = HashMap<String, String>() val keysMap = HashMap<String, String>()
keysMap["ed25519"] = mOlmDevice.deviceEd25519Key!! keysMap["ed25519"] = olmDevice.deviceEd25519Key!!
payloadJson["keys"] = keysMap payloadJson["keys"] = keysMap
val ciphertext = HashMap<String, Any>() val ciphertext = HashMap<String, Any>()
for (deviceKey in participantKeys) { for (deviceKey in participantKeys) {
val sessionId = mOlmDevice.getSessionId(deviceKey) val sessionId = olmDevice.getSessionId(deviceKey)
if (!TextUtils.isEmpty(sessionId)) { if (!TextUtils.isEmpty(sessionId)) {
Timber.v("Using sessionid $sessionId for device $deviceKey") Timber.v("Using sessionid $sessionId for device $deviceKey")
@ -83,14 +83,14 @@ internal class MessageEncrypter(private val mCredentials: Credentials,
//JsonUtility.canonicalize(JsonUtility.getGson(false).toJsonTree(payloadJson)).toString() //JsonUtility.canonicalize(JsonUtility.getGson(false).toJsonTree(payloadJson)).toString()
val payloadString = convertToUTF8(MoshiProvider.getCanonicalJson(Map::class.java, payloadJson)) val payloadString = convertToUTF8(MoshiProvider.getCanonicalJson(Map::class.java, payloadJson))
ciphertext[deviceKey] = mOlmDevice.encryptMessage(deviceKey, sessionId!!, payloadString!!)!! ciphertext[deviceKey] = olmDevice.encryptMessage(deviceKey, sessionId!!, payloadString!!)!!
} }
} }
val res = EncryptedMessage() val res = EncryptedMessage()
res.algorithm = MXCRYPTO_ALGORITHM_OLM res.algorithm = MXCRYPTO_ALGORITHM_OLM
res.senderKey = mOlmDevice.deviceCurve25519Key res.senderKey = olmDevice.deviceCurve25519Key
res.cipherText = ciphertext res.cipherText = ciphertext
return res return res

View File

@ -21,12 +21,12 @@ import im.vector.matrix.android.internal.crypto.keysbackup.KeysBackup
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import timber.log.Timber import timber.log.Timber
internal class SetDeviceVerificationAction(private val mCryptoStore: IMXCryptoStore, internal class SetDeviceVerificationAction(private val cryptoStore: IMXCryptoStore,
private val mCredentials: Credentials, private val credentials: Credentials,
private val mKeysBackup: KeysBackup) { private val keysBackup: KeysBackup) {
fun handle(verificationStatus: Int, deviceId: String, userId: String) { fun handle(verificationStatus: Int, deviceId: String, userId: String) {
val device = mCryptoStore.getUserDevice(deviceId, userId) val device = cryptoStore.getUserDevice(deviceId, userId)
// Sanity check // Sanity check
if (null == device) { if (null == device) {
@ -36,13 +36,13 @@ internal class SetDeviceVerificationAction(private val mCryptoStore: IMXCryptoSt
if (device.verified != verificationStatus) { if (device.verified != verificationStatus) {
device.verified = verificationStatus device.verified = verificationStatus
mCryptoStore.storeUserDevice(userId, device) cryptoStore.storeUserDevice(userId, device)
if (userId == mCredentials.userId) { if (userId == credentials.userId) {
// If one of the user's own devices is being marked as verified / unverified, // If one of the user's own devices is being marked as verified / unverified,
// check the key backup status, since whether or not we use this depends on // check the key backup status, since whether or not we use this depends on
// whether it has a signature from a verified device // whether it has a signature from a verified device
mKeysBackup.checkAndStartKeysBackup() keysBackup.checkAndStartKeysBackup()
} }
} }
} }

View File

@ -327,7 +327,7 @@ internal class MXMegolmDecryption(private val credentials: Credentials,
.flatMap { .flatMap {
val body = request.requestBody val body = request.requestBody
val olmSessionResult = it.getObject(deviceId, userId) val olmSessionResult = it.getObject(deviceId, userId)
if (olmSessionResult?.mSessionId == null) { if (olmSessionResult?.sessionId == null) {
// no session with this device, probably because there // no session with this device, probably because there
// were no one-time keys. // were no one-time keys.
Try.just(Unit) Try.just(Unit)

View File

@ -26,26 +26,26 @@ import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.tasks.SendToDeviceTask import im.vector.matrix.android.internal.crypto.tasks.SendToDeviceTask
import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers
internal class MXMegolmDecryptionFactory(private val mCredentials: Credentials, internal class MXMegolmDecryptionFactory(private val credentials: Credentials,
private val mOlmDevice: MXOlmDevice, private val olmDevice: MXOlmDevice,
private val mDeviceListManager: DeviceListManager, private val deviceListManager: DeviceListManager,
private val mOutgoingRoomKeyRequestManager: OutgoingRoomKeyRequestManager, private val outgoingRoomKeyRequestManager: OutgoingRoomKeyRequestManager,
private val mMessageEncrypter: MessageEncrypter, private val messageEncrypter: MessageEncrypter,
private val mEnsureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction, private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction,
private val mCryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
private val mSendToDeviceTask: SendToDeviceTask, private val sendToDeviceTask: SendToDeviceTask,
private val coroutineDispatchers: MatrixCoroutineDispatchers) { private val coroutineDispatchers: MatrixCoroutineDispatchers) {
fun create(): MXMegolmDecryption { fun create(): MXMegolmDecryption {
return MXMegolmDecryption( return MXMegolmDecryption(
mCredentials, credentials,
mOlmDevice, olmDevice,
mDeviceListManager, deviceListManager,
mOutgoingRoomKeyRequestManager, outgoingRoomKeyRequestManager,
mMessageEncrypter, messageEncrypter,
mEnsureOlmSessionsForDevicesAction, ensureOlmSessionsForDevicesAction,
mCryptoStore, cryptoStore,
mSendToDeviceTask, sendToDeviceTask,
coroutineDispatchers) coroutineDispatchers)
} }
} }

View File

@ -202,7 +202,7 @@ internal class MXMegolmEncryption(
val devicesToShareWith = devicesByUser[userId] val devicesToShareWith = devicesByUser[userId]
for ((deviceID) in devicesToShareWith!!) { for ((deviceID) in devicesToShareWith!!) {
val sessionResult = it.getObject(deviceID, userId) val sessionResult = it.getObject(deviceID, userId)
if (sessionResult?.mSessionId == null) { if (sessionResult?.sessionId == null) {
// no session with this device, probably because there // no session with this device, probably because there
// were no one-time keys. // were no one-time keys.
// //
@ -218,7 +218,7 @@ internal class MXMegolmEncryption(
} }
Timber.v("## shareUserDevicesKey() : Sharing keys with device $userId:$deviceID") Timber.v("## shareUserDevicesKey() : Sharing keys with device $userId:$deviceID")
//noinspection ArraysAsListWithZeroOrOneArgument,ArraysAsListWithZeroOrOneArgument //noinspection ArraysAsListWithZeroOrOneArgument,ArraysAsListWithZeroOrOneArgument
contentMap.setObject(messageEncrypter.encryptMessage(payload, Arrays.asList(sessionResult.mDevice)), userId, deviceID) contentMap.setObject(messageEncrypter.encryptMessage(payload, Arrays.asList(sessionResult.deviceInfo)), userId, deviceID)
haveTargets = true haveTargets = true
} }
} }

View File

@ -29,28 +29,28 @@ import im.vector.matrix.android.internal.task.TaskExecutor
internal class MXMegolmEncryptionFactory( internal class MXMegolmEncryptionFactory(
private val olmDevice: MXOlmDevice, private val olmDevice: MXOlmDevice,
private val mKeysBackup: KeysBackup, private val keysBackup: KeysBackup,
private val mCryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
private val mDeviceListManager: DeviceListManager, private val deviceListManager: DeviceListManager,
private val mEnsureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction, private val ensureOlmSessionsForDevicesAction: EnsureOlmSessionsForDevicesAction,
private val credentials: Credentials,
private val mCredentials: Credentials, private val sendToDeviceTask: SendToDeviceTask,
private val mSendToDeviceTask: SendToDeviceTask, // FIXME Why taskExecutor is not used?
private val mTaskExecutor: TaskExecutor, private val taskExecutor: TaskExecutor,
private val mMessageEncrypter: MessageEncrypter, private val messageEncrypter: MessageEncrypter,
private val mWarnOnUnknownDevicesRepository: WarnOnUnknownDeviceRepository) { private val warnOnUnknownDevicesRepository: WarnOnUnknownDeviceRepository) {
fun create(roomId: String): MXMegolmEncryption { fun create(roomId: String): MXMegolmEncryption {
return MXMegolmEncryption( return MXMegolmEncryption(
roomId, roomId,
olmDevice, olmDevice,
mKeysBackup, keysBackup,
mCryptoStore, cryptoStore,
mDeviceListManager, deviceListManager,
mEnsureOlmSessionsForDevicesAction, ensureOlmSessionsForDevicesAction,
mCredentials, credentials,
mSendToDeviceTask, sendToDeviceTask,
mMessageEncrypter, messageEncrypter,
mWarnOnUnknownDevicesRepository) warnOnUnknownDevicesRepository)
} }
} }

View File

@ -37,10 +37,9 @@ import java.util.*
internal class MXOlmDecryption( internal class MXOlmDecryption(
// The olm device interface // The olm device interface
private val mOlmDevice: MXOlmDevice, private val olmDevice: MXOlmDevice,
// the matrix credentials // the matrix credentials
private val mCredentials: Credentials) private val credentials: Credentials)
: IMXDecrypting { : IMXDecrypting {
@Throws(MXDecryptionException::class) @Throws(MXDecryptionException::class)
@ -53,15 +52,15 @@ internal class MXOlmDecryption(
MXCryptoError.UNABLE_TO_DECRYPT, MXCryptoError.MISSING_CIPHER_TEXT_REASON)) MXCryptoError.UNABLE_TO_DECRYPT, MXCryptoError.MISSING_CIPHER_TEXT_REASON))
} }
if (!olmEventContent.ciphertext!!.containsKey(mOlmDevice.deviceCurve25519Key)) { if (!olmEventContent.ciphertext!!.containsKey(olmDevice.deviceCurve25519Key)) {
Timber.e("## decryptEvent() : our device " + mOlmDevice.deviceCurve25519Key Timber.e("## decryptEvent() : our device " + olmDevice.deviceCurve25519Key
+ " is not included in recipients. Event") + " is not included in recipients. Event")
throw MXDecryptionException(MXCryptoError(MXCryptoError.NOT_INCLUDE_IN_RECIPIENTS_ERROR_CODE, throw MXDecryptionException(MXCryptoError(MXCryptoError.NOT_INCLUDE_IN_RECIPIENTS_ERROR_CODE,
MXCryptoError.UNABLE_TO_DECRYPT, MXCryptoError.NOT_INCLUDED_IN_RECIPIENT_REASON)) MXCryptoError.UNABLE_TO_DECRYPT, MXCryptoError.NOT_INCLUDED_IN_RECIPIENT_REASON))
} }
// The message for myUser // The message for myUser
val message = olmEventContent.ciphertext!![mOlmDevice.deviceCurve25519Key] as JsonDict val message = olmEventContent.ciphertext!![olmDevice.deviceCurve25519Key] as JsonDict
val decryptedPayload = decryptMessage(message, olmEventContent.senderKey!!) val decryptedPayload = decryptMessage(message, olmEventContent.senderKey!!)
if (decryptedPayload == null) { if (decryptedPayload == null) {
@ -93,9 +92,9 @@ internal class MXOlmDecryption(
MXCryptoError.UNABLE_TO_DECRYPT, reason)) MXCryptoError.UNABLE_TO_DECRYPT, reason))
} }
if (!TextUtils.equals(olmPayloadContent.recipient, mCredentials.userId)) { if (!TextUtils.equals(olmPayloadContent.recipient, credentials.userId)) {
Timber.e("## decryptEvent() : Event " + event.eventId + ": Intended recipient " + olmPayloadContent.recipient Timber.e("## decryptEvent() : Event " + event.eventId + ": Intended recipient " + olmPayloadContent.recipient
+ " does not match our id " + mCredentials.userId) + " does not match our id " + credentials.userId)
throw MXDecryptionException(MXCryptoError(MXCryptoError.BAD_RECIPIENT_ERROR_CODE, throw MXDecryptionException(MXCryptoError(MXCryptoError.BAD_RECIPIENT_ERROR_CODE,
MXCryptoError.UNABLE_TO_DECRYPT, String.format(MXCryptoError.BAD_RECIPIENT_REASON, olmPayloadContent.recipient))) MXCryptoError.UNABLE_TO_DECRYPT, String.format(MXCryptoError.BAD_RECIPIENT_REASON, olmPayloadContent.recipient)))
} }
@ -109,7 +108,7 @@ internal class MXOlmDecryption(
val ed25519 = olmPayloadContent.recipient_keys!!.get("ed25519") val ed25519 = olmPayloadContent.recipient_keys!!.get("ed25519")
if (!TextUtils.equals(ed25519, mOlmDevice.deviceEd25519Key)) { if (!TextUtils.equals(ed25519, olmDevice.deviceEd25519Key)) {
Timber.e("## decryptEvent() : Event " + event.eventId + ": Intended recipient ed25519 key " + ed25519 + " did not match ours") Timber.e("## decryptEvent() : Event " + event.eventId + ": Intended recipient ed25519 key " + ed25519 + " did not match ours")
throw MXDecryptionException(MXCryptoError(MXCryptoError.BAD_RECIPIENT_KEY_ERROR_CODE, throw MXDecryptionException(MXCryptoError(MXCryptoError.BAD_RECIPIENT_KEY_ERROR_CODE,
MXCryptoError.UNABLE_TO_DECRYPT, MXCryptoError.BAD_RECIPIENT_KEY_REASON)) MXCryptoError.UNABLE_TO_DECRYPT, MXCryptoError.BAD_RECIPIENT_KEY_REASON))
@ -158,7 +157,7 @@ internal class MXOlmDecryption(
* @return payload, if decrypted successfully. * @return payload, if decrypted successfully.
*/ */
private fun decryptMessage(message: JsonDict, theirDeviceIdentityKey: String): String? { private fun decryptMessage(message: JsonDict, theirDeviceIdentityKey: String): String? {
val sessionIdsSet = mOlmDevice.getSessionIds(theirDeviceIdentityKey) val sessionIdsSet = olmDevice.getSessionIds(theirDeviceIdentityKey)
val sessionIds: List<String> val sessionIds: List<String>
@ -190,13 +189,13 @@ internal class MXOlmDecryption(
// Try each session in turn // Try each session in turn
// decryptionErrors = {}; // decryptionErrors = {};
for (sessionId in sessionIds) { for (sessionId in sessionIds) {
val payload = mOlmDevice.decryptMessage(messageBody, messageType, sessionId, theirDeviceIdentityKey) val payload = olmDevice.decryptMessage(messageBody, messageType, sessionId, theirDeviceIdentityKey)
if (null != payload) { if (null != payload) {
Timber.v("## decryptMessage() : Decrypted Olm message from $theirDeviceIdentityKey with session $sessionId") Timber.v("## decryptMessage() : Decrypted Olm message from $theirDeviceIdentityKey with session $sessionId")
return payload return payload
} else { } else {
val foundSession = mOlmDevice.matchesSession(theirDeviceIdentityKey, sessionId, messageType, messageBody) val foundSession = olmDevice.matchesSession(theirDeviceIdentityKey, sessionId, messageType, messageBody)
if (foundSession) { if (foundSession) {
// Decryption failed, but it was a prekey message matching this // Decryption failed, but it was a prekey message matching this
@ -222,7 +221,7 @@ internal class MXOlmDecryption(
// prekey message which doesn't match any existing sessions: make a new // prekey message which doesn't match any existing sessions: make a new
// session. // session.
val res = mOlmDevice.createInboundSession(theirDeviceIdentityKey, messageType, messageBody) val res = olmDevice.createInboundSession(theirDeviceIdentityKey, messageType, messageBody)
if (null == res) { if (null == res) {
Timber.e("## decryptMessage() : Error decrypting non-prekey message with existing sessions") Timber.e("## decryptMessage() : Error decrypting non-prekey message with existing sessions")

View File

@ -19,12 +19,12 @@ package im.vector.matrix.android.internal.crypto.algorithms.olm
import im.vector.matrix.android.api.auth.data.Credentials import im.vector.matrix.android.api.auth.data.Credentials
import im.vector.matrix.android.internal.crypto.MXOlmDevice import im.vector.matrix.android.internal.crypto.MXOlmDevice
internal class MXOlmDecryptionFactory(private val mOlmDevice: MXOlmDevice, internal class MXOlmDecryptionFactory(private val olmDevice: MXOlmDevice,
private val mCredentials: Credentials) { private val credentials: Credentials) {
fun create(): MXOlmDecryption { fun create(): MXOlmDecryption {
return MXOlmDecryption( return MXOlmDecryption(
mOlmDevice, olmDevice,
mCredentials) credentials)
} }
} }

View File

@ -23,20 +23,20 @@ import im.vector.matrix.android.internal.crypto.actions.MessageEncrypter
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers
internal class MXOlmEncryptionFactory(private val mOlmDevice: MXOlmDevice, internal class MXOlmEncryptionFactory(private val olmDevice: MXOlmDevice,
private val mCryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
private val mMessageEncrypter: MessageEncrypter, private val messageEncrypter: MessageEncrypter,
private val mDeviceListManager: DeviceListManager, private val deviceListManager: DeviceListManager,
private val coroutineDispatchers: MatrixCoroutineDispatchers, private val coroutineDispatchers: MatrixCoroutineDispatchers,
private val mEnsureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction) { private val ensureOlmSessionsForUsersAction: EnsureOlmSessionsForUsersAction) {
fun create(roomId: String): MXOlmEncryption { fun create(roomId: String): MXOlmEncryption {
return MXOlmEncryption( return MXOlmEncryption(
roomId, roomId,
mOlmDevice, olmDevice,
mCryptoStore, cryptoStore,
mMessageEncrypter, messageEncrypter,
mDeviceListManager, deviceListManager,
mEnsureOlmSessionsForUsersAction) ensureOlmSessionsForUsersAction)
} }
} }

View File

@ -42,7 +42,7 @@ import im.vector.matrix.android.internal.crypto.keysbackup.util.computeRecoveryK
import im.vector.matrix.android.internal.crypto.keysbackup.util.extractCurveKeyFromRecoveryKey import im.vector.matrix.android.internal.crypto.keysbackup.util.extractCurveKeyFromRecoveryKey
import im.vector.matrix.android.internal.crypto.model.ImportRoomKeysResult import im.vector.matrix.android.internal.crypto.model.ImportRoomKeysResult
import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo
import im.vector.matrix.android.internal.crypto.model.MXOlmInboundGroupSession2 import im.vector.matrix.android.internal.crypto.model.OlmInboundGroupSessionWrapper
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.store.db.model.KeysBackupDataEntity import im.vector.matrix.android.internal.crypto.store.db.model.KeysBackupDataEntity
import im.vector.matrix.android.internal.di.MoshiProvider import im.vector.matrix.android.internal.di.MoshiProvider
@ -94,17 +94,17 @@ internal class KeysBackup(
private val keysBackupStateManager = KeysBackupStateManager(uiHandler) private val keysBackupStateManager = KeysBackupStateManager(uiHandler)
// The backup version // The backup version
override var mKeysBackupVersion: KeysVersionResult? = null override var keysBackupVersion: KeysVersionResult? = null
private set private set
// The backup key being used. // The backup key being used.
private var mBackupKey: OlmPkEncryption? = null private var backupOlmPkEncryption: OlmPkEncryption? = null
private val mRandom = Random() private val random = Random()
private var backupAllGroupSessionsCallback: MatrixCallback<Unit>? = null private var backupAllGroupSessionsCallback: MatrixCallback<Unit>? = null
private var mKeysBackupStateListener: KeysBackupService.KeysBackupStateListener? = null private var keysBackupStateListener: KeysBackupService.KeysBackupStateListener? = null
override val isEnabled: Boolean override val isEnabled: Boolean
get() = keysBackupStateManager.isEnabled get() = keysBackupStateManager.isEnabled
@ -116,7 +116,7 @@ internal class KeysBackup(
get() = keysBackupStateManager.state get() = keysBackupStateManager.state
override val currentBackupVersion: String? override val currentBackupVersion: String?
get() = mKeysBackupVersion?.version get() = keysBackupVersion?.version
override fun addListener(listener: KeysBackupService.KeysBackupStateListener) { override fun addListener(listener: KeysBackupService.KeysBackupStateListener) {
keysBackupStateManager.addListener(listener) keysBackupStateManager.addListener(listener)
@ -248,9 +248,9 @@ internal class KeysBackup(
CryptoAsyncHelper.getDecryptBackgroundHandler().post { CryptoAsyncHelper.getDecryptBackgroundHandler().post {
// If we're currently backing up to this backup... stop. // If we're currently backing up to this backup... stop.
// (We start using it automatically in createKeysBackupVersion so this is symmetrical). // (We start using it automatically in createKeysBackupVersion so this is symmetrical).
if (mKeysBackupVersion != null && version == mKeysBackupVersion!!.version) { if (keysBackupVersion != null && version == keysBackupVersion!!.version) {
resetKeysBackupData() resetKeysBackupData()
mKeysBackupVersion = null keysBackupVersion = null
keysBackupStateManager.state = KeysBackupState.Unknown keysBackupStateManager.state = KeysBackupState.Unknown
} }
@ -350,7 +350,7 @@ internal class KeysBackup(
backupAllGroupSessionsCallback = callback backupAllGroupSessionsCallback = callback
// Listen to `state` change to determine when to call onBackupProgress and onComplete // Listen to `state` change to determine when to call onBackupProgress and onComplete
mKeysBackupStateListener = object : KeysBackupService.KeysBackupStateListener { keysBackupStateListener = object : KeysBackupService.KeysBackupStateListener {
override fun onStateChange(newState: KeysBackupState) { override fun onStateChange(newState: KeysBackupState) {
getBackupProgress(object : ProgressListener { getBackupProgress(object : ProgressListener {
override fun onProgress(progress: Int, total: Int) { override fun onProgress(progress: Int, total: Int) {
@ -370,7 +370,7 @@ internal class KeysBackup(
} }
} }
keysBackupStateManager.addListener(mKeysBackupStateListener!!) keysBackupStateManager.addListener(keysBackupStateListener!!)
backupKeys() backupKeys()
} }
@ -651,11 +651,11 @@ internal class KeysBackup(
private fun resetBackupAllGroupSessionsListeners() { private fun resetBackupAllGroupSessionsListeners() {
backupAllGroupSessionsCallback = null backupAllGroupSessionsCallback = null
mKeysBackupStateListener?.let { keysBackupStateListener?.let {
keysBackupStateManager.removeListener(it) keysBackupStateManager.removeListener(it)
} }
mKeysBackupStateListener = null keysBackupStateListener = null
} }
/** /**
@ -732,9 +732,9 @@ internal class KeysBackup(
+ sessionsFromHsCount + " from the backup store on the homeserver") + sessionsFromHsCount + " from the backup store on the homeserver")
// Do not trigger a backup for them if they come from the backup version we are using // Do not trigger a backup for them if they come from the backup version we are using
val backUp = keysVersionResult.version != mKeysBackupVersion?.version val backUp = keysVersionResult.version != keysBackupVersion?.version
if (backUp) { if (backUp) {
Timber.v("restoreKeysWithRecoveryKey: Those keys will be backed up to backup version: " + mKeysBackupVersion?.version) Timber.v("restoreKeysWithRecoveryKey: Those keys will be backed up to backup version: " + keysBackupVersion?.version)
} }
// Import them into the crypto store // Import them into the crypto store
@ -913,7 +913,7 @@ internal class KeysBackup(
// Wait between 0 and 10 seconds, to avoid backup requests from // Wait between 0 and 10 seconds, to avoid backup requests from
// different clients hitting the server all at the same time when a // different clients hitting the server all at the same time when a
// new key is sent // new key is sent
val delayInMs = mRandom.nextInt(KEY_BACKUP_WAITING_TIME_TO_SEND_KEY_BACKUP_MILLIS).toLong() val delayInMs = random.nextInt(KEY_BACKUP_WAITING_TIME_TO_SEND_KEY_BACKUP_MILLIS).toLong()
uiHandler.postDelayed({ backupKeys() }, delayInMs) uiHandler.postDelayed({ backupKeys() }, delayInMs)
} }
@ -926,7 +926,7 @@ internal class KeysBackup(
/** /**
* Get information about a backup version defined on the homeserver. * Get information about a backup version defined on the homeserver.
* *
* It can be different than mKeysBackupVersion. * It can be different than keysBackupVersion.
* @param version the backup version * @param version the backup version
* @param callback * @param callback
*/ */
@ -956,7 +956,7 @@ internal class KeysBackup(
/** /**
* Retrieve the current version of the backup from the home server * Retrieve the current version of the backup from the home server
* *
* It can be different than mKeysBackupVersion. * It can be different than keysBackupVersion.
* @param callback onSuccess(null) will be called if there is no backup on the server * @param callback onSuccess(null) will be called if there is no backup on the server
*/ */
override fun getCurrentVersion(callback: MatrixCallback<KeysVersionResult?>) { override fun getCurrentVersion(callback: MatrixCallback<KeysVersionResult?>) {
@ -990,7 +990,7 @@ internal class KeysBackup(
override fun forceUsingLastVersion(callback: MatrixCallback<Boolean>) { override fun forceUsingLastVersion(callback: MatrixCallback<Boolean>) {
getCurrentVersion(object : MatrixCallback<KeysVersionResult?> { getCurrentVersion(object : MatrixCallback<KeysVersionResult?> {
override fun onSuccess(data: KeysVersionResult?) { override fun onSuccess(data: KeysVersionResult?) {
val localBackupVersion = mKeysBackupVersion?.version val localBackupVersion = keysBackupVersion?.version
val serverBackupVersion = data?.version val serverBackupVersion = data?.version
if (serverBackupVersion == null) { if (serverBackupVersion == null) {
@ -1001,7 +1001,7 @@ internal class KeysBackup(
// No backup on the server, and we are currently backing up, so stop backing up // No backup on the server, and we are currently backing up, so stop backing up
callback.onSuccess(false) callback.onSuccess(false)
resetKeysBackupData() resetKeysBackupData()
mKeysBackupVersion = null keysBackupVersion = null
keysBackupStateManager.state = KeysBackupState.Disabled keysBackupStateManager.state = KeysBackupState.Disabled
} }
} else { } else {
@ -1046,7 +1046,7 @@ internal class KeysBackup(
return return
} }
mKeysBackupVersion = null keysBackupVersion = null
keysBackupStateManager.state = KeysBackupState.CheckingBackUpOnHomeserver keysBackupStateManager.state = KeysBackupState.CheckingBackUpOnHomeserver
getCurrentVersion(object : MatrixCallback<KeysVersionResult?> { getCurrentVersion(object : MatrixCallback<KeysVersionResult?> {
@ -1064,7 +1064,7 @@ internal class KeysBackup(
private fun checkAndStartWithKeysBackupVersion(keyBackupVersion: KeysVersionResult?) { private fun checkAndStartWithKeysBackupVersion(keyBackupVersion: KeysVersionResult?) {
Timber.v("checkAndStartWithKeyBackupVersion: ${keyBackupVersion?.version}") Timber.v("checkAndStartWithKeyBackupVersion: ${keyBackupVersion?.version}")
mKeysBackupVersion = keyBackupVersion keysBackupVersion = keyBackupVersion
if (keyBackupVersion == null) { if (keyBackupVersion == null) {
Timber.v("checkAndStartWithKeysBackupVersion: Found no key backup version on the homeserver") Timber.v("checkAndStartWithKeysBackupVersion: Found no key backup version on the homeserver")
@ -1212,13 +1212,13 @@ internal class KeysBackup(
val retrievedMegolmBackupAuthData = keysVersionResult.getAuthDataAsMegolmBackupAuthData() val retrievedMegolmBackupAuthData = keysVersionResult.getAuthDataAsMegolmBackupAuthData()
if (retrievedMegolmBackupAuthData != null) { if (retrievedMegolmBackupAuthData != null) {
mKeysBackupVersion = keysVersionResult keysBackupVersion = keysVersionResult
cryptoStore.setKeyBackupVersion(keysVersionResult.version) cryptoStore.setKeyBackupVersion(keysVersionResult.version)
onServerDataRetrieved(keysVersionResult.count, keysVersionResult.hash) onServerDataRetrieved(keysVersionResult.count, keysVersionResult.hash)
try { try {
mBackupKey = OlmPkEncryption().apply { backupOlmPkEncryption = OlmPkEncryption().apply {
setRecipientKey(retrievedMegolmBackupAuthData.publicKey) setRecipientKey(retrievedMegolmBackupAuthData.publicKey)
} }
} catch (e: OlmException) { } catch (e: OlmException) {
@ -1262,7 +1262,7 @@ internal class KeysBackup(
cryptoStore.setKeyBackupVersion(null) cryptoStore.setKeyBackupVersion(null)
cryptoStore.setKeysBackupData(null) cryptoStore.setKeysBackupData(null)
mBackupKey = null backupOlmPkEncryption = null
// Reset backup markers // Reset backup markers
cryptoStore.resetBackupMarkers() cryptoStore.resetBackupMarkers()
@ -1276,7 +1276,7 @@ internal class KeysBackup(
Timber.v("backupKeys") Timber.v("backupKeys")
// Sanity check, as this method can be called after a delay, the state may have change during the delay // Sanity check, as this method can be called after a delay, the state may have change during the delay
if (!isEnabled || mBackupKey == null || mKeysBackupVersion == null) { if (!isEnabled || backupOlmPkEncryption == null || keysBackupVersion == null) {
Timber.v("backupKeys: Invalid configuration") Timber.v("backupKeys: Invalid configuration")
backupAllGroupSessionsCallback?.onFailure(IllegalStateException("Invalid configuration")) backupAllGroupSessionsCallback?.onFailure(IllegalStateException("Invalid configuration"))
resetBackupAllGroupSessionsListeners() resetBackupAllGroupSessionsListeners()
@ -1291,11 +1291,11 @@ internal class KeysBackup(
} }
// Get a chunk of keys to backup // Get a chunk of keys to backup
val sessions = cryptoStore.inboundGroupSessionsToBackup(KEY_BACKUP_SEND_KEYS_MAX_COUNT) val olmInboundGroupSessionWrappers = cryptoStore.inboundGroupSessionsToBackup(KEY_BACKUP_SEND_KEYS_MAX_COUNT)
Timber.v("backupKeys: 1 - " + sessions.size + " sessions to back up") Timber.v("backupKeys: 1 - " + olmInboundGroupSessionWrappers.size + " sessions to back up")
if (sessions.isEmpty()) { if (olmInboundGroupSessionWrappers.isEmpty()) {
// Backup is up to date // Backup is up to date
keysBackupStateManager.state = KeysBackupState.ReadyToBackUp keysBackupStateManager.state = KeysBackupState.ReadyToBackUp
@ -1314,16 +1314,16 @@ internal class KeysBackup(
val keysBackupData = KeysBackupData() val keysBackupData = KeysBackupData()
keysBackupData.roomIdToRoomKeysBackupData = HashMap() keysBackupData.roomIdToRoomKeysBackupData = HashMap()
for (session in sessions) { for (olmInboundGroupSessionWrapper in olmInboundGroupSessionWrappers) {
val keyBackupData = encryptGroupSession(session) val keyBackupData = encryptGroupSession(olmInboundGroupSessionWrapper)
if (keysBackupData.roomIdToRoomKeysBackupData[session.mRoomId] == null) { if (keysBackupData.roomIdToRoomKeysBackupData[olmInboundGroupSessionWrapper.roomId] == null) {
val roomKeysBackupData = RoomKeysBackupData() val roomKeysBackupData = RoomKeysBackupData()
roomKeysBackupData.sessionIdToKeyBackupData = HashMap() roomKeysBackupData.sessionIdToKeyBackupData = HashMap()
keysBackupData.roomIdToRoomKeysBackupData[session.mRoomId!!] = roomKeysBackupData keysBackupData.roomIdToRoomKeysBackupData[olmInboundGroupSessionWrapper.roomId!!] = roomKeysBackupData
} }
try { try {
keysBackupData.roomIdToRoomKeysBackupData[session.mRoomId]!!.sessionIdToKeyBackupData[session.mSession!!.sessionIdentifier()] = keyBackupData keysBackupData.roomIdToRoomKeysBackupData[olmInboundGroupSessionWrapper.roomId]!!.sessionIdToKeyBackupData[olmInboundGroupSessionWrapper.olmInboundGroupSession!!.sessionIdentifier()] = keyBackupData
} catch (e: OlmException) { } catch (e: OlmException) {
Timber.e(e, "OlmException") Timber.e(e, "OlmException")
} }
@ -1333,16 +1333,16 @@ internal class KeysBackup(
// Make the request // Make the request
storeSessionDataTask storeSessionDataTask
.configureWith(StoreSessionsDataTask.Params(mKeysBackupVersion!!.version!!, keysBackupData)) .configureWith(StoreSessionsDataTask.Params(keysBackupVersion!!.version!!, keysBackupData))
.dispatchTo(object : MatrixCallback<BackupKeysResult> { .dispatchTo(object : MatrixCallback<BackupKeysResult> {
override fun onSuccess(data: BackupKeysResult) { override fun onSuccess(data: BackupKeysResult) {
uiHandler.post { uiHandler.post {
Timber.v("backupKeys: 5a - Request complete") Timber.v("backupKeys: 5a - Request complete")
// Mark keys as backed up // Mark keys as backed up
cryptoStore.markBackupDoneForInboundGroupSessions(sessions) cryptoStore.markBackupDoneForInboundGroupSessions(olmInboundGroupSessionWrappers)
if (sessions.size < KEY_BACKUP_SEND_KEYS_MAX_COUNT) { if (olmInboundGroupSessionWrappers.size < KEY_BACKUP_SEND_KEYS_MAX_COUNT) {
Timber.v("backupKeys: All keys have been backed up") Timber.v("backupKeys: All keys have been backed up")
onServerDataRetrieved(data.count, data.hash) onServerDataRetrieved(data.count, data.hash)
@ -1370,7 +1370,7 @@ internal class KeysBackup(
backupAllGroupSessionsCallback?.onFailure(failure) backupAllGroupSessionsCallback?.onFailure(failure)
resetBackupAllGroupSessionsListeners() resetBackupAllGroupSessionsListeners()
resetKeysBackupData() resetKeysBackupData()
mKeysBackupVersion = null keysBackupVersion = null
// Do not stay in KeysBackupState.WrongBackUpVersion but check what is available on the homeserver // Do not stay in KeysBackupState.WrongBackUpVersion but check what is available on the homeserver
checkAndStartKeysBackup() checkAndStartKeysBackup()
@ -1399,13 +1399,13 @@ internal class KeysBackup(
@VisibleForTesting @VisibleForTesting
@WorkerThread @WorkerThread
fun encryptGroupSession(session: MXOlmInboundGroupSession2): KeyBackupData { fun encryptGroupSession(olmInboundGroupSessionWrapper: OlmInboundGroupSessionWrapper): KeyBackupData {
// Gather information for each key // Gather information for each key
val device = cryptoStore.deviceWithIdentityKey(session.mSenderKey!!) val device = cryptoStore.deviceWithIdentityKey(olmInboundGroupSessionWrapper.senderKey!!)
// Build the m.megolm_backup.v1.curve25519-aes-sha2 data as defined at // Build the m.megolm_backup.v1.curve25519-aes-sha2 data as defined at
// https://github.com/uhoreg/matrix-doc/blob/e2e_backup/proposals/1219-storing-megolm-keys-serverside.md#mmegolm_backupv1curve25519-aes-sha2-key-format // https://github.com/uhoreg/matrix-doc/blob/e2e_backup/proposals/1219-storing-megolm-keys-serverside.md#mmegolm_backupv1curve25519-aes-sha2-key-format
val sessionData = session.exportKeys() val sessionData = olmInboundGroupSessionWrapper.exportKeys()
val sessionBackupData = mapOf( val sessionBackupData = mapOf(
"algorithm" to sessionData!!.algorithm, "algorithm" to sessionData!!.algorithm,
"sender_key" to sessionData.senderKey, "sender_key" to sessionData.senderKey,
@ -1421,7 +1421,7 @@ internal class KeysBackup(
try { try {
val json = adapter.toJson(sessionBackupData) val json = adapter.toJson(sessionBackupData)
encryptedSessionBackupData = mBackupKey?.encrypt(json) encryptedSessionBackupData = backupOlmPkEncryption?.encrypt(json)
} catch (e: OlmException) { } catch (e: OlmException) {
Timber.e(e, "OlmException") Timber.e(e, "OlmException")
} }
@ -1429,12 +1429,12 @@ internal class KeysBackup(
// Build backup data for that key // Build backup data for that key
val keyBackupData = KeyBackupData() val keyBackupData = KeyBackupData()
try { try {
keyBackupData.firstMessageIndex = session.mSession!!.firstKnownIndex keyBackupData.firstMessageIndex = olmInboundGroupSessionWrapper.olmInboundGroupSession!!.firstKnownIndex
} catch (e: OlmException) { } catch (e: OlmException) {
Timber.e(e, "OlmException") Timber.e(e, "OlmException")
} }
keyBackupData.forwardedCount = session.mForwardingCurve25519KeyChain!!.size keyBackupData.forwardedCount = olmInboundGroupSessionWrapper.forwardingCurve25519KeyChain!!.size
keyBackupData.isVerified = device?.isVerified == true keyBackupData.isVerified = device?.isVerified == true
val data = mapOf( val data = mapOf(

View File

@ -24,19 +24,19 @@ import java.util.*
internal class KeysBackupStateManager(private val uiHandler: Handler) { internal class KeysBackupStateManager(private val uiHandler: Handler) {
private val mListeners = ArrayList<KeysBackupService.KeysBackupStateListener>() private val listeners = ArrayList<KeysBackupService.KeysBackupStateListener>()
// Backup state // Backup state
var state = KeysBackupState.Unknown var state = KeysBackupState.Unknown
set(newState) { set(newState) {
Timber.v("KeysBackup", "setState: $field -> $newState") Timber.v("KeysBackup: setState: $field -> $newState")
field = newState field = newState
// Notify listeners about the state change, on the ui thread // Notify listeners about the state change, on the ui thread
uiHandler.post { uiHandler.post {
synchronized(mListeners) { synchronized(listeners) {
mListeners.forEach { listeners.forEach {
// Use newState because state may have already changed again // Use newState because state may have already changed again
it.onStateChange(newState) it.onStateChange(newState)
} }
@ -57,14 +57,14 @@ internal class KeysBackupStateManager(private val uiHandler: Handler) {
|| state == KeysBackupState.NotTrusted || state == KeysBackupState.NotTrusted
fun addListener(listener: KeysBackupService.KeysBackupStateListener) { fun addListener(listener: KeysBackupService.KeysBackupStateListener) {
synchronized(mListeners) { synchronized(listeners) {
mListeners.add(listener) listeners.add(listener)
} }
} }
fun removeListener(listener: KeysBackupService.KeysBackupStateListener) { fun removeListener(listener: KeysBackupService.KeysBackupStateListener) {
synchronized(mListeners) { synchronized(listeners) {
mListeners.remove(listener) listeners.remove(listener)
} }
} }
} }

View File

@ -22,9 +22,9 @@ data class MXEncryptEventContentResult(
/** /**
* The event content * The event content
*/ */
val mEventContent: Content, val eventContent: Content,
/** /**
* the event type * the event type
*/ */
val mEventType: String val eventType: String
) )

View File

@ -1,57 +0,0 @@
/*
* Copyright 2016 OpenMarket Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.matrix.android.internal.crypto.model;
import org.matrix.olm.OlmInboundGroupSession;
import java.io.Serializable;
import java.util.Map;
import timber.log.Timber;
/**
* This class adds more context to a OLMInboundGroupSession object.
* This allows additional checks. The class implements NSCoding so that the context can be stored.
*/
public class MXOlmInboundGroupSession implements Serializable {
// The associated olm inbound group session.
public OlmInboundGroupSession mSession;
// The room in which this session is used.
public String mRoomId;
// The base64-encoded curve25519 key of the sender.
public String mSenderKey;
// Other keys the sender claims.
public Map<String, String> mKeysClaimed;
/**
* Constructor
*
* @param sessionKey the session key
*/
public MXOlmInboundGroupSession(String sessionKey) {
try {
mSession = new OlmInboundGroupSession(sessionKey);
} catch (Exception e) {
Timber.e(e, "Cannot create");
}
}
}

View File

@ -18,14 +18,13 @@ package im.vector.matrix.android.internal.crypto.model
import java.io.Serializable import java.io.Serializable
data class MXOlmSessionResult data class MXOlmSessionResult(
(
/** /**
* the device * the device
*/ */
val mDevice: MXDeviceInfo, val deviceInfo: MXDeviceInfo,
/** /**
* Base64 olm session id. * Base64 olm session id.
* null if no session could be established. * null if no session could be established.
*/ */
var mSessionId: String?) : Serializable var sessionId: String?) : Serializable

View File

@ -26,34 +26,34 @@ import java.io.Serializable
import java.util.* import java.util.*
/** /**
* This class adds more context to a OLMInboundGroupSession object. * This class adds more context to a OlmInboundGroupSession object.
* This allows additional checks. The class implements Serializable so that the context can be stored. * This allows additional checks. The class implements Serializable so that the context can be stored.
*/ */
class MXOlmInboundGroupSession2 : Serializable { class OlmInboundGroupSessionWrapper : Serializable {
// The associated olm inbound group session. // The associated olm inbound group session.
var mSession: OlmInboundGroupSession? = null var olmInboundGroupSession: OlmInboundGroupSession? = null
// The room in which this session is used. // The room in which this session is used.
var mRoomId: String? = null var roomId: String? = null
// The base64-encoded curve25519 key of the sender. // The base64-encoded curve25519 key of the sender.
var mSenderKey: String? = null var senderKey: String? = null
// Other keys the sender claims. // Other keys the sender claims.
var mKeysClaimed: Map<String, String>? = null var keysClaimed: Map<String, String>? = null
// Devices which forwarded this session to us (normally empty). // Devices which forwarded this session to us (normally empty).
var mForwardingCurve25519KeyChain: List<String>? = ArrayList() var forwardingCurve25519KeyChain: List<String>? = ArrayList()
/** /**
* @return the first known message index * @return the first known message index
*/ */
val firstKnownIndex: Long? val firstKnownIndex: Long?
get() { get() {
if (null != mSession) { if (null != olmInboundGroupSession) {
try { try {
return mSession!!.firstKnownIndex return olmInboundGroupSession!!.firstKnownIndex
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e, "## getFirstKnownIndex() : getFirstKnownIndex failed") Timber.e(e, "## getFirstKnownIndex() : getFirstKnownIndex failed")
} }
@ -63,18 +63,6 @@ class MXOlmInboundGroupSession2 : Serializable {
return null return null
} }
/**
* Constructor
*
* @param prevFormatSession the previous session format
*/
constructor(prevFormatSession: MXOlmInboundGroupSession) {
mSession = prevFormatSession.mSession
mRoomId = prevFormatSession.mRoomId
mSenderKey = prevFormatSession.mSenderKey
mKeysClaimed = prevFormatSession.mKeysClaimed
}
/** /**
* Constructor * Constructor
* *
@ -84,9 +72,9 @@ class MXOlmInboundGroupSession2 : Serializable {
constructor(sessionKey: String, isImported: Boolean) { constructor(sessionKey: String, isImported: Boolean) {
try { try {
if (!isImported) { if (!isImported) {
mSession = OlmInboundGroupSession(sessionKey) olmInboundGroupSession = OlmInboundGroupSession(sessionKey)
} else { } else {
mSession = OlmInboundGroupSession.importSession(sessionKey) olmInboundGroupSession = OlmInboundGroupSession.importSession(sessionKey)
} }
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e, "Cannot create") Timber.e(e, "Cannot create")
@ -103,15 +91,15 @@ class MXOlmInboundGroupSession2 : Serializable {
@Throws(Exception::class) @Throws(Exception::class)
constructor(megolmSessionData: MegolmSessionData) { constructor(megolmSessionData: MegolmSessionData) {
try { try {
mSession = OlmInboundGroupSession.importSession(megolmSessionData.sessionKey!!) olmInboundGroupSession = OlmInboundGroupSession.importSession(megolmSessionData.sessionKey!!)
if (!TextUtils.equals(mSession!!.sessionIdentifier(), megolmSessionData.sessionId)) { if (!TextUtils.equals(olmInboundGroupSession!!.sessionIdentifier(), megolmSessionData.sessionId)) {
throw Exception("Mismatched group session Id") throw Exception("Mismatched group session Id")
} }
mSenderKey = megolmSessionData.senderKey senderKey = megolmSessionData.senderKey
mKeysClaimed = megolmSessionData.senderClaimedKeys keysClaimed = megolmSessionData.senderClaimedKeys
mRoomId = megolmSessionData.roomId roomId = megolmSessionData.roomId
} catch (e: Exception) { } catch (e: Exception) {
throw Exception(e.message) throw Exception(e.message)
} }
@ -126,21 +114,21 @@ class MXOlmInboundGroupSession2 : Serializable {
var megolmSessionData: MegolmSessionData? = MegolmSessionData() var megolmSessionData: MegolmSessionData? = MegolmSessionData()
try { try {
if (null == mForwardingCurve25519KeyChain) { if (null == forwardingCurve25519KeyChain) {
mForwardingCurve25519KeyChain = ArrayList() forwardingCurve25519KeyChain = ArrayList()
} }
megolmSessionData!!.senderClaimedEd25519Key = mKeysClaimed!!["ed25519"] megolmSessionData!!.senderClaimedEd25519Key = keysClaimed!!["ed25519"]
megolmSessionData.forwardingCurve25519KeyChain = ArrayList(mForwardingCurve25519KeyChain!!) megolmSessionData.forwardingCurve25519KeyChain = ArrayList(forwardingCurve25519KeyChain!!)
megolmSessionData.senderKey = mSenderKey megolmSessionData.senderKey = senderKey
megolmSessionData.senderClaimedKeys = mKeysClaimed megolmSessionData.senderClaimedKeys = keysClaimed
megolmSessionData.roomId = mRoomId megolmSessionData.roomId = roomId
megolmSessionData.sessionId = mSession!!.sessionIdentifier() megolmSessionData.sessionId = olmInboundGroupSession!!.sessionIdentifier()
megolmSessionData.sessionKey = mSession!!.export(mSession!!.firstKnownIndex) megolmSessionData.sessionKey = olmInboundGroupSession!!.export(olmInboundGroupSession!!.firstKnownIndex)
megolmSessionData.algorithm = MXCRYPTO_ALGORITHM_MEGOLM megolmSessionData.algorithm = MXCRYPTO_ALGORITHM_MEGOLM
} catch (e: Exception) { } catch (e: Exception) {
megolmSessionData = null megolmSessionData = null
Timber.e(e, "## export() : senderKey " + mSenderKey + " failed") Timber.e(e, "## export() : senderKey " + senderKey + " failed")
} }
return megolmSessionData return megolmSessionData
@ -153,9 +141,9 @@ class MXOlmInboundGroupSession2 : Serializable {
* @return the exported data * @return the exported data
*/ */
fun exportSession(messageIndex: Long): String? { fun exportSession(messageIndex: Long): String? {
if (null != mSession) { if (null != olmInboundGroupSession) {
try { try {
return mSession!!.export(messageIndex) return olmInboundGroupSession!!.export(messageIndex)
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e, "## exportSession() : export failed") Timber.e(e, "## exportSession() : export failed")
} }

View File

@ -21,7 +21,7 @@ import org.matrix.olm.OlmSession
/** /**
* Encapsulate a OlmSession and a last received message Timestamp * Encapsulate a OlmSession and a last received message Timestamp
*/ */
data class MXOlmSession( data class OlmSessionWrapper(
// The associated olm session. // The associated olm session.
val olmSession: OlmSession, val olmSession: OlmSession,
// Timestamp at which the session last received a message. // Timestamp at which the session last received a message.

View File

@ -20,8 +20,8 @@ package im.vector.matrix.android.internal.crypto.store
import im.vector.matrix.android.internal.crypto.IncomingRoomKeyRequest import im.vector.matrix.android.internal.crypto.IncomingRoomKeyRequest
import im.vector.matrix.android.internal.crypto.OutgoingRoomKeyRequest import im.vector.matrix.android.internal.crypto.OutgoingRoomKeyRequest
import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo
import im.vector.matrix.android.internal.crypto.model.MXOlmInboundGroupSession2 import im.vector.matrix.android.internal.crypto.model.OlmInboundGroupSessionWrapper
import im.vector.matrix.android.internal.crypto.model.MXOlmSession import im.vector.matrix.android.internal.crypto.model.OlmSessionWrapper
import im.vector.matrix.android.internal.crypto.model.rest.RoomKeyRequestBody import im.vector.matrix.android.internal.crypto.model.rest.RoomKeyRequestBody
import im.vector.matrix.android.internal.crypto.store.db.model.KeysBackupDataEntity import im.vector.matrix.android.internal.crypto.store.db.model.KeysBackupDataEntity
import org.matrix.olm.OlmAccount import org.matrix.olm.OlmAccount
@ -46,7 +46,7 @@ internal interface IMXCryptoStore {
* *
* @return the list of all known group sessions, to export them. * @return the list of all known group sessions, to export them.
*/ */
fun getInboundGroupSessions(): List<MXOlmInboundGroupSession2> fun getInboundGroupSessions(): List<OlmInboundGroupSessionWrapper>
/** /**
* @return true to unilaterally blacklist all unverified devices. * @return true to unilaterally blacklist all unverified devices.
@ -153,7 +153,7 @@ internal interface IMXCryptoStore {
* @param userId the user's id. * @param userId the user's id.
* @param device the device to store. * @param device the device to store.
*/ */
fun storeUserDevice(userId: String?, device: MXDeviceInfo?) fun storeUserDevice(userId: String?, deviceInfo: MXDeviceInfo?)
/** /**
* Retrieve a device for a user. * Retrieve a device for a user.
@ -211,10 +211,10 @@ internal interface IMXCryptoStore {
/** /**
* Store a session between the logged-in user and another device. * Store a session between the logged-in user and another device.
* *
* @param session the end-to-end session. * @param olmSessionWrapper the end-to-end session.
* @param deviceKey the public key of the other device. * @param deviceKey the public key of the other device.
*/ */
fun storeSession(session: MXOlmSession, deviceKey: String) fun storeSession(olmSessionWrapper: OlmSessionWrapper, deviceKey: String)
/** /**
* Retrieve the end-to-end session ids between the logged-in user and another * Retrieve the end-to-end session ids between the logged-in user and another
@ -233,7 +233,7 @@ internal interface IMXCryptoStore {
* @param deviceKey the public key of the other device. * @param deviceKey the public key of the other device.
* @return The Base64 end-to-end session, or null if not found * @return The Base64 end-to-end session, or null if not found
*/ */
fun getDeviceSession(sessionId: String?, deviceKey: String?): MXOlmSession? fun getDeviceSession(sessionId: String?, deviceKey: String?): OlmSessionWrapper?
/** /**
* Retrieve the last used sessionId, regarding `lastReceivedMessageTs`, or null if no session exist * Retrieve the last used sessionId, regarding `lastReceivedMessageTs`, or null if no session exist
@ -248,7 +248,7 @@ internal interface IMXCryptoStore {
* *
* @param sessions the inbound group sessions to store. * @param sessions the inbound group sessions to store.
*/ */
fun storeInboundGroupSessions(sessions: List<MXOlmInboundGroupSession2>) fun storeInboundGroupSessions(sessions: List<OlmInboundGroupSessionWrapper>)
/** /**
* Retrieve an inbound group session. * Retrieve an inbound group session.
@ -257,7 +257,7 @@ internal interface IMXCryptoStore {
* @param senderKey the base64-encoded curve25519 key of the sender. * @param senderKey the base64-encoded curve25519 key of the sender.
* @return an inbound group session. * @return an inbound group session.
*/ */
fun getInboundGroupSession(sessionId: String, senderKey: String): MXOlmInboundGroupSession2? fun getInboundGroupSession(sessionId: String, senderKey: String): OlmInboundGroupSessionWrapper?
/** /**
* Remove an inbound group session * Remove an inbound group session
@ -281,7 +281,7 @@ internal interface IMXCryptoStore {
* *
* @param sessions the sessions * @param sessions the sessions
*/ */
fun markBackupDoneForInboundGroupSessions(sessions: List<MXOlmInboundGroupSession2>) fun markBackupDoneForInboundGroupSessions(olmInboundGroupSessionWrappers: List<OlmInboundGroupSessionWrapper>)
/** /**
* Retrieve inbound group sessions that are not yet backed up. * Retrieve inbound group sessions that are not yet backed up.
@ -289,7 +289,7 @@ internal interface IMXCryptoStore {
* @param limit the maximum number of sessions to return. * @param limit the maximum number of sessions to return.
* @return an array of non backed up inbound group sessions. * @return an array of non backed up inbound group sessions.
*/ */
fun inboundGroupSessionsToBackup(limit: Int): List<MXOlmInboundGroupSession2> fun inboundGroupSessionsToBackup(limit: Int): List<OlmInboundGroupSessionWrapper>
/** /**
* Number of stored inbound group sessions. * Number of stored inbound group sessions.

View File

@ -21,8 +21,8 @@ import im.vector.matrix.android.api.auth.data.Credentials
import im.vector.matrix.android.internal.crypto.IncomingRoomKeyRequest import im.vector.matrix.android.internal.crypto.IncomingRoomKeyRequest
import im.vector.matrix.android.internal.crypto.OutgoingRoomKeyRequest import im.vector.matrix.android.internal.crypto.OutgoingRoomKeyRequest
import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo
import im.vector.matrix.android.internal.crypto.model.MXOlmInboundGroupSession2 import im.vector.matrix.android.internal.crypto.model.OlmInboundGroupSessionWrapper
import im.vector.matrix.android.internal.crypto.model.MXOlmSession import im.vector.matrix.android.internal.crypto.model.OlmSessionWrapper
import im.vector.matrix.android.internal.crypto.model.rest.RoomKeyRequestBody import im.vector.matrix.android.internal.crypto.model.rest.RoomKeyRequestBody
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.store.db.model.* import im.vector.matrix.android.internal.crypto.store.db.model.*
@ -50,10 +50,10 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
private var olmAccount: OlmAccount? = null private var olmAccount: OlmAccount? = null
// Cache for OlmSession, to release them properly // Cache for OlmSession, to release them properly
private val olmSessionsToRelease = HashMap<String, MXOlmSession>() private val olmSessionsToRelease = HashMap<String, OlmSessionWrapper>()
// Cache for InboundGroupSession, to release them properly // Cache for InboundGroupSession, to release them properly
private val inboundGroupSessionToRelease = HashMap<String, MXOlmInboundGroupSession2>() private val inboundGroupSessionToRelease = HashMap<String, OlmInboundGroupSessionWrapper>()
/* ========================================================================================== /* ==========================================================================================
* Other data * Other data
@ -114,7 +114,7 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
olmSessionsToRelease.clear() olmSessionsToRelease.clear()
inboundGroupSessionToRelease.forEach { inboundGroupSessionToRelease.forEach {
it.value.mSession?.releaseSession() it.value.olmInboundGroupSession?.releaseSession()
} }
inboundGroupSessionToRelease.clear() inboundGroupSessionToRelease.clear()
@ -254,11 +254,11 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
} }
} }
override fun storeSession(session: MXOlmSession, deviceKey: String) { override fun storeSession(olmSessionWrapper: OlmSessionWrapper, deviceKey: String) {
var sessionIdentifier: String? = null var sessionIdentifier: String? = null
try { try {
sessionIdentifier = session.olmSession.sessionIdentifier() sessionIdentifier = olmSessionWrapper.olmSession.sessionIdentifier()
} catch (e: OlmException) { } catch (e: OlmException) {
Timber.e(e, "## storeSession() : sessionIdentifier failed " + e.message) Timber.e(e, "## storeSession() : sessionIdentifier failed " + e.message)
} }
@ -267,19 +267,19 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
val key = OlmSessionEntity.createPrimaryKey(sessionIdentifier, deviceKey) val key = OlmSessionEntity.createPrimaryKey(sessionIdentifier, deviceKey)
// Release memory of previously known session, if it is not the same one // Release memory of previously known session, if it is not the same one
if (olmSessionsToRelease[key]?.olmSession != session.olmSession) { if (olmSessionsToRelease[key]?.olmSession != olmSessionWrapper.olmSession) {
olmSessionsToRelease[key]?.olmSession?.releaseSession() olmSessionsToRelease[key]?.olmSession?.releaseSession()
} }
olmSessionsToRelease[key] = session olmSessionsToRelease[key] = olmSessionWrapper
doRealmTransaction(realmConfiguration) { doRealmTransaction(realmConfiguration) {
val realmOlmSession = OlmSessionEntity().apply { val realmOlmSession = OlmSessionEntity().apply {
primaryKey = key primaryKey = key
sessionId = sessionIdentifier sessionId = sessionIdentifier
this.deviceKey = deviceKey this.deviceKey = deviceKey
putOlmSession(session.olmSession) putOlmSession(olmSessionWrapper.olmSession)
lastReceivedMessageTs = session.lastReceivedMessageTs lastReceivedMessageTs = olmSessionWrapper.lastReceivedMessageTs
} }
it.insertOrUpdate(realmOlmSession) it.insertOrUpdate(realmOlmSession)
@ -287,7 +287,7 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
} }
} }
override fun getDeviceSession(sessionId: String?, deviceKey: String?): MXOlmSession? { override fun getDeviceSession(sessionId: String?, deviceKey: String?): OlmSessionWrapper? {
if (sessionId == null || deviceKey == null) { if (sessionId == null || deviceKey == null) {
return null return null
} }
@ -304,7 +304,7 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
?.let { ?.let {
val olmSession = it.getOlmSession() val olmSession = it.getOlmSession()
if (olmSession != null && it.sessionId != null) { if (olmSession != null && it.sessionId != null) {
olmSessionsToRelease[key] = MXOlmSession(olmSession, it.lastReceivedMessageTs) olmSessionsToRelease[key] = OlmSessionWrapper(olmSession, it.lastReceivedMessageTs)
} }
} }
} }
@ -334,7 +334,7 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
.toMutableSet() .toMutableSet()
} }
override fun storeInboundGroupSessions(sessions: List<MXOlmInboundGroupSession2>) { override fun storeInboundGroupSessions(sessions: List<OlmInboundGroupSessionWrapper>) {
if (sessions.isEmpty()) { if (sessions.isEmpty()) {
return return
} }
@ -344,17 +344,17 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
var sessionIdentifier: String? = null var sessionIdentifier: String? = null
try { try {
sessionIdentifier = session.mSession?.sessionIdentifier() sessionIdentifier = session.olmInboundGroupSession?.sessionIdentifier()
} catch (e: OlmException) { } catch (e: OlmException) {
Timber.e(e, "## storeInboundGroupSession() : sessionIdentifier failed " + e.message) Timber.e(e, "## storeInboundGroupSession() : sessionIdentifier failed " + e.message)
} }
if (sessionIdentifier != null) { if (sessionIdentifier != null) {
val key = OlmInboundGroupSessionEntity.createPrimaryKey(sessionIdentifier, session.mSenderKey) val key = OlmInboundGroupSessionEntity.createPrimaryKey(sessionIdentifier, session.senderKey)
// Release memory of previously known session, if it is not the same one // Release memory of previously known session, if it is not the same one
if (inboundGroupSessionToRelease[key] != session) { if (inboundGroupSessionToRelease[key] != session) {
inboundGroupSessionToRelease[key]?.mSession?.releaseSession() inboundGroupSessionToRelease[key]?.olmInboundGroupSession?.releaseSession()
} }
inboundGroupSessionToRelease[key] = session inboundGroupSessionToRelease[key] = session
@ -362,7 +362,7 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
val realmOlmInboundGroupSession = OlmInboundGroupSessionEntity().apply { val realmOlmInboundGroupSession = OlmInboundGroupSessionEntity().apply {
primaryKey = key primaryKey = key
sessionId = sessionIdentifier sessionId = sessionIdentifier
senderKey = session.mSenderKey senderKey = session.senderKey
putInboundGroupSession(session) putInboundGroupSession(session)
} }
@ -372,7 +372,7 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
} }
} }
override fun getInboundGroupSession(sessionId: String, senderKey: String): MXOlmInboundGroupSession2? { override fun getInboundGroupSession(sessionId: String, senderKey: String): OlmInboundGroupSessionWrapper? {
val key = OlmInboundGroupSessionEntity.createPrimaryKey(sessionId, senderKey) val key = OlmInboundGroupSessionEntity.createPrimaryKey(sessionId, senderKey)
// If not in cache (or not found), try to read it from realm // If not in cache (or not found), try to read it from realm
@ -392,10 +392,10 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
} }
/** /**
* Note: the result will be only use to export all the keys and not to use the MXOlmInboundGroupSession2, * Note: the result will be only use to export all the keys and not to use the OlmInboundGroupSessionWrapper,
* so there is no need to use or update `inboundGroupSessionToRelease` for native memory management * so there is no need to use or update `inboundGroupSessionToRelease` for native memory management
*/ */
override fun getInboundGroupSessions(): MutableList<MXOlmInboundGroupSession2> { override fun getInboundGroupSessions(): MutableList<OlmInboundGroupSessionWrapper> {
return doRealmQueryAndCopyList(realmConfiguration) { return doRealmQueryAndCopyList(realmConfiguration) {
it.where<OlmInboundGroupSessionEntity>() it.where<OlmInboundGroupSessionEntity>()
.findAll() .findAll()
@ -410,7 +410,7 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
val key = OlmInboundGroupSessionEntity.createPrimaryKey(sessionId, senderKey) val key = OlmInboundGroupSessionEntity.createPrimaryKey(sessionId, senderKey)
// Release memory of previously known session // Release memory of previously known session
inboundGroupSessionToRelease[key]?.mSession?.releaseSession() inboundGroupSessionToRelease[key]?.olmInboundGroupSession?.releaseSession()
inboundGroupSessionToRelease.remove(key) inboundGroupSessionToRelease.remove(key)
doRealmTransaction(realmConfiguration) { doRealmTransaction(realmConfiguration) {
@ -467,15 +467,17 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
} }
} }
override fun markBackupDoneForInboundGroupSessions(sessions: List<MXOlmInboundGroupSession2>) { override fun markBackupDoneForInboundGroupSessions(olmInboundGroupSessionWrappers: List<OlmInboundGroupSessionWrapper>) {
if (sessions.isEmpty()) { if (olmInboundGroupSessionWrappers.isEmpty()) {
return return
} }
doRealmTransaction(realmConfiguration) { doRealmTransaction(realmConfiguration) {
sessions.forEach { session -> olmInboundGroupSessionWrappers.forEach { olmInboundGroupSessionWrapper ->
try { try {
val key = OlmInboundGroupSessionEntity.createPrimaryKey(session.mSession?.sessionIdentifier(), session.mSenderKey) val key = OlmInboundGroupSessionEntity.createPrimaryKey(
olmInboundGroupSessionWrapper.olmInboundGroupSession?.sessionIdentifier(),
olmInboundGroupSessionWrapper.senderKey)
it.where<OlmInboundGroupSessionEntity>() it.where<OlmInboundGroupSessionEntity>()
.equalTo(OlmInboundGroupSessionEntityFields.PRIMARY_KEY, key) .equalTo(OlmInboundGroupSessionEntityFields.PRIMARY_KEY, key)
@ -488,7 +490,7 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
} }
} }
override fun inboundGroupSessionsToBackup(limit: Int): List<MXOlmInboundGroupSession2> { override fun inboundGroupSessionsToBackup(limit: Int): List<OlmInboundGroupSessionWrapper> {
return doRealmQueryAndCopyList(realmConfiguration) { return doRealmQueryAndCopyList(realmConfiguration) {
it.where<OlmInboundGroupSessionEntity>() it.where<OlmInboundGroupSessionEntity>()
.equalTo(OlmInboundGroupSessionEntityFields.BACKED_UP, false) .equalTo(OlmInboundGroupSessionEntityFields.BACKED_UP, false)

View File

@ -20,7 +20,7 @@ import io.realm.RealmObject
import io.realm.annotations.PrimaryKey import io.realm.annotations.PrimaryKey
import im.vector.matrix.android.internal.crypto.store.db.deserializeFromRealm import im.vector.matrix.android.internal.crypto.store.db.deserializeFromRealm
import im.vector.matrix.android.internal.crypto.store.db.serializeForRealm import im.vector.matrix.android.internal.crypto.store.db.serializeForRealm
import im.vector.matrix.android.internal.crypto.model.MXOlmInboundGroupSession2 import im.vector.matrix.android.internal.crypto.model.OlmInboundGroupSessionWrapper
internal fun OlmInboundGroupSessionEntity.Companion.createPrimaryKey(sessionId: String?, senderKey: String?) = "$sessionId|$senderKey" internal fun OlmInboundGroupSessionEntity.Companion.createPrimaryKey(sessionId: String?, senderKey: String?) = "$sessionId|$senderKey"
@ -35,12 +35,12 @@ internal open class OlmInboundGroupSessionEntity(
var backedUp: Boolean = false) var backedUp: Boolean = false)
: RealmObject() { : RealmObject() {
fun getInboundGroupSession(): MXOlmInboundGroupSession2? { fun getInboundGroupSession(): OlmInboundGroupSessionWrapper? {
return deserializeFromRealm(olmInboundGroupSessionData) return deserializeFromRealm(olmInboundGroupSessionData)
} }
fun putInboundGroupSession(mxOlmInboundGroupSession2: MXOlmInboundGroupSession2?) { fun putInboundGroupSession(olmInboundGroupSessionWrapper: OlmInboundGroupSessionWrapper?) {
olmInboundGroupSessionData = serializeForRealm(mxOlmInboundGroupSession2) olmInboundGroupSessionData = serializeForRealm(olmInboundGroupSessionWrapper)
} }
companion object companion object

View File

@ -35,22 +35,22 @@ import im.vector.matrix.android.internal.task.TaskExecutor
import timber.log.Timber import timber.log.Timber
internal class IncomingSASVerificationTransaction( internal class IncomingSASVerificationTransaction(
private val mSasVerificationService: DefaultSasVerificationService, private val sasVerificationService: DefaultSasVerificationService,
private val mSetDeviceVerificationAction: SetDeviceVerificationAction, private val setDeviceVerificationAction: SetDeviceVerificationAction,
private val mCredentials: Credentials, private val credentials: Credentials,
private val mCryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
private val mSendToDeviceTask: SendToDeviceTask, private val sendToDeviceTask: SendToDeviceTask,
private val mTaskExecutor: TaskExecutor, private val taskExecutor: TaskExecutor,
deviceFingerprint: String, deviceFingerprint: String,
transactionId: String, transactionId: String,
otherUserID: String) otherUserID: String)
: SASVerificationTransaction( : SASVerificationTransaction(
mSasVerificationService, sasVerificationService,
mSetDeviceVerificationAction, setDeviceVerificationAction,
mCredentials, credentials,
mCryptoStore, cryptoStore,
mSendToDeviceTask, sendToDeviceTask,
mTaskExecutor, taskExecutor,
deviceFingerprint, deviceFingerprint,
transactionId, transactionId,
otherUserID, otherUserID,
@ -118,7 +118,7 @@ internal class IncomingSASVerificationTransaction(
} }
//Bobs device ensures that it has a copy of Alices device key. //Bobs device ensures that it has a copy of Alices device key.
val mxDeviceInfo = mCryptoStore.getUserDevice(deviceId = otherDeviceId!!, userId = otherUserId) val mxDeviceInfo = cryptoStore.getUserDevice(deviceId = otherDeviceId!!, userId = otherUserId)
if (mxDeviceInfo?.fingerprint() == null) { if (mxDeviceInfo?.fingerprint() == null) {
Timber.e("## Failed to find device key ") Timber.e("## Failed to find device key ")
@ -209,7 +209,7 @@ internal class IncomingSASVerificationTransaction(
// - the transaction ID. // - the transaction ID.
val sasInfo = "MATRIX_KEY_VERIFICATION_SAS" + val sasInfo = "MATRIX_KEY_VERIFICATION_SAS" +
"$otherUserId$otherDeviceId" + "$otherUserId$otherDeviceId" +
"${mCredentials.userId}${mCredentials.deviceId}" + "${credentials.userId}${credentials.deviceId}" +
transactionId transactionId
//decimal: generate five bytes by using HKDF. //decimal: generate five bytes by using HKDF.
//emoji: generate six bytes by using HKDF. //emoji: generate six bytes by using HKDF.

View File

@ -33,23 +33,23 @@ import im.vector.matrix.android.internal.task.TaskExecutor
import timber.log.Timber import timber.log.Timber
internal class OutgoingSASVerificationRequest( internal class OutgoingSASVerificationRequest(
private val mSasVerificationService: DefaultSasVerificationService, private val sasVerificationService: DefaultSasVerificationService,
private val mSetDeviceVerificationAction: SetDeviceVerificationAction, private val setDeviceVerificationAction: SetDeviceVerificationAction,
private val mCredentials: Credentials, private val credentials: Credentials,
private val mCryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
private val mSendToDeviceTask: SendToDeviceTask, private val sendToDeviceTask: SendToDeviceTask,
private val mTaskExecutor: TaskExecutor, private val taskExecutor: TaskExecutor,
deviceFingerprint: String, deviceFingerprint: String,
transactionId: String, transactionId: String,
otherUserId: String, otherUserId: String,
otherDeviceId: String) otherDeviceId: String)
: SASVerificationTransaction( : SASVerificationTransaction(
mSasVerificationService, sasVerificationService,
mSetDeviceVerificationAction, setDeviceVerificationAction,
mCredentials, credentials,
mCryptoStore, cryptoStore,
mSendToDeviceTask, sendToDeviceTask,
mTaskExecutor, taskExecutor,
deviceFingerprint, deviceFingerprint,
transactionId, transactionId,
otherUserId, otherUserId,
@ -94,7 +94,7 @@ internal class OutgoingSASVerificationRequest(
} }
val startMessage = KeyVerificationStart() val startMessage = KeyVerificationStart()
startMessage.fromDevice = mCredentials.deviceId startMessage.fromDevice = credentials.deviceId
startMessage.method = KeyVerificationStart.VERIF_METHOD_SAS startMessage.method = KeyVerificationStart.VERIF_METHOD_SAS
startMessage.transactionID = transactionId startMessage.transactionID = transactionId
startMessage.keyAgreementProtocols = KNOWN_AGREEMENT_PROTOCOLS startMessage.keyAgreementProtocols = KNOWN_AGREEMENT_PROTOCOLS
@ -182,7 +182,7 @@ internal class OutgoingSASVerificationRequest(
// - he device ID of the device that sent the m.key.verification.accept message // - he device ID of the device that sent the m.key.verification.accept message
// - the transaction ID. // - the transaction ID.
val sasInfo = "MATRIX_KEY_VERIFICATION_SAS" + val sasInfo = "MATRIX_KEY_VERIFICATION_SAS" +
"${mCredentials.userId}${mCredentials.deviceId}" + "${credentials.userId}${credentials.deviceId}" +
"$otherUserId$otherDeviceId" + "$otherUserId$otherDeviceId" +
transactionId transactionId
//decimal: generate five bytes by using HKDF. //decimal: generate five bytes by using HKDF.

View File

@ -42,12 +42,12 @@ import kotlin.properties.Delegates
* Represents an ongoing short code interactive key verification between two devices. * Represents an ongoing short code interactive key verification between two devices.
*/ */
internal abstract class SASVerificationTransaction( internal abstract class SASVerificationTransaction(
private val mSasVerificationService: DefaultSasVerificationService, private val sasVerificationService: DefaultSasVerificationService,
private val mSetDeviceVerificationAction: SetDeviceVerificationAction, private val setDeviceVerificationAction: SetDeviceVerificationAction,
private val mCredentials: Credentials, private val credentials: Credentials,
private val mCryptoStore: IMXCryptoStore, private val cryptoStore: IMXCryptoStore,
private val mSendToDeviceTask: SendToDeviceTask, private val sendToDeviceTask: SendToDeviceTask,
private val mTaskExecutor: TaskExecutor, private val taskExecutor: TaskExecutor,
private val deviceFingerprint: String, private val deviceFingerprint: String,
transactionId: String, transactionId: String,
otherUserId: String, otherUserId: String,
@ -146,11 +146,11 @@ internal abstract class SASVerificationTransaction(
// - the key ID of the key being MAC-ed, or the string “KEY_IDS” if the item being MAC-ed is the list of key IDs. // - the key ID of the key being MAC-ed, or the string “KEY_IDS” if the item being MAC-ed is the list of key IDs.
val baseInfo = "MATRIX_KEY_VERIFICATION_MAC" + val baseInfo = "MATRIX_KEY_VERIFICATION_MAC" +
mCredentials.userId + mCredentials.deviceId + credentials.userId + credentials.deviceId +
otherUserId + otherDeviceId + otherUserId + otherDeviceId +
transactionId transactionId
val keyId = "ed25519:${mCredentials.deviceId}" val keyId = "ed25519:${credentials.deviceId}"
val macString = macUsingAgreedMethod(deviceFingerprint, baseInfo + keyId) val macString = macUsingAgreedMethod(deviceFingerprint, baseInfo + keyId)
val keyStrings = macUsingAgreedMethod(keyId, baseInfo + "KEY_IDS") val keyStrings = macUsingAgreedMethod(keyId, baseInfo + "KEY_IDS")
@ -203,7 +203,7 @@ internal abstract class SASVerificationTransaction(
state = SasVerificationTxState.Verifying state = SasVerificationTxState.Verifying
//Keys have been downloaded earlier in process //Keys have been downloaded earlier in process
val otherUserKnownDevices = mCryptoStore.getUserDevices(otherUserId) val otherUserKnownDevices = cryptoStore.getUserDevices(otherUserId)
// Bobs device calculates the HMAC (as above) of its copies of Alices keys given in the message (as identified by their key ID), // Bobs device calculates the HMAC (as above) of its copies of Alices keys given in the message (as identified by their key ID),
// as well as the HMAC of the comma-separated, sorted list of the key IDs given in the message. // as well as the HMAC of the comma-separated, sorted list of the key IDs given in the message.
@ -212,7 +212,7 @@ internal abstract class SASVerificationTransaction(
val baseInfo = "MATRIX_KEY_VERIFICATION_MAC" + val baseInfo = "MATRIX_KEY_VERIFICATION_MAC" +
otherUserId + otherDeviceId + otherUserId + otherDeviceId +
mCredentials.userId + mCredentials.deviceId + credentials.userId + credentials.deviceId +
transactionId transactionId
val commaSeparatedListOfKeyIds = theirMac!!.mac!!.keys.sorted().joinToString(",") val commaSeparatedListOfKeyIds = theirMac!!.mac!!.keys.sorted().joinToString(",")
@ -247,7 +247,7 @@ internal abstract class SASVerificationTransaction(
} }
private fun setDeviceVerified(deviceId: String, userId: String) { private fun setDeviceVerified(deviceId: String, userId: String) {
mSetDeviceVerificationAction.handle(MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED, setDeviceVerificationAction.handle(MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED,
deviceId, deviceId,
userId) userId)
} }
@ -259,7 +259,7 @@ internal abstract class SASVerificationTransaction(
override fun cancel(code: CancelCode) { override fun cancel(code: CancelCode) {
cancelledReason = code cancelledReason = code
state = SasVerificationTxState.Cancelled state = SasVerificationTxState.Cancelled
mSasVerificationService.cancelTransaction( sasVerificationService.cancelTransaction(
transactionId, transactionId,
otherUserId, otherUserId,
otherDeviceId ?: "", otherDeviceId ?: "",
@ -274,7 +274,7 @@ internal abstract class SASVerificationTransaction(
val contentMap = MXUsersDevicesMap<Any>() val contentMap = MXUsersDevicesMap<Any>()
contentMap.setObject(keyToDevice, otherUserId, otherDeviceId) contentMap.setObject(keyToDevice, otherUserId, otherDeviceId)
mSendToDeviceTask.configureWith(SendToDeviceTask.Params(type, contentMap, transactionId)) sendToDeviceTask.configureWith(SendToDeviceTask.Params(type, contentMap, transactionId))
.dispatchTo(object : MatrixCallback<Unit> { .dispatchTo(object : MatrixCallback<Unit> {
override fun onSuccess(data: Unit) { override fun onSuccess(data: Unit) {
Timber.v("## SAS verification [$transactionId] toDevice type '$type' success.") Timber.v("## SAS verification [$transactionId] toDevice type '$type' success.")
@ -295,7 +295,7 @@ internal abstract class SASVerificationTransaction(
} }
} }
}) })
.executeBy(mTaskExecutor) .executeBy(taskExecutor)
} }
fun getShortCodeRepresentation(shortAuthenticationStringMode: String): String? { fun getShortCodeRepresentation(shortAuthenticationStringMode: String): String? {

View File

@ -23,19 +23,19 @@ import java.security.cert.X509Certificate
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
data class Fingerprint( data class Fingerprint(
val mBytes: ByteArray, val bytes: ByteArray,
val mHashType: HashType val hashType: HashType
) { ) {
val displayableHexRepr: String by lazy { val displayableHexRepr: String by lazy {
CertUtil.fingerprintToHexString(mBytes) CertUtil.fingerprintToHexString(bytes)
} }
@Throws(CertificateException::class) @Throws(CertificateException::class)
fun matchesCert(cert: X509Certificate): Boolean { fun matchesCert(cert: X509Certificate): Boolean {
var o: Fingerprint? = when (mHashType) { var o: Fingerprint? = when (hashType) {
Fingerprint.HashType.SHA256 -> Fingerprint.newSha256Fingerprint(cert) HashType.SHA256 -> newSha256Fingerprint(cert)
Fingerprint.HashType.SHA1 -> Fingerprint.newSha1Fingerprint(cert) HashType.SHA1 -> newSha1Fingerprint(cert)
} }
return equals(o) return equals(o)
} }
@ -45,15 +45,15 @@ data class Fingerprint(
if (javaClass != other?.javaClass) return false if (javaClass != other?.javaClass) return false
other as Fingerprint other as Fingerprint
if (!mBytes.contentEquals(other.mBytes)) return false if (!bytes.contentEquals(other.bytes)) return false
if (mHashType != other.mHashType) return false if (hashType != other.hashType) return false
return true return true
} }
override fun hashCode(): Int { override fun hashCode(): Int {
var result = mBytes.contentHashCode() var result = bytes.contentHashCode()
result = 31 * result + mHashType.hashCode() result = 31 * result + hashType.hashCode()
return result return result
} }

View File

@ -82,8 +82,8 @@ internal class EncryptEventWorker(context: Context, params: WorkerParameters)
val safeResult = result val safeResult = result
if (safeResult != null) { if (safeResult != null) {
val encryptedEvent = localEvent.copy( val encryptedEvent = localEvent.copy(
type = safeResult.mEventType, type = safeResult.eventType,
content = safeResult.mEventContent content = safeResult.eventContent
) )
val nextWorkerParams = SendEventWorker.Params(params.roomId, encryptedEvent) val nextWorkerParams = SendEventWorker.Params(params.roomId, encryptedEvent)
return Result.success(WorkerParamsFactory.toData(nextWorkerParams)) return Result.success(WorkerParamsFactory.toData(nextWorkerParams))

View File

@ -43,7 +43,7 @@ internal class RoomSyncHandler(private val monarchy: Monarchy,
private val readReceiptHandler: ReadReceiptHandler, private val readReceiptHandler: ReadReceiptHandler,
private val roomSummaryUpdater: RoomSummaryUpdater, private val roomSummaryUpdater: RoomSummaryUpdater,
private val roomTagHandler: RoomTagHandler, private val roomTagHandler: RoomTagHandler,
private val mCrypto: CryptoManager) { private val cryptoManager: CryptoManager) {
sealed class HandlingStrategy { sealed class HandlingStrategy {
data class JOINED(val data: Map<String, RoomSync>) : HandlingStrategy() data class JOINED(val data: Map<String, RoomSync>) : HandlingStrategy()
@ -53,9 +53,9 @@ internal class RoomSyncHandler(private val monarchy: Monarchy,
fun handle(roomsSyncResponse: RoomsSyncResponse) { fun handle(roomsSyncResponse: RoomsSyncResponse) {
monarchy.runTransactionSync { realm -> monarchy.runTransactionSync { realm ->
handleRoomSync(realm, RoomSyncHandler.HandlingStrategy.JOINED(roomsSyncResponse.join)) handleRoomSync(realm, HandlingStrategy.JOINED(roomsSyncResponse.join))
handleRoomSync(realm, RoomSyncHandler.HandlingStrategy.INVITED(roomsSyncResponse.invite)) handleRoomSync(realm, HandlingStrategy.INVITED(roomsSyncResponse.invite))
handleRoomSync(realm, RoomSyncHandler.HandlingStrategy.LEFT(roomsSyncResponse.leave)) handleRoomSync(realm, HandlingStrategy.LEFT(roomsSyncResponse.leave))
} }
} }
@ -97,7 +97,7 @@ internal class RoomSyncHandler(private val monarchy: Monarchy,
// Give info to crypto module // Give info to crypto module
roomSync.state.events.forEach { roomSync.state.events.forEach {
mCrypto.onStateEvent(roomId, it) cryptoManager.onStateEvent(roomId, it)
} }
} }
@ -115,7 +115,7 @@ internal class RoomSyncHandler(private val monarchy: Monarchy,
// Give info to crypto module // Give info to crypto module
roomSync.timeline.events.forEach { roomSync.timeline.events.forEach {
mCrypto.onLiveEvent(roomId, it) cryptoManager.onLiveEvent(roomId, it)
} }
// Try to remove local echo // Try to remove local echo

View File

@ -77,7 +77,7 @@ class KeysBackupSettingsFragment : VectorBaseFragment(),
else -> { else -> {
viewModel.loadingEvent.value = null viewModel.loadingEvent.value = null
//All this cases will be manage by looking at the backup trust object //All this cases will be manage by looking at the backup trust object
viewModel.session?.getKeysBackupService()?.mKeysBackupVersion?.let { viewModel.session?.getKeysBackupService()?.keysBackupVersion?.let {
viewModel.getKeysBackupTrust(it) viewModel.getKeysBackupTrust(it)
} ?: run { } ?: run {
viewModel.keyVersionTrust.value = null viewModel.keyVersionTrust.value = null

View File

@ -91,7 +91,7 @@ class KeysBackupSettingsRecyclerViewAdapter(val context: Context) : RecyclerView
fun updateWithTrust(session: Session, keyBackupVersionTrust: KeysBackupVersionTrust?) { fun updateWithTrust(session: Session, keyBackupVersionTrust: KeysBackupVersionTrust?) {
val keyBackupState = session.getKeysBackupService().state val keyBackupState = session.getKeysBackupService().state
val keyVersionResult = session.getKeysBackupService().mKeysBackupVersion val keyVersionResult = session.getKeysBackupService().keysBackupVersion
val infos = ArrayList<GenericRecyclerViewItem>() val infos = ArrayList<GenericRecyclerViewItem>()
var itemSummary: GenericRecyclerViewItem? = null var itemSummary: GenericRecyclerViewItem? = null