diff --git a/opencloudApp/src/main/java/eu/opencloud/android/presentation/settings/security/SettingsSecurityFragment.kt b/opencloudApp/src/main/java/eu/opencloud/android/presentation/settings/security/SettingsSecurityFragment.kt index 5f28b8f7b2..253bcc2a0c 100644 --- a/opencloudApp/src/main/java/eu/opencloud/android/presentation/settings/security/SettingsSecurityFragment.kt +++ b/opencloudApp/src/main/java/eu/opencloud/android/presentation/settings/security/SettingsSecurityFragment.kt @@ -24,6 +24,7 @@ import android.app.Activity import android.content.DialogInterface import android.content.Intent import android.os.Bundle +import android.security.KeyChain import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.preference.CheckBoxPreference @@ -56,6 +57,8 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { private var prefLockApplication: ListPreference? = null private var prefLockAccessDocumentProvider: CheckBoxPreference? = null private var prefTouchesWithOtherVisibleWindows: CheckBoxPreference? = null + private var prefMtls: CheckBoxPreference? = null + private var prefMtlsSelectCert: Preference? = null private val enablePasscodeLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> @@ -222,6 +225,66 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { } true } + + // mTLS client certificate + prefMtls = findPreference(SettingsSecurityViewModel.PREFERENCE_ENABLE_MTLS) + prefMtlsSelectCert = findPreference(SettingsSecurityViewModel.PREFERENCE_MTLS_SELECT_CERTIFICATE) + + updateMtlsCertSummary() + + prefMtls?.setOnPreferenceChangeListener { _: Preference?, newValue: Any -> + val enabled = newValue as Boolean + if (enabled && securityViewModel.getMtlsAlias() == null) { + // Optimistically allow the toggle, prompt for a cert, revert if cancelled. + launchKeyChainPicker { alias -> + if (alias != null) { + onMtlsCertPicked(alias) + } else { + prefMtls?.isChecked = false + } + } + } else if (!enabled) { + securityViewModel.clearMtlsAlias() + updateMtlsCertSummary() + securityViewModel.invalidateHttpClients() + } else { + securityViewModel.invalidateHttpClients() + } + true + } + + prefMtlsSelectCert?.setOnPreferenceClickListener { + launchKeyChainPicker { alias -> + // Null = user cancelled; preserve current selection. + if (alias != null) onMtlsCertPicked(alias) + } + true + } + } + + private fun onMtlsCertPicked(alias: String) { + securityViewModel.setMtlsAlias(alias) + showMessageInSnackbar(getString(R.string.prefs_mtls_cert_selected)) + updateMtlsCertSummary() + securityViewModel.invalidateHttpClients() + } + + private fun launchKeyChainPicker(onResult: (String?) -> Unit) { + val currentAlias = securityViewModel.getMtlsAlias() + KeyChain.choosePrivateKeyAlias( + requireActivity(), + { alias -> activity?.runOnUiThread { onResult(alias) } }, + null, null, null, KEYCHAIN_NO_PORT, currentAlias + ) + } + + private fun updateMtlsCertSummary() { + val alias = securityViewModel.getMtlsAlias() + prefMtlsSelectCert?.summary = if (alias != null) { + getString(R.string.prefs_mtls_select_cert_summary, alias) + } else { + getString(R.string.prefs_mtls_select_cert_summary_none) + } } private fun enableBiometricAndLockApplication() { @@ -246,5 +309,6 @@ class SettingsSecurityFragment : PreferenceFragmentCompat() { const val PREFERENCE_TOUCHES_WITH_OTHER_VISIBLE_WINDOWS = "touches_with_other_visible_windows" const val EXTRAS_LOCK_ENFORCED = "EXTRAS_LOCK_ENFORCED" const val PREFERENCE_LOCK_ATTEMPTS = "PrefLockAttempts" + private const val KEYCHAIN_NO_PORT = -1 } } diff --git a/opencloudApp/src/main/java/eu/opencloud/android/presentation/settings/security/SettingsSecurityViewModel.kt b/opencloudApp/src/main/java/eu/opencloud/android/presentation/settings/security/SettingsSecurityViewModel.kt index 103cd4e5ca..c2a2a3ed01 100644 --- a/opencloudApp/src/main/java/eu/opencloud/android/presentation/settings/security/SettingsSecurityViewModel.kt +++ b/opencloudApp/src/main/java/eu/opencloud/android/presentation/settings/security/SettingsSecurityViewModel.kt @@ -23,6 +23,8 @@ package eu.opencloud.android.presentation.settings.security import androidx.lifecycle.ViewModel import eu.opencloud.android.R import eu.opencloud.android.data.providers.SharedPreferencesProvider +import eu.opencloud.android.lib.common.SingleSessionManager +import eu.opencloud.android.lib.common.network.ClientCertificateManager import eu.opencloud.android.presentation.security.LockEnforcedType import eu.opencloud.android.presentation.security.LockEnforcedType.Companion.parseFromInteger import eu.opencloud.android.presentation.security.LockTimeout @@ -63,4 +65,22 @@ class SettingsSecurityViewModel( integerKey = R.integer.lock_delay_enforced ) ) != LockTimeout.DISABLED + + fun getMtlsAlias(): String? = + preferencesProvider.getString(ClientCertificateManager.PREF_MTLS_ALIAS, null) + + fun setMtlsAlias(alias: String) = + preferencesProvider.putString(ClientCertificateManager.PREF_MTLS_ALIAS, alias) + + fun clearMtlsAlias() = + preferencesProvider.removePreference(ClientCertificateManager.PREF_MTLS_ALIAS) + + fun invalidateHttpClients() { + SingleSessionManager.getDefaultSingleton().invalidateAllClients() + } + + companion object { + const val PREFERENCE_ENABLE_MTLS = ClientCertificateManager.PREF_MTLS_ENABLED + const val PREFERENCE_MTLS_SELECT_CERTIFICATE = "mtls_select_certificate" + } } diff --git a/opencloudApp/src/main/res/values/strings.xml b/opencloudApp/src/main/res/values/strings.xml index e867c95a7c..c30121b9c0 100644 --- a/opencloudApp/src/main/res/values/strings.xml +++ b/opencloudApp/src/main/res/values/strings.xml @@ -59,6 +59,13 @@ Lock access from other apps to the files of the accounts in the app via the Android native file explorer. Touches with other visible windows Allow touches when the view is obscured by another visible window. Enable it to use light filtering apps. + + mTLS client certificate + Present a client certificate for mutual TLS authentication + Select certificate + No certificate selected + Selected: %s + Client certificate selected Are you sure you want to enable this feature? Use this feature at your own risk. A malicious application could try to spoof you into unknowingly performing some actions, using other views. Automatic picture uploads diff --git a/opencloudApp/src/main/res/xml/settings_security.xml b/opencloudApp/src/main/res/xml/settings_security.xml index 91c72bb0dd..c5afe3d309 100644 --- a/opencloudApp/src/main/res/xml/settings_security.xml +++ b/opencloudApp/src/main/res/xml/settings_security.xml @@ -49,4 +49,16 @@ app:summary="@string/prefs_touches_with_other_visible_windows_summary" app:title="@string/prefs_touches_with_other_visible_windows" /> - \ No newline at end of file + + + + diff --git a/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/SingleSessionManager.java b/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/SingleSessionManager.java index 82a7f3dec8..1ca56536e8 100644 --- a/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/SingleSessionManager.java +++ b/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/SingleSessionManager.java @@ -205,6 +205,15 @@ public void removeClientFor(OpenCloudAccount account) { Timber.d("removeClientFor finishing "); } + public void invalidateAllClients() { + for (OpenCloudClient client : mClientsWithKnownUsername.values()) { + client.invalidate(); + } + for (OpenCloudClient client : mClientsWithUnknownUsername.values()) { + client.invalidate(); + } + } + public void refreshCredentialsForAccount(String accountName, OpenCloudCredentials credentials) { OpenCloudClient openCloudClient = mClientsWithKnownUsername.get(accountName); if (openCloudClient == null) { diff --git a/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/http/HttpClient.java b/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/http/HttpClient.java index ab8b711ed5..e6025854aa 100644 --- a/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/http/HttpClient.java +++ b/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/http/HttpClient.java @@ -28,6 +28,7 @@ import eu.opencloud.android.lib.common.http.logging.LogInterceptor; import eu.opencloud.android.lib.common.network.AdvancedX509TrustManager; +import eu.opencloud.android.lib.common.network.ClientCertificateManager; import eu.opencloud.android.lib.common.network.KnownServersHostnameVerifier; import eu.opencloud.android.lib.common.network.NetworkUtils; import okhttp3.Cookie; @@ -38,6 +39,7 @@ import okhttp3.TlsVersion; import timber.log.Timber; +import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; @@ -69,14 +71,16 @@ protected HttpClient(Context context) { mContext = context; } - public OkHttpClient getOkHttpClient() { + public synchronized OkHttpClient getOkHttpClient() { if (mOkHttpClient == null) { try { final X509TrustManager trustManager = new AdvancedX509TrustManager( NetworkUtils.getKnownServersStore(mContext)); final SSLContext sslContext = buildSSLContext(); - sslContext.init(null, new TrustManager[]{trustManager}, null); + + KeyManager[] keyManagers = ClientCertificateManager.INSTANCE.getKeyManagers(mContext); + sslContext.init(keyManagers, new TrustManager[]{trustManager}, null); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); // Automatic cookie handling, NOT PERSISTENT @@ -94,6 +98,10 @@ public OkHttpClient getOkHttpClient() { return mOkHttpClient; } + public synchronized void invalidate() { + mOkHttpClient = null; + } + private SSLContext buildSSLContext() throws NoSuchAlgorithmException { try { return SSLContext.getInstance(TlsVersion.TLS_1_3.javaName()); diff --git a/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/network/ClientCertificateManager.kt b/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/network/ClientCertificateManager.kt new file mode 100644 index 0000000000..c71a847f9f --- /dev/null +++ b/opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/network/ClientCertificateManager.kt @@ -0,0 +1,90 @@ +/* openCloud Android Library is available under MIT license + * Copyright (C) 2026 openCloud GmbH. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package eu.opencloud.android.lib.common.network + +import android.content.Context +import android.content.SharedPreferences +import android.preference.PreferenceManager +import android.security.KeyChain +import timber.log.Timber +import java.net.Socket +import java.security.Principal +import java.security.PrivateKey +import java.security.cert.X509Certificate +import javax.net.ssl.KeyManager +import javax.net.ssl.X509KeyManager + +object ClientCertificateManager { + + const val PREF_MTLS_ENABLED = "enable_mtls" + const val PREF_MTLS_ALIAS = "mtls_cert_alias" + + fun getAlias(context: Context): String? = + prefs(context).getString(PREF_MTLS_ALIAS, null) + + fun setAlias(context: Context, alias: String) { + prefs(context).edit().putString(PREF_MTLS_ALIAS, alias).apply() + } + + fun clearAlias(context: Context) { + prefs(context).edit().remove(PREF_MTLS_ALIAS).apply() + } + + fun isMtlsEnabled(context: Context): Boolean = + prefs(context).getBoolean(PREF_MTLS_ENABLED, false) + + fun getKeyManagers(context: Context): Array? { + if (!isMtlsEnabled(context)) return null + val alias = getAlias(context) ?: return null + return arrayOf(KeyChainKeyManager(context.applicationContext, alias)) + } + + private fun prefs(context: Context): SharedPreferences = + PreferenceManager.getDefaultSharedPreferences(context) + + private class KeyChainKeyManager( + private val appContext: Context, + private val alias: String, + ) : X509KeyManager { + + override fun chooseClientAlias(keyType: Array?, issuers: Array?, socket: Socket?): String = alias + + override fun getClientAliases(keyType: String?, issuers: Array?): Array = arrayOf(alias) + + override fun getCertificateChain(alias: String?): Array? = + runCatching { KeyChain.getCertificateChain(appContext, this.alias) } + .onFailure { Timber.e(it, "Failed to get certificate chain for alias: %s", this.alias) } + .getOrNull() + + override fun getPrivateKey(alias: String?): PrivateKey? = + runCatching { KeyChain.getPrivateKey(appContext, this.alias) } + .onFailure { Timber.e(it, "Failed to get private key for alias: %s", this.alias) } + .getOrNull() + + override fun chooseServerAlias(keyType: String?, issuers: Array?, socket: Socket?): String? = null + + override fun getServerAliases(keyType: String?, issuers: Array?): Array? = null + } +}