Explain Codes LogoExplain Codes Logo

Trusting all certificates using HttpClient over HTTPS

java
ssl
https
truststore
Nikita BarsukovbyNikita Barsukov·Sep 29, 2024
TLDR

To bypass SSL validation with Apache HttpClient, a permissive SSLContext can be utilized:

import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.impl.client.HttpClients; import javax.net.ssl.SSLContext; public class UnsafeHttpClient { public CloseableHttpClient createBlindClient() throws Exception { // creates an SSLContext that trusts everything - not recommended for production! SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial((chain, authType) -> true).build(); return HttpClients.custom() .setSslcontext(sslContext) .setSSLHostnameVerifier((hostname, session) -> true) .build(); } }

Alert: This blind trust is for testing purposes only. Don't let your guard down in production — it sets you up for MITM attacks.

Taming the trust beast

Playing with fire? Handle with care

While it's tempting to trust all certificates for quick testing, remember to switch back to a cautious level of trust in production.

Custom TrustStore: Your guardian knight

Create a custom keystore with trusted certificates. Your self-signed or corporate certificates live happily inside.

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); //Game of Thrones fans, don't use "password" as your password ;) trustStore.load(new FileInputStream("myTrustStore.keystore"), "password".toCharArray()); SSLContext sslContext = SSLContextBuilder.create() .loadTrustMaterial(trustStore, null) .build();

Keeping the fortress secure

Ensure that you're only trusting the certificates that you validly own. Cersei from GoT couldn't pull off a better betrayal than a MITM attack.

The Trust Manager: The Knight's Watch in action

Trust Managers are your knights, verifying certificate chains and expiry dates, and fighting against trust in all certificates.

Test with caution: You know nothing, Jon Snow

In debugging or development, methods like SSLCertificateSocketFactory.getInsecure and AllowAllHostnameVerifier() don't deserve to sit on the iron throne. They should never exist in production code.

Curating your Android armory

Fill your Android keystore with your best swords (certificates), add them to the Android master list, and use AdditionalKeyStoresSSLSocketFactory for instructing your knights.

Valar Morghulis: All men must confront exceptions

Facing a SSLHandshakeException or Not Trusted error? Examine your keystore for the missing certificate and put it back on the wall (autority list).

When all roads lead to trust

In rare cases like local testing or working with a self-signed certificate behind corporate firewalls, trusting an unverified certificate might seem the only way.

Strategy stands tall, even when convenience lures

Even in such desperate times, let not blanket trust be your strategy. Develop a unique trust manager that can be switched out with a secure one when needed.

Register your faithful servers

Register your custom SSLSocketFactory with HttpClient. In the battle of secure connections, these are reliable bannermen.

httpClientBuilder.setSSLContext(sslContext) .setSSLHostnameVerifier(hostnameVerifier) .build();

Heed the watchman's call

When your logs turn into cries of alert, like expired certificates or a broken certificate chain, rally your troops and face the enemy head-on.

KeyStore: The king of your secure kingdom

Master the arts of the KeyStore

Just like mastering the sword, managing Java KeyStores is crucial. Swing your keytool rightly to command actions like generating keys, generating certificate requests, and importing certificates.

Revise, renew, and remember

As time moves on, expiry dates approach. Continually review certificates to ensure your wall (app) doesn't crumble due to expired certificates.

Walk the Android pathway steadily

When dealing with HTTPS on Android, follow the north star and steps to create and register custom keystores for success.

Dodging shadows in the dark

Avoid trusting all certificates in production like the plague. Validate hostnames and certificate chains to secure your kingdom against vulnerabilities.