Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -185,12 +185,12 @@ open class EncryptedFoldersIT : AbstractOnServerIT() {
}

private fun uploadFolderMetadata(ocFile: OCFile) {
val publicKey = arbitraryDataProvider.getValue(user, EncryptionUtils.PUBLIC_KEY)
val certificate = arbitraryDataProvider.getValue(user, EncryptionUtils.CERTIFICATE)
val privateKey = arbitraryDataProvider.getValue(user, EncryptionUtils.PRIVATE_KEY)
val uploadedMetadata = encryptionKeyGenerator.uploadEncryptedFolderMetadata(
ocFile,
client,
publicKey,
certificate,
privateKey,
storageManager,
arbitraryDataProvider
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public class EncryptionTestIT extends AbstractIT {
"JLecOFu3ZlQl/RStQb69QKb5MNOIMmQhg8WOxZxHcpmIDbkDAm/J/ovJXFSoBdOr5o" +
"uQsYsDZhsWW97zvLMzg5pH9/3/1BNz5q3Vu4HgfBSwWGt4E2NENj+XA+QAVmGA==";

public static final String publicKey = "-----BEGIN CERTIFICATE-----\n" +
public static final String certificate = "-----BEGIN CERTIFICATE-----\n" +
"MIIDpzCCAo+gAwIBAgIBADANBgkqhkiG9w0BAQUFADBuMRowGAYDVQQDDBF3d3cu\n" +
"bmV4dGNsb3VkLmNvbTESMBAGA1UECgwJTmV4dGNsb3VkMRIwEAYDVQQHDAlTdHV0\n" +
"dGdhcnQxGzAZBgNVBAgMEkJhZGVuLVd1ZXJ0dGVtYmVyZzELMAkGA1UEBhMCREUw\n" +
Expand Down Expand Up @@ -146,7 +146,7 @@ public void encryptStringAsymmetric() throws Exception {
byte[] key1 = generateKey();
String base64encodedKey = encodeBytesToBase64String(key1);

String encryptedString = EncryptionUtils.encryptStringAsymmetric(base64encodedKey, publicKey);
String encryptedString = EncryptionUtils.encryptStringAsymmetric(base64encodedKey, certificate);
String decryptedString = decryptStringAsymmetric(encryptedString, privateKey);

byte[] key2 = decodeStringToBase64Bytes(decryptedString);
Expand Down Expand Up @@ -292,7 +292,7 @@ public void encryptionMetadataV1() throws Exception {
// encrypt
EncryptedFolderMetadataFileV1 encryptedFolderMetadata1 = encryptFolderMetadata(
decryptedFolderMetadata1,
publicKey,
certificate,
1,
user,
arbitraryDataProvider);
Expand Down Expand Up @@ -326,7 +326,7 @@ public void testChangedMetadataKey() throws Exception {
// encrypt
EncryptedFolderMetadataFileV1 encryptedFolderMetadata1 = encryptFolderMetadata(
decryptedFolderMetadata1,
publicKey,
certificate,
folderID,
user,
arbitraryDataProvider);
Expand All @@ -338,7 +338,7 @@ public void testChangedMetadataKey() throws Exception {
// encrypt
EncryptedFolderMetadataFileV1 encryptedFolderMetadata2 = encryptFolderMetadata(
decryptedFolderMetadata1,
publicKey,
certificate,
folderID,
user,
arbitraryDataProvider);
Expand All @@ -356,7 +356,7 @@ public void testMigrateMetadataKey() throws Exception {
// encrypt
EncryptedFolderMetadataFileV1 encryptedFolderMetadata1 = encryptFolderMetadata(
decryptedFolderMetadata1,
publicKey,
certificate,
folderID,
user,
arbitraryDataProvider);
Expand All @@ -369,7 +369,7 @@ public void testMigrateMetadataKey() throws Exception {
// encrypt
EncryptedFolderMetadataFileV1 encryptedFolderMetadata2 = encryptFolderMetadata(
decryptedFolderMetadata1,
publicKey,
certificate,
folderID,
user,
arbitraryDataProvider);
Expand Down Expand Up @@ -414,7 +414,7 @@ public void bigMetadata() throws Exception {
// encrypt
EncryptedFolderMetadataFileV1 encryptedFolderMetadata1 = encryptFolderMetadata(
decryptedFolderMetadata1,
publicKey,
certificate,
folderID,
user,
arbitraryDataProvider);
Expand Down Expand Up @@ -452,7 +452,7 @@ public void bigMetadata() throws Exception {

// encrypt
encryptedFolderMetadata1 = encryptFolderMetadata(decryptedFolderMetadata1,
publicKey,
certificate,
folderID,
user,
arbitraryDataProvider);
Expand Down Expand Up @@ -489,7 +489,7 @@ public void bigMetadata2() throws Exception {
// encrypt
EncryptedFolderMetadataFileV1 encryptedFolderMetadata1 = encryptFolderMetadata(
decryptedFolderMetadata1,
publicKey,
certificate,
folderID,
user,
arbitraryDataProvider);
Expand Down Expand Up @@ -528,7 +528,7 @@ public void bigMetadata2() throws Exception {
// encrypt
encryptedFolderMetadata1 = encryptFolderMetadata(
decryptedFolderMetadata1,
publicKey,
certificate,
folderID,
user,
arbitraryDataProvider);
Expand Down Expand Up @@ -584,11 +584,11 @@ public void filedrop() throws Exception {
// encrypt
EncryptedFolderMetadataFileV1 encryptedFolderMetadata1 = encryptFolderMetadata(
decryptedFolderMetadata1,
publicKey,
certificate,
folderID,
user,
arbitraryDataProvider);
EncryptionUtils.encryptFileDropFiles(decryptedFolderMetadata1, encryptedFolderMetadata1, publicKey);
EncryptionUtils.encryptFileDropFiles(decryptedFolderMetadata1, encryptedFolderMetadata1, certificate);

// serialize
String encryptedJson = serializeJSON(encryptedFolderMetadata1, true);
Expand Down Expand Up @@ -785,9 +785,9 @@ private DecryptedFolderMetadataFileV1 generateFolderMetadataV1_1() throws Except
String metadataKey1 = encodeBytesToBase64String(generateKey());
String metadataKey2 = encodeBytesToBase64String(generateKey());
HashMap<Integer, String> metadataKeys = new HashMap<>();
metadataKeys.put(0, EncryptionUtils.encryptStringAsymmetric(metadataKey0, publicKey));
metadataKeys.put(1, EncryptionUtils.encryptStringAsymmetric(metadataKey1, publicKey));
metadataKeys.put(2, EncryptionUtils.encryptStringAsymmetric(metadataKey2, publicKey));
metadataKeys.put(0, EncryptionUtils.encryptStringAsymmetric(metadataKey0, certificate));
metadataKeys.put(1, EncryptionUtils.encryptStringAsymmetric(metadataKey1, certificate));
metadataKeys.put(2, EncryptionUtils.encryptStringAsymmetric(metadataKey2, certificate));
Encrypted encrypted = new Encrypted();
encrypted.setMetadataKeys(metadataKeys);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class EncryptionTestUtils {
"GsYOFuUehKUBXSJ0929hdP0sjOQDJN3DEDISzmgdWX5NyLJxEYgFWNivpePjWCWzOzyua3nPSpvxPIUB7xh27gjT91glj1hEmy" +
"sCd7+9yoMPiCXR7iigRycxegI/Krd39QzISSk9O0finfytU="

val t1PublicKey = """-----BEGIN CERTIFICATE-----
val t1Certificate = """-----BEGIN CERTIFICATE-----
MIIC6DCCAdCgAwIBAgIBADANBgkqhkiG9w0BAQUFADANMQswCQYDVQQDDAJ0MTAe
Fw0yMzA3MjUwNzU3MTJaFw00MzA3MjAwNzU3MTJaMA0xCzAJBgNVBAMMAnQxMIIB
IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtafHmDBcBqIu4HmMxMDW3j0S
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ class EncryptionUtilsIT : EncryptionIT() {
org.bouncycastle.operator.OperatorCreationException::class
)
@Test
fun saveAndRestorePublicKey() {
fun saveAndRestoreShareeCertificate() {
val arbitraryDataProvider = ArbitraryDataProviderImpl(targetContext)
val keyPair = EncryptionKeyGenerator.generateKeyPair()
val e2eUser = "e2e-user"
val key = CsrHelper().generateCsrPemEncodedString(keyPair, e2eUser)

EncryptionUtils.savePublicKey(user, key, e2eUser, arbitraryDataProvider)
EncryptionUtils.saveShareeCertificate(user, key, e2eUser, arbitraryDataProvider)

assertEquals(key, EncryptionUtils.getPublicKey(user, e2eUser, arbitraryDataProvider))
assertEquals(key, EncryptionUtils.getShareeCertificate(user, e2eUser, arbitraryDataProvider))
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ class EncryptionUtilsV2IT : EncryptionIT() {
val metadataKeyBase64 = EncryptionUtils.generateKeyString()
val metadataKey = EncryptionUtils.decodeStringToBase64Bytes(metadataKeyBase64)

val user = DecryptedUser("t1", encryptionTestUtils.t1PublicKey, null)
val user = DecryptedUser("t1", encryptionTestUtils.t1Certificate, null)

val encryptedUser = encryptionUtilsV2.encryptUser(user, metadataKey)
assertNotEquals(encryptedUser.encryptedMetadataKey, metadataKeyBase64)
Expand Down Expand Up @@ -861,7 +861,7 @@ class EncryptionUtilsV2IT : EncryptionIT() {
""".trimMargin()

val privateKey = EncryptionUtils.PEMtoPrivateKey(encryptionTestUtils.t1PrivateKey)
val certificateT1 = EncryptionUtils.convertCertFromString(encryptionTestUtils.t1PublicKey)
val certificateT1 = EncryptionUtils.convertCertFromString(encryptionTestUtils.t1Certificate)
val certificateEnc2 = EncryptionUtils.convertCertFromString(enc2Cert)

val signed = encryptionUtilsV2.signMessage(
Expand All @@ -884,7 +884,7 @@ class EncryptionUtilsV2IT : EncryptionIT() {
val sut = "randomstring123"

val privateKey = EncryptionUtils.PEMtoPrivateKey(encryptionTestUtils.t1PrivateKey)
val certificate = EncryptionUtils.convertCertFromString(encryptionTestUtils.t1PublicKey)
val certificate = EncryptionUtils.convertCertFromString(encryptionTestUtils.t1Certificate)

val signed = encryptionUtilsV2.signMessage(
certificate,
Expand All @@ -907,7 +907,7 @@ class EncryptionUtilsV2IT : EncryptionIT() {

val metadata = EncryptionTestUtils().generateFolderMetadataV2(
client.userId,
EncryptionTestIT.publicKey
EncryptionTestIT.certificate
)

RefreshFolderOperation.updateFileNameForEncryptedFile(storageManager, metadata, folder)
Expand All @@ -923,7 +923,7 @@ class EncryptionUtilsV2IT : EncryptionIT() {
@Throws(Exception::class, Throwable::class)
fun encryptionMetadataV2() {
val decryptedFolderMetadata1: DecryptedFolderMetadataFile =
EncryptionTestUtils().generateFolderMetadataV2(client.userId, EncryptionTestIT.publicKey)
EncryptionTestUtils().generateFolderMetadataV2(client.userId, EncryptionTestIT.certificate)
setE2EECapabilityVersion(E2EVersion.fromValue(decryptedFolderMetadata1.version))
val root = OCFile("/")
storageManager.saveFile(root)
Expand All @@ -942,7 +942,7 @@ class EncryptionUtilsV2IT : EncryptionIT() {
folder,
storageManager,
client,
EncryptionTestIT.publicKey,
EncryptionTestIT.certificate,
user,
targetContext,
arbitraryDataProvider
Expand Down
14 changes: 11 additions & 3 deletions app/src/main/java/com/nextcloud/utils/e2ee/E2EEActionResolver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ class E2EEActionResolver @Inject constructor(
storageManager.setReadOnly(file, true)
}

suspend fun setReadOnlyAndCanDecrypt(file: OCFile): Boolean = withContext(Dispatchers.IO) {
storageManager.setReadOnly(file, true)
val capability = storageManager.getCapability(accountManager.user.accountName)
return@withContext inspector.canDecryptFolderMetadata(file, capability)
}

suspend fun checkFolderMetadataKey(file: OCFile): Boolean = withContext(Dispatchers.IO) {
val capability = storageManager.getCapability(accountManager.user.accountName)
val canDecrypt = inspector.canDecryptFolderMetadata(file, capability)
Expand Down Expand Up @@ -75,13 +81,15 @@ class E2EEActionResolver @Inject constructor(
}

private suspend fun compareKeys(): E2EEKeyCheck {
val storedPublicKey = arbitraryDataProvider.getValue(accountManager.user, EncryptionUtils.PUBLIC_KEY)
val storedCertificate = arbitraryDataProvider.getValue(accountManager.user, EncryptionUtils.CERTIFICATE)

return when (val result = inspector.compareWithServerKey(storedPublicKey)) {
return when (val result = inspector.compareWithServerCertificate(storedCertificate)) {
is DownloadKeyResult.CompareKeys ->
if (result.same) E2EEKeyCheck.SAME_AS_SERVER else E2EEKeyCheck.DIFFERS_FROM_SERVER

is DownloadKeyResult.NoServerKey -> E2EEKeyCheck.ONLY_ON_DEVICE
is DownloadKeyResult.NoCertificateOnServer -> E2EEKeyCheck.ONLY_ON_DEVICE

is DownloadKeyResult.CertificateNotSignedByStoredServerKey -> E2EEKeyCheck.UNTRUSTED_CERTIFICATE

else -> E2EEKeyCheck.CHECK_FAILED
}
Expand Down
74 changes: 56 additions & 18 deletions app/src/main/java/com/nextcloud/utils/e2ee/E2EEKeyInspector.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ package com.nextcloud.utils.e2ee

import android.content.Context
import com.google.gson.reflect.TypeToken
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.owncloud.android.datamodel.ArbitraryDataProvider
import com.owncloud.android.datamodel.FileDataStorageManager
Expand All @@ -29,8 +30,10 @@ import com.owncloud.android.utils.EncryptionUtilsV2
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.apache.commons.httpclient.HttpStatus
import java.security.cert.CertificateException
import javax.inject.Inject

@Suppress("TooGenericExceptionCaught", "ReturnCount", "DEPRECATION")
class E2EEKeyInspector @Inject constructor(
private val context: Context,
private val storageManager: FileDataStorageManager,
Expand All @@ -44,7 +47,7 @@ class E2EEKeyInspector @Inject constructor(

fun isLocalKeysAbsent(): Boolean =
arbitraryDataProvider.getValue(accountManager.user, EncryptionUtils.PRIVATE_KEY).isEmpty() ||
arbitraryDataProvider.getValue(accountManager.user, EncryptionUtils.PUBLIC_KEY).isEmpty()
arbitraryDataProvider.getValue(accountManager.user, EncryptionUtils.CERTIFICATE).isEmpty()

suspend fun fetchCapabilities(): Boolean = withContext(Dispatchers.IO) {
val result = GetCapabilitiesOperation(storageManager).execute(context).isSuccess
Expand All @@ -56,30 +59,65 @@ class E2EEKeyInspector @Inject constructor(
return@withContext result
}

suspend fun compareWithServerKey(storedPublicKey: String): DownloadKeyResult = withContext(Dispatchers.IO) {
Log_OC.d(TAG, "comparing local public key with remote public key")
suspend fun compareWithServerCertificate(storedCertificate: String): DownloadKeyResult =
withContext(Dispatchers.IO) {
Log_OC.d(TAG, "comparing stored certificate against server certificate")

val user = accountManager.user
val user = accountManager.user

val certificateResult = GetCertificateRemoteOperation().executeNextcloudClient(user, context)
if (!certificateResult.isSuccess) {
return@withContext if (certificateResult.httpCode == HttpStatus.SC_NOT_FOUND) {
DownloadKeyResult.NoServerKey
} else {
DownloadKeyResult.CertificateUnavailable()
val certificateResult = GetCertificateRemoteOperation().executeNextcloudClient(user, context)
if (!certificateResult.isSuccess) {
return@withContext if (certificateResult.httpCode == HttpStatus.SC_NOT_FOUND) {
DownloadKeyResult.NoCertificateOnServer
} else {
DownloadKeyResult.CertificateUnavailable()
}
}

val remoteCertificate = certificateResult.resultData
val storedServerPublicKey = arbitraryDataProvider.getValue(user, EncryptionUtils.SERVER_PUBLIC_KEY)
if (storedServerPublicKey.isEmpty()) {
return@withContext fetchServerPublicKeyStoreAndCompare(user, storedCertificate, remoteCertificate)
}

val isSignedByStoredServerPublicKey = certificateValidator.validate(
serverPublicKeyString = storedServerPublicKey,
certificate = remoteCertificate
)
if (!isSignedByStoredServerPublicKey) {
Log_OC.w(TAG, "certificate cannot be verified with the stored server public key")
return@withContext DownloadKeyResult.CertificateNotSignedByStoredServerKey
}

return@withContext DownloadKeyResult.CompareKeys(
same = haveSamePublicKey(storedCertificate, remoteCertificate)
)
}

private fun fetchServerPublicKeyStoreAndCompare(
user: User,
storedCertificate: String,
remoteCertificate: String
): DownloadKeyResult {
val serverPublicKeyResult = GetServerPublicKeyRemoteOperation().executeNextcloudClient(user, context)
if (!serverPublicKeyResult.isSuccess) return@withContext DownloadKeyResult.ServerPublicKeyUnavailable()
if (!serverPublicKeyResult.isSuccess) return DownloadKeyResult.ServerPublicKeyUnavailable()

val isCertificateValid = certificateValidator.validate(
serverPublicKeyResult.resultData,
certificateResult.resultData
)
if (!isCertificateValid) return@withContext DownloadKeyResult.CertificateVerificationFailed()
val serverPublicKey = serverPublicKeyResult.resultData
if (!certificateValidator.validate(serverPublicKeyString = serverPublicKey, certificate = remoteCertificate)) {
return DownloadKeyResult.CertificateNotSignedByCurrentServerKey()
}

arbitraryDataProvider.storeOrUpdateKeyValue(user, EncryptionUtils.SERVER_PUBLIC_KEY, serverPublicKey)
return DownloadKeyResult.CompareKeys(same = haveSamePublicKey(storedCertificate, remoteCertificate))
}

return@withContext DownloadKeyResult.CompareKeys(same = (storedPublicKey == certificateResult.resultData))
private fun haveSamePublicKey(firstCertificate: String, secondCertificate: String): Boolean = try {
val firstPublicKey = EncryptionUtils.convertPublicKeyFromString(firstCertificate)
val secondPublicKey = EncryptionUtils.convertPublicKeyFromString(secondCertificate)
firstPublicKey.encoded.contentEquals(secondPublicKey.encoded)
} catch (e: CertificateException) {
Log_OC.w(TAG, "certificate could not be parsed: $e")
false
}

suspend fun canDecryptFolderMetadata(folder: OCFile, capability: OCCapability): Boolean =
Expand Down Expand Up @@ -122,7 +160,7 @@ class E2EEKeyInspector @Inject constructor(
context,
arbitraryDataProvider
)
!metadataKey.isEmpty()
metadataKey.isNotEmpty()
} catch (e: Exception) {
Log_OC.w(TAG, "user tried to decrypt folder's metadata with different private key: $e")
false
Expand Down
14 changes: 2 additions & 12 deletions app/src/main/java/com/nextcloud/utils/e2ee/model/E2EEDialog.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,9 @@ import androidx.annotation.StringRes
import com.owncloud.android.R

enum class E2EEDialog(@param:StringRes val titleId: Int, @param:StringRes val descriptionId: Int) {
KeysRevokedOrChangedWhenEncrypting(
KeysChangedOnServer(
titleId = R.string.encryption_key_handle_key_removed_title,
descriptionId = R.string.encryption_key_handle_setup_new_key_before_encrypting_description
),

KeysLocallyOutdated(
titleId = R.string.encryption_key_handle_key_removed_title,
descriptionId = R.string.encryption_key_handle_key_keys_only_on_device_outdated_description
),

KeysOnlyExistsOnDeviceWhenCreatingFolder(
titleId = R.string.encryption_key_handle_key_removed_title,
descriptionId = R.string.encryption_key_handle_key_keys_only_on_device_description
descriptionId = R.string.encryption_key_handle_keys_changed_on_server_description
),

KeysUnusableWhenOpeningFolder(
Expand Down
Loading
Loading