Skip to content
Closed
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 @@ -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
Expand Down Expand Up @@ -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 ->
Expand Down Expand Up @@ -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() {
Expand All @@ -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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
}
}
7 changes: 7 additions & 0 deletions opencloudApp/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@
<string name="prefs_lock_access_from_document_provider_summary">Lock access from other apps to the files of the accounts in the app via the Android native file explorer.</string>
<string name="prefs_touches_with_other_visible_windows">Touches with other visible windows</string>
<string name="prefs_touches_with_other_visible_windows_summary">Allow touches when the view is obscured by another visible window. Enable it to use light filtering apps.</string>

<string name="prefs_mtls">mTLS client certificate</string>
<string name="prefs_mtls_summary">Present a client certificate for mutual TLS authentication</string>
<string name="prefs_mtls_select_cert">Select certificate</string>
<string name="prefs_mtls_select_cert_summary_none">No certificate selected</string>
<string name="prefs_mtls_select_cert_summary">Selected: %s</string>
<string name="prefs_mtls_cert_selected">Client certificate selected</string>
<string name="confirmation_touches_with_other_windows_title">Are you sure you want to enable this feature?</string>
<string name="confirmation_touches_with_other_windows_message">Use this feature at your own risk. A malicious application could try to spoof you into unknowingly performing some actions, using other views.</string>
<string name="prefs_subsection_picture_uploads">Automatic picture uploads</string>
Expand Down
14 changes: 13 additions & 1 deletion opencloudApp/src/main/res/xml/settings_security.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,16 @@
app:summary="@string/prefs_touches_with_other_visible_windows_summary"
app:title="@string/prefs_touches_with_other_visible_windows" />

</PreferenceScreen>
<CheckBoxPreference
app:iconSpaceReserved="false"
app:key="enable_mtls"
app:summary="@string/prefs_mtls_summary"
app:title="@string/prefs_mtls" />
<Preference
app:dependency="enable_mtls"
app:iconSpaceReserved="false"
app:key="mtls_select_certificate"
app:summary="@string/prefs_mtls_select_cert_summary_none"
app:title="@string/prefs_mtls_select_cert" />

</PreferenceScreen>
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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());
Expand Down
Original file line number Diff line number Diff line change
@@ -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<KeyManager>? {
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<String>?, issuers: Array<Principal>?, socket: Socket?): String = alias

override fun getClientAliases(keyType: String?, issuers: Array<Principal>?): Array<String> = arrayOf(alias)

override fun getCertificateChain(alias: String?): Array<X509Certificate>? =
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<Principal>?, socket: Socket?): String? = null

override fun getServerAliases(keyType: String?, issuers: Array<Principal>?): Array<String>? = null
}
}