-
-
Notifications
You must be signed in to change notification settings - Fork 112
Cache SSLSocketFactories to allow okhttp HTTPS connection reuse #1942
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+423
−74
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
a144180
Reuse CustomCertManager
rfc2822 ee57967
Implement connection security manager for HTTP client
rfc2822 256b338
[WIP] Cache SSLContext by certificate alias
rfc2822 218559a
Update comments in HttpClientBuilder.kt for clarity
rfc2822 647be71
Update ConnectionSecurityManager to use SSLSocketFactory caching
rfc2822 d642b6e
Refactor socket factory caching logic for better clarity
rfc2822 fa99d03
Add tests
rfc2822 eacfde0
Refactor socket factory cache to store only SSLSocketFactory
rfc2822 c37781e
Minor changes
rfc2822 a7b2b79
Add tests for caching
rfc2822 f244920
Add logging
rfc2822 fa3f892
Indenting
rfc2822 386c189
Minor simplification
rfc2822 57f7652
Fix tests
rfc2822 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
64 changes: 64 additions & 0 deletions
64
app/src/main/kotlin/at/bitfire/davdroid/di/CustomCertManagerModule.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| /* | ||
| * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. | ||
| */ | ||
|
|
||
| package at.bitfire.davdroid.di | ||
|
|
||
| import android.content.Context | ||
| import at.bitfire.cert4android.CustomCertManager | ||
| import at.bitfire.cert4android.CustomCertStore | ||
| import at.bitfire.cert4android.SettingsProvider | ||
| import at.bitfire.davdroid.BuildConfig | ||
| import at.bitfire.davdroid.settings.Settings | ||
| import at.bitfire.davdroid.settings.SettingsManager | ||
| import at.bitfire.davdroid.ui.ForegroundTracker | ||
| import dagger.Module | ||
| import dagger.Provides | ||
| import dagger.hilt.InstallIn | ||
| import dagger.hilt.android.qualifiers.ApplicationContext | ||
| import dagger.hilt.components.SingletonComponent | ||
| import okhttp3.internal.tls.OkHostnameVerifier | ||
| import java.util.Optional | ||
| import javax.inject.Singleton | ||
|
|
||
| @Module | ||
| @InstallIn(SingletonComponent::class) | ||
| /** | ||
| * cert4android integration module | ||
| */ | ||
| class CustomCertManagerModule { | ||
|
|
||
| @Provides | ||
| @Singleton | ||
| fun customCertManager( | ||
| @ApplicationContext context: Context, | ||
| settings: SettingsManager | ||
| ): Optional<CustomCertManager> = | ||
| if (BuildConfig.allowCustomCerts) | ||
| Optional.of(CustomCertManager( | ||
| certStore = CustomCertStore.getInstance(context), | ||
| settings = object : SettingsProvider { | ||
|
|
||
| override val appInForeground: Boolean | ||
| get() = ForegroundTracker.inForeground.value | ||
|
|
||
| override val trustSystemCerts: Boolean | ||
| get() = !settings.getBoolean(Settings.DISTRUST_SYSTEM_CERTIFICATES) | ||
|
|
||
| } | ||
| )) | ||
| else | ||
| Optional.empty() | ||
|
|
||
| @Provides | ||
| @Singleton | ||
| fun customHostnameVerifier( | ||
| customCertManager: Optional<CustomCertManager> | ||
| ): Optional<CustomCertManager.HostnameVerifier> = | ||
| if (BuildConfig.allowCustomCerts && customCertManager.isPresent) { | ||
| val hostnameVerifier = customCertManager.get().HostnameVerifier(OkHostnameVerifier) | ||
| Optional.of(hostnameVerifier) | ||
| } else | ||
| Optional.empty() | ||
|
|
||
| } |
24 changes: 24 additions & 0 deletions
24
app/src/main/kotlin/at/bitfire/davdroid/network/ConnectionSecurityContext.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| /* | ||
| * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. | ||
| */ | ||
|
|
||
| package at.bitfire.davdroid.network | ||
|
|
||
| import javax.net.ssl.HostnameVerifier | ||
| import javax.net.ssl.SSLSocketFactory | ||
| import javax.net.ssl.X509TrustManager | ||
|
|
||
| /** | ||
| * Holds information that shall be used to create TLS connections. | ||
| * | ||
| * @param sslSocketFactory the socket factory that shall be used | ||
| * @param trustManager the trust manager that shall be used | ||
| * @param hostnameVerifier the hostname verifier that shall be used | ||
| * @param disableHttp2 whether HTTP/2 shall be disabled | ||
| */ | ||
| class ConnectionSecurityContext( | ||
| val sslSocketFactory: SSLSocketFactory?, | ||
| val trustManager: X509TrustManager?, | ||
| val hostnameVerifier: HostnameVerifier?, | ||
| val disableHttp2: Boolean | ||
| ) |
108 changes: 108 additions & 0 deletions
108
app/src/main/kotlin/at/bitfire/davdroid/network/ConnectionSecurityManager.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| /* | ||
| * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. | ||
| */ | ||
|
|
||
| package at.bitfire.davdroid.network | ||
|
|
||
| import androidx.annotation.VisibleForTesting | ||
| import at.bitfire.cert4android.CustomCertManager | ||
| import java.lang.ref.SoftReference | ||
| import java.security.KeyStore | ||
| import java.util.Optional | ||
| import java.util.logging.Logger | ||
| import javax.inject.Inject | ||
| import javax.inject.Singleton | ||
| import javax.net.ssl.SSLContext | ||
| import javax.net.ssl.SSLSocketFactory | ||
| import javax.net.ssl.TrustManagerFactory | ||
| import javax.net.ssl.X509TrustManager | ||
| import kotlin.jvm.optionals.getOrNull | ||
|
|
||
| /** | ||
| * Caching provider for [ConnectionSecurityContext]. | ||
| */ | ||
| @Singleton | ||
| class ConnectionSecurityManager @Inject constructor( | ||
| private val customHostnameVerifier: Optional<CustomCertManager.HostnameVerifier>, | ||
| private val customTrustManager: Optional<CustomCertManager>, | ||
| private val keyManagerFactory: ClientCertKeyManager.Factory, | ||
| private val logger: Logger | ||
| ) { | ||
|
|
||
| /** | ||
| * Maps client certificate aliases (or `null` if no client authentication is used) to their SSLSocketFactory. | ||
| * Uses soft references for the values so that they can be garbage-collected when not used anymore. | ||
| * | ||
| * Not thread-safe, access must be synchronized by caller. | ||
| */ | ||
| private val socketFactoryCache: MutableMap<String?, SoftReference<SSLSocketFactory>> = | ||
| LinkedHashMap(2) // usually not more than: one for no client certificates + one for a certain certificate alias | ||
|
|
||
| /** | ||
| * The default TrustManager to use for connections. If [customTrustManager] provides a value, that value is | ||
| * used. Otherwise, the platform's default trust manager is used. | ||
| */ | ||
| private val trustManager by lazy { customTrustManager.getOrNull() ?: defaultTrustManager() } | ||
|
|
||
| /** | ||
| * Provides the [ConnectionSecurityContext] for a given [certificateAlias]. | ||
| * | ||
| * Uses [socketFactoryCache] to cache the entries (per [certificateAlias]). | ||
| * | ||
| * @param certificateAlias alias of the client certificate that shall be used for authentication (`null` for none) | ||
| * @return the connection security context | ||
| */ | ||
| fun getContext(certificateAlias: String?): ConnectionSecurityContext { | ||
| /* We only need a custom socket factory for | ||
| - client certificates and/or | ||
| - when cert4android is active (= there's a custom trustManager). */ | ||
| val socketFactory = if (certificateAlias != null || customTrustManager.isPresent) | ||
| getSocketFactory(certificateAlias) | ||
| else | ||
| null | ||
|
|
||
| return ConnectionSecurityContext( | ||
| sslSocketFactory = socketFactory, | ||
| trustManager = if (socketFactory != null) trustManager else null, // when there's a customTrustManager, there's always a socketFactory, too | ||
| hostnameVerifier = customHostnameVerifier.getOrNull(), | ||
| disableHttp2 = certificateAlias != null | ||
| ) | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| internal fun getSocketFactory(certificateAlias: String?): SSLSocketFactory = synchronized(socketFactoryCache) { | ||
| // look up cache first | ||
| val cachedFactory = socketFactoryCache[certificateAlias]?.get() | ||
| if (cachedFactory != null) { | ||
| logger.fine("Using cached SSLSocketFactory (certificateAlias=$certificateAlias)") | ||
| return cachedFactory | ||
| } else | ||
| logger.fine("Creating new SSLSocketFactory (certificateAlias=$certificateAlias)") | ||
| // no cached value, calculate and store into cache | ||
|
|
||
| // when a client certificate alias is given, create and use the respective ClientKeyManager | ||
| val clientKeyManager = certificateAlias?.let { keyManagerFactory.create(it) } | ||
|
|
||
| // create SSLContext that provides the SSLSocketFactory | ||
| val sslContext = SSLContext.getInstance("TLS").apply { | ||
| init( | ||
| /* km = */ clientKeyManager?.let { arrayOf(it) }, | ||
| /* tm = */ arrayOf(trustManager), | ||
| /* random = */ null /* default RNG */ | ||
| ) | ||
| } | ||
|
|
||
| // cache reference and return socket factory | ||
| return sslContext.socketFactory.also { socketFactory -> | ||
| socketFactoryCache[certificateAlias] = SoftReference(socketFactory) | ||
| } | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| internal fun defaultTrustManager(): X509TrustManager { | ||
| val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) | ||
| factory.init(null as KeyStore?) | ||
| return factory.trustManagers.filterIsInstance<X509TrustManager>().first() | ||
| } | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.