Skip to content
Open
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 @@ -11,6 +11,7 @@ import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.account.UserAccountManagerImpl
import com.nextcloud.client.database.entity.FileEntity
import com.nextcloud.client.network.NetworkModule
import com.nextcloud.repository.ClientRepository
import com.nextcloud.test.SinceServer
import com.nextcloud.utils.e2ee.E2EEActionResolver
import com.nextcloud.utils.e2ee.E2EEKeyInspector
Expand All @@ -33,6 +34,7 @@ import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.mock

@SinceServer(majorVersion = 30)
open class EncryptedFoldersIT : AbstractOnServerIT() {
Expand Down Expand Up @@ -61,12 +63,17 @@ open class EncryptedFoldersIT : AbstractOnServerIT() {

init {
val accountManager: UserAccountManager = UserAccountManagerImpl.fromContext(targetContext)
val clientRepository: ClientRepository = mock {
onBlocking { getOwncloudClient() }.thenReturn(client)
onBlocking { getNextcloudClient() }.thenReturn(nextcloudClient)
}
val inspector = E2EEKeyInspector(
targetContext,
storageManager,
CertificateValidator(),
arbitraryDataProvider,
accountManager
accountManager,
clientRepository
)
e2eeActionResolver = E2EEActionResolver(
storageManager,
Expand Down
6 changes: 4 additions & 2 deletions app/src/main/java/com/nextcloud/client/di/AppModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -239,13 +239,15 @@ internal class AppModule {
fileDataStorageManager: FileDataStorageManager,
certificateValidator: CertificateValidator,
arbitraryDataProvider: ArbitraryDataProvider,
accountManager: UserAccountManager
accountManager: UserAccountManager,
clientRepository: ClientRepository
): E2EEKeyInspector = E2EEKeyInspector(
context,
fileDataStorageManager,
certificateValidator,
arbitraryDataProvider,
accountManager
accountManager,
clientRepository
)

@Provides
Expand Down
27 changes: 19 additions & 8 deletions app/src/main/java/com/nextcloud/utils/e2ee/E2EEKeyInspector.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ import android.content.Context
import com.google.gson.reflect.TypeToken
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.repository.ClientRepository
import com.owncloud.android.datamodel.ArbitraryDataProvider
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.e2e.v1.encrypted.EncryptedFolderMetadataFileV1
import com.owncloud.android.lib.common.OwnCloudClient
import com.owncloud.android.lib.common.OwnCloudClientFactory
import com.nextcloud.common.NextcloudClient
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.lib.resources.e2ee.GetMetadataRemoteOperation
import com.owncloud.android.lib.resources.status.OCCapability
Expand All @@ -39,7 +40,8 @@ class E2EEKeyInspector @Inject constructor(
private val storageManager: FileDataStorageManager,
private val certificateValidator: CertificateValidator,
private val arbitraryDataProvider: ArbitraryDataProvider,
private val accountManager: UserAccountManager
private val accountManager: UserAccountManager,
private val clientRepository: ClientRepository
) {
companion object {
private const val TAG = "E2EEKeyInspector"
Expand All @@ -50,7 +52,8 @@ class E2EEKeyInspector @Inject constructor(
arbitraryDataProvider.getValue(accountManager.user, EncryptionUtils.CERTIFICATE).isEmpty()

suspend fun fetchCapabilities(): Boolean = withContext(Dispatchers.IO) {
val result = GetCapabilitiesOperation(storageManager).execute(context).isSuccess
val client = clientRepository.getOwncloudClient() ?: return@withContext false
val result = GetCapabilitiesOperation(storageManager).execute(client).isSuccess
if (result) {
Log_OC.i(TAG, "capabilities fetched")
} else {
Expand All @@ -65,7 +68,9 @@ class E2EEKeyInspector @Inject constructor(

val user = accountManager.user

val certificateResult = GetCertificateRemoteOperation().executeNextcloudClient(user, context)
val client = clientRepository.getNextcloudClient()
?: return@withContext DownloadKeyResult.UnexpectedError()
val certificateResult = GetCertificateRemoteOperation().execute(client)
if (!certificateResult.isSuccess) {
return@withContext if (certificateResult.httpCode == HttpStatus.SC_NOT_FOUND) {
DownloadKeyResult.NoCertificateOnServer
Expand All @@ -77,7 +82,12 @@ class E2EEKeyInspector @Inject constructor(
val remoteCertificate = certificateResult.resultData
val storedServerPublicKey = arbitraryDataProvider.getValue(user, EncryptionUtils.SERVER_PUBLIC_KEY)
if (storedServerPublicKey.isEmpty()) {
return@withContext fetchServerPublicKeyStoreAndCompare(user, storedCertificate, remoteCertificate)
return@withContext fetchServerPublicKeyStoreAndCompare(
user,
storedCertificate,
remoteCertificate,
client
)
}

val isSignedByStoredServerPublicKey = certificateValidator.validate(
Expand All @@ -97,9 +107,10 @@ class E2EEKeyInspector @Inject constructor(
private fun fetchServerPublicKeyStoreAndCompare(
user: User,
storedCertificate: String,
remoteCertificate: String
remoteCertificate: String,
client: NextcloudClient
): DownloadKeyResult {
val serverPublicKeyResult = GetServerPublicKeyRemoteOperation().executeNextcloudClient(user, context)
val serverPublicKeyResult = GetServerPublicKeyRemoteOperation().execute(client)
if (!serverPublicKeyResult.isSuccess) return DownloadKeyResult.ServerPublicKeyUnavailable()

val serverPublicKey = serverPublicKeyResult.resultData
Expand All @@ -124,7 +135,7 @@ class E2EEKeyInspector @Inject constructor(
withContext(Dispatchers.IO) {
Log_OC.d(TAG, "checking folder metadata key")

val client = OwnCloudClientFactory.createOwnCloudClient(accountManager.currentAccount, context)
val client = clientRepository.getOwncloudClient() ?: return@withContext false
val metadataResult = GetMetadataRemoteOperation(folder.localId).execute(client)

if (!metadataResult.isSuccess) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

package com.nextcloud.utils.e2ee

import org.bouncycastle.asn1.ASN1ObjectIdentifier
import org.bouncycastle.asn1.x500.X500Name
import org.bouncycastle.asn1.x509.AlgorithmIdentifier
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder
import org.bouncycastle.operator.ContentSigner
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
import java.math.BigInteger
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.util.Base64
import java.util.Date

internal object CertificateTestFixtures {
const val DAY_MILLIS = 86_400_000L
private const val KEY_SIZE = 2048
private const val PEM_LINE_LENGTH = 64
private const val UNKNOWN_ALGORITHM_OID = "1.2.3.4.5"

val serverKeys: KeyPair by lazy { generateKeyPair() }
val userKeys: KeyPair by lazy { generateKeyPair() }
val otherKeys: KeyPair by lazy { generateKeyPair() }

fun certificate(
keys: KeyPair = userKeys,
serial: Long = 1,
notBefore: Long = System.currentTimeMillis() - DAY_MILLIS,
notAfter: Long = System.currentTimeMillis() + DAY_MILLIS,
unsupportedAlgorithm: Boolean = false
): String {
val builder = JcaX509v3CertificateBuilder(
X500Name("CN=Encryption server"),
BigInteger.valueOf(serial),
Date(notBefore),
Date(notAfter),
X500Name("CN=Encryption user"),
keys.public
)
val signer = JcaContentSignerBuilder("SHA256withRSA").build(serverKeys.private)
val contentSigner = if (unsupportedAlgorithm) {
object : ContentSigner by signer {
override fun getAlgorithmIdentifier(): AlgorithmIdentifier =
AlgorithmIdentifier(ASN1ObjectIdentifier(UNKNOWN_ALGORITHM_OID))
}
} else {
signer
}
return pem("CERTIFICATE", builder.build(contentSigner).encoded)
}

fun publicKey(keys: KeyPair = serverKeys): String = pem("PUBLIC KEY", keys.public.encoded)

fun privateKey(keys: KeyPair = userKeys): String = Base64.getEncoder().encodeToString(keys.private.encoded)

fun pem(label: String, bytes: ByteArray): String {
val body = Base64.getMimeEncoder(PEM_LINE_LENGTH, "\n".toByteArray()).encodeToString(bytes)
return "-----BEGIN $label-----\n$body\n-----END $label-----\n"
}

private fun generateKeyPair(): KeyPair = KeyPairGenerator.getInstance("RSA").apply {
initialize(KEY_SIZE)
}.generateKeyPair()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

package com.nextcloud.utils.e2ee

import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.owncloud.android.datamodel.ArbitraryDataProvider
import com.owncloud.android.utils.EncryptionUtils
import com.nextcloud.common.NextcloudClient
import com.nextcloud.repository.ClientRepository
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode
import com.owncloud.android.lib.resources.users.GetCertificateRemoteOperation
import com.owncloud.android.lib.resources.users.GetServerPublicKeyRemoteOperation
import com.owncloud.android.ui.dialog.setupEncryption.CertificateValidator
import com.owncloud.android.ui.dialog.setupEncryption.model.DownloadKeyResult
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.mockConstruction
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever

class E2EEKeyInspectorServerKeyTest {
@Test
fun repeatedEntryFetchesCertificateAndVerifiesItWhileSharingServerKeyAcrossInspectors() = runTest {
withContext(Dispatchers.IO) {
val client: NextcloudClient = mock()
val repository: ClientRepository = mock { onBlocking { getNextcloudClient() } doReturn client }
val validator: CertificateValidator = mock()
whenever(validator.validate(SERVER_KEY, CERTIFICATE)).thenReturn(true)
val user: User = mock()
val accounts: UserAccountManager = mock { on { this.user } doReturn user }
var storedServerKey = ""
val provider: ArbitraryDataProvider = mock()
whenever(provider.getValue(user, EncryptionUtils.SERVER_PUBLIC_KEY)).thenAnswer { storedServerKey }
doAnswer { invocation ->
storedServerKey = invocation.getArgument(2)
null
}.whenever(provider).storeOrUpdateKeyValue(user, EncryptionUtils.SERVER_PUBLIC_KEY, SERVER_KEY)
val certificateResult = RemoteOperationResult<String>(ResultCode.OK).apply { resultData = CERTIFICATE }
val serverKeyResult = RemoteOperationResult<String>(ResultCode.OK).apply { resultData = SERVER_KEY }

mockConstruction(GetCertificateRemoteOperation::class.java) { operation, _ ->
whenever(operation.execute(client)).thenReturn(certificateResult)
}.use { certificates ->
mockConstruction(GetServerPublicKeyRemoteOperation::class.java) { operation, _ ->
whenever(operation.execute(client)).thenReturn(serverKeyResult)
}.use { serverKeys ->
repeat(ENTRIES) {
val inspector = E2EEKeyInspector(mock(), mock(), validator, provider, accounts, repository)
assertEquals(
DownloadKeyResult.CompareKeys(true),
inspector.compareWithServerCertificate(CERTIFICATE)
)
}
assertEquals(ENTRIES, certificates.constructed().size)
assertEquals(1, serverKeys.constructed().size)
}
}
verify(validator, times(ENTRIES)).validate(SERVER_KEY, CERTIFICATE)
}
}

companion object {
private const val SERVER_KEY = "server-key"
private val CERTIFICATE = CertificateTestFixtures.certificate()
private const val ENTRIES = 10
}
}