From 1ee2a9c27955b49d5d8c5ebc981726305deebcc8 Mon Sep 17 00:00:00 2001 From: Paolo Stivanin Date: Tue, 10 Mar 2026 15:35:11 +0100 Subject: [PATCH 1/2] Security: Add mTLS client certificate support Allow users to present a client certificate for mutual TLS authentication (e.g. Cloudflare mTLS). Uses Android KeyChain API so users pick from certificates already installed on device. --- .../security/SettingsSecurityFragment.kt | 64 +++++++++++++ .../security/SettingsSecurityViewModel.kt | 20 +++++ opencloudApp/src/main/res/values/strings.xml | 7 ++ .../src/main/res/xml/settings_security.xml | 14 ++- .../lib/common/SingleSessionManager.java | 9 ++ .../android/lib/common/http/HttpClient.java | 12 ++- .../network/ClientCertificateManager.kt | 90 +++++++++++++++++++ 7 files changed, 213 insertions(+), 3 deletions(-) create mode 100644 opencloudComLibrary/src/main/java/eu/opencloud/android/lib/common/network/ClientCertificateManager.kt 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 + } +} From de6f1763074a591e74b2e93e475d11aff489bd5e Mon Sep 17 00:00:00 2001 From: Paolo Stivanin Date: Wed, 24 Jun 2026 17:03:28 +0200 Subject: [PATCH 2/2] Security: Make mTLS client certificates per-account Previously the client certificate for mutual TLS was a single global setting applied to every account and host. Make it per-account instead: - Store the certificate alias in the account's AccountManager userData (auto-removed with the account) - Resolve and present it per OpenCloudClient when the account is bound, re-resolved on each request so a change is picked up immediately - Choose the certificate at login time via the Android KeyChain picker so servers gated behind mTLS can be reached for the initial server-check/login, before the account exists - Manage (set / change / remove) the certificate per account from the Manage Accounts dialog - Evict idle connections on change so the new certificate takes effect Removes the now-redundant global mTLS toggle from Settings > Security. --- .../accounts/ManageAccountsAdapter.kt | 6 ++ .../accounts/ManageAccountsDialogFragment.kt | 65 +++++++++++++++++ .../authentication/LoginActivity.kt | 71 +++++++++++++++++++ .../security/SettingsSecurityFragment.kt | 64 ----------------- .../security/SettingsSecurityViewModel.kt | 20 ------ .../main/res/layout-land/account_setup.xml | 22 ++++++ .../src/main/res/layout/account_item.xml | 22 +++++- .../src/main/res/layout/account_setup.xml | 22 ++++++ opencloudApp/src/main/res/values/strings.xml | 14 ++-- .../src/main/res/xml/settings_security.xml | 12 ---- .../lib/common/SingleSessionManager.java | 6 ++ .../lib/common/accounts/AccountUtils.java | 21 ++++++ .../android/lib/common/http/HttpClient.java | 22 +++++- .../network/ClientCertificateManager.kt | 36 +++------- .../opencloud/android/data/ClientManager.kt | 7 ++ 15 files changed, 280 insertions(+), 130 deletions(-) diff --git a/opencloudApp/src/main/java/eu/opencloud/android/presentation/accounts/ManageAccountsAdapter.kt b/opencloudApp/src/main/java/eu/opencloud/android/presentation/accounts/ManageAccountsAdapter.kt index 3327ef4443..4aa327c085 100644 --- a/opencloudApp/src/main/java/eu/opencloud/android/presentation/accounts/ManageAccountsAdapter.kt +++ b/opencloudApp/src/main/java/eu/opencloud/android/presentation/accounts/ManageAccountsAdapter.kt @@ -135,6 +135,11 @@ class ManageAccountsAdapter( setImageResource(R.drawable.ic_clean_account) setOnClickListener { accountListener.cleanAccountLocalStorage(account) } } + /// bind listener to manage the client certificate (mTLS) of the account + holder.binding.mtlsAccountButton.apply { + setImageResource(R.drawable.ic_lock) + setOnClickListener { accountListener.manageClientCertificate(account, it) } + } /// bind listener to remove account holder.binding.removeButton.apply { setImageResource(R.drawable.ic_action_delete_grey) @@ -240,6 +245,7 @@ class ManageAccountsAdapter( fun cleanAccountLocalStorage(account: Account) fun createAccount() fun switchAccount(position: Int) + fun manageClientCertificate(account: Account, anchor: View) } } diff --git a/opencloudApp/src/main/java/eu/opencloud/android/presentation/accounts/ManageAccountsDialogFragment.kt b/opencloudApp/src/main/java/eu/opencloud/android/presentation/accounts/ManageAccountsDialogFragment.kt index 6bc7a06546..d471b22b20 100644 --- a/opencloudApp/src/main/java/eu/opencloud/android/presentation/accounts/ManageAccountsDialogFragment.kt +++ b/opencloudApp/src/main/java/eu/opencloud/android/presentation/accounts/ManageAccountsDialogFragment.kt @@ -29,11 +29,14 @@ import android.app.AlertDialog import android.app.Dialog import android.content.Intent import android.os.Bundle +import android.security.KeyChain import android.view.ContextThemeWrapper import android.view.View import android.widget.ImageView import android.widget.LinearLayout +import android.widget.PopupMenu import android.widget.ProgressBar +import android.widget.Toast import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.LinearLayoutManager @@ -44,6 +47,8 @@ import eu.opencloud.android.domain.user.model.UserQuota import eu.opencloud.android.extensions.avoidScreenshotsIfNeeded import eu.opencloud.android.extensions.collectLatestLifecycleFlow import eu.opencloud.android.extensions.showErrorInSnackbar +import eu.opencloud.android.lib.common.SingleSessionManager +import eu.opencloud.android.lib.common.accounts.AccountUtils as LibAccountUtils import eu.opencloud.android.presentation.authentication.AccountUtils import eu.opencloud.android.presentation.common.UIResult import eu.opencloud.android.ui.activity.FileActivity @@ -145,6 +150,60 @@ class ManageAccountsDialogFragment : DialogFragment(), ManageAccountsAdapter.Acc dialog.show() } + /** + * Lets the user set, change or remove the client certificate (mTLS) presented for [account]. + * The chosen alias is stored in the account's userData and the cached HTTP clients are + * invalidated so the next request uses the updated certificate. + */ + override fun manageClientCertificate(account: Account, anchor: View) { + val hasCert = !LibAccountUtils.getClientCertAliasForAccount(requireContext(), account).isNullOrBlank() + PopupMenu(requireContext(), anchor).apply { + menu.add(0, MENU_SET_CERT, 0, getString(R.string.account_mtls_set_cert)) + if (hasCert) { + menu.add(0, MENU_CLEAR_CERT, 1, getString(R.string.account_mtls_clear_cert)) + } + setOnMenuItemClickListener { item -> + when (item.itemId) { + MENU_SET_CERT -> { + launchClientCertPicker(account) + true + } + MENU_CLEAR_CERT -> { + setAccountClientCertAlias(account, null) + true + } + else -> { + false + } + } + } + show() + } + } + + private fun launchClientCertPicker(account: Account) { + val currentAlias = LibAccountUtils.getClientCertAliasForAccount(requireContext(), account) + KeyChain.choosePrivateKeyAlias( + requireActivity(), + // Null = user cancelled; preserve the current selection. + { alias -> activity?.runOnUiThread { alias?.let { setAccountClientCertAlias(account, it) } } }, + null, null, null, KEYCHAIN_NO_PORT, currentAlias + ) + } + + private fun setAccountClientCertAlias(account: Account, alias: String?) { + AccountManager.get(requireContext().applicationContext) + .setUserData(account, LibAccountUtils.Constants.KEY_MTLS_CERT_ALIAS, alias?.takeIf { it.isNotBlank() }) + // Drop cached clients so the next request renegotiates TLS with the updated certificate. + SingleSessionManager.getDefaultSingleton().invalidateAllClients() + val message = if (alias.isNullOrBlank()) { + getString(R.string.account_mtls_cert_cleared) + } else { + getString(R.string.account_mtls_cert_selected, alias) + } + Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show() + } + override fun createAccount() { val accountManager = AccountManager.get(MainApp.appContext) accountManager.addAccount( @@ -277,6 +336,12 @@ class ManageAccountsDialogFragment : DialogFragment(), ManageAccountsAdapter.Acc const val MANAGE_ACCOUNTS_DIALOG = "MANAGE_ACCOUNTS_DIALOG" const val KEY_CURRENT_ACCOUNT = "KEY_CURRENT_ACCOUNT" + private const val MENU_SET_CERT = 1 + private const val MENU_CLEAR_CERT = 2 + + // KeyChain.choosePrivateKeyAlias: -1 means no port constraint on the host hint. + private const val KEYCHAIN_NO_PORT = -1 + fun newInstance(currentAccount: Account?): ManageAccountsDialogFragment { val args = Bundle().apply { putParcelable(KEY_CURRENT_ACCOUNT, currentAccount) diff --git a/opencloudApp/src/main/java/eu/opencloud/android/presentation/authentication/LoginActivity.kt b/opencloudApp/src/main/java/eu/opencloud/android/presentation/authentication/LoginActivity.kt index ea440310d9..f470fa426d 100644 --- a/opencloudApp/src/main/java/eu/opencloud/android/presentation/authentication/LoginActivity.kt +++ b/opencloudApp/src/main/java/eu/opencloud/android/presentation/authentication/LoginActivity.kt @@ -38,6 +38,7 @@ import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle +import android.security.KeyChain import android.view.View.INVISIBLE import android.view.WindowManager.LayoutParams.FLAG_SECURE import androidx.appcompat.app.AppCompatActivity @@ -49,6 +50,7 @@ import androidx.core.widget.doAfterTextChanged import eu.opencloud.android.BuildConfig import eu.opencloud.android.MainApp.Companion.accountType import eu.opencloud.android.R +import eu.opencloud.android.data.ClientManager import eu.opencloud.android.data.authentication.KEY_OIDC_ISSUER import eu.opencloud.android.data.authentication.KEY_PREFERRED_USERNAME import eu.opencloud.android.data.authentication.KEY_USER_ID @@ -107,12 +109,20 @@ private const val KEY_AUTH_SERVER_BASE_URL = "KEY_AUTH_SERVER_BASE_URL" private const val KEY_AUTH_OIDC_SUPPORTED = "KEY_AUTH_OIDC_SUPPORTED" private const val KEY_AUTH_LOGIN_ACTION = "KEY_AUTH_LOGIN_ACTION" private const val KEY_AUTH_USER_ACCOUNT = "KEY_AUTH_USER_ACCOUNT" +private const val KEY_AUTH_MTLS_CERT_ALIAS = "KEY_AUTH_MTLS_CERT_ALIAS" + +// KeyChain.choosePrivateKeyAlias: -1 means no port constraint on the host hint. +private const val KEYCHAIN_NO_PORT = -1 class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrustedCertListener, SecurityEnforced { private val authenticationViewModel by viewModel() private val contextProvider by inject() private val mdmProvider by inject() + private val clientManager by inject() + + // Alias (from the Android KeyChain) of the client certificate to present for mTLS during login. + private var clientCertAlias: String? = null private var loginAction: Byte = ACTION_CREATE private var authTokenType: String? = null @@ -213,12 +223,16 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted binding.root.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(this@LoginActivity) + restoreClientCertAlias(savedInstanceState) + initBrandableOptionsUI() binding.thumbnail.setOnClickListener { checkOcServer() } binding.embeddedCheckServerButton.setOnClickListener { checkOcServer() } + binding.mtlsSelectCertButton.setOnClickListener { launchClientCertPicker() } + binding.loginButton.setOnClickListener { if (AccountTypeUtils.getAuthTokenTypeAccessToken(accountType) != authTokenType) { // Basic authenticationViewModel.loginBasic( @@ -258,6 +272,24 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted // getServerInfo() completes (process death recovery flow). } + /** + * Restores the mTLS client certificate alias: from saved state on recreate, from the existing + * account on re-login, or none on a fresh login. Keeps [clientManager]'s transient alias in sync + * so the login connection (server check + login) presents the right certificate before the + * account exists. + */ + private fun restoreClientCertAlias(savedInstanceState: Bundle?) { + clientCertAlias = when { + savedInstanceState != null -> savedInstanceState.getString(KEY_AUTH_MTLS_CERT_ALIAS) + loginAction != ACTION_CREATE -> userAccount?.let { + AccountManager.get(this).getUserData(it, AccountUtils.Constants.KEY_MTLS_CERT_ALIAS) + } + else -> null + } + clientManager.loginClientCertAlias = clientCertAlias + updateClientCertStatus() + } + /** * If this onCreate is an OAuth redirect, either forward it to the existing instance * (when not task root) or let it proceed. Otherwise, track this instance so the @@ -626,6 +658,11 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted am.setUserData(account, KEY_OIDC_ISSUER, serverInfo.oidcServerConfiguration.issuer) } + // Persist the mTLS client certificate chosen during login to the account, then clear the + // login-time transient so it does not leak into later anonymous clients. + am.setUserData(account, AccountUtils.Constants.KEY_MTLS_CERT_ALIAS, clientCertAlias?.takeIf { it.isNotBlank() }) + clientManager.loginClientCertAlias = null + authenticationViewModel.discoverAccount(accountName = accountName, discoveryNeeded = loginAction == ACTION_CREATE) clearAuthState() } @@ -1084,6 +1121,39 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted } } + /** + * Opens the Android KeyChain picker so the user can choose a client certificate for mTLS, + * defaulting to the currently selected alias. The chosen alias is applied to the login client + * immediately so the next server check / login presents it. + */ + private fun launchClientCertPicker() { + KeyChain.choosePrivateKeyAlias( + this, + { alias -> runOnUiThread { onClientCertPicked(alias) } }, + null, null, null, KEYCHAIN_NO_PORT, clientCertAlias + ) + } + + private fun onClientCertPicked(alias: String?) { + // Null = user cancelled the picker; keep the current selection. + if (alias == null) return + clientCertAlias = alias + clientManager.loginClientCertAlias = alias + updateClientCertStatus() + } + + private fun updateClientCertStatus() { + binding.mtlsStatusText.run { + val alias = clientCertAlias + if (alias.isNullOrBlank()) { + isVisible = false + } else { + text = getString(R.string.auth_mtls_cert_selected, alias) + isVisible = true + } + } + } + override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(KEY_AUTH_TOKEN_TYPE, authTokenType) @@ -1094,6 +1164,7 @@ class LoginActivity : AppCompatActivity(), SslUntrustedCertDialog.OnSslUntrusted outState.putString(KEY_CODE_VERIFIER, authenticationViewModel.codeVerifier) outState.putString(KEY_CODE_CHALLENGE, authenticationViewModel.codeChallenge) outState.putString(KEY_OIDC_STATE, authenticationViewModel.oidcState) + outState.putString(KEY_AUTH_MTLS_CERT_ALIAS, clientCertAlias) } override fun finish() { 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 253bcc2a0c..5f28b8f7b2 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,7 +24,6 @@ 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 @@ -57,8 +56,6 @@ 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 -> @@ -225,66 +222,6 @@ 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() { @@ -309,6 +246,5 @@ 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 c2a2a3ed01..103cd4e5ca 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,8 +23,6 @@ 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 @@ -65,22 +63,4 @@ 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/layout-land/account_setup.xml b/opencloudApp/src/main/res/layout-land/account_setup.xml index 81c7251221..0dc6fa824a 100644 --- a/opencloudApp/src/main/res/layout-land/account_setup.xml +++ b/opencloudApp/src/main/res/layout-land/account_setup.xml @@ -200,6 +200,28 @@ android:visibility="gone" /> +