Description
Trusting every certificate or accepting every hostname makes a TLS connection vulnerable to man-in-the-middle attacks. Empty verification methods in an X509TrustManager or a HostnameVerifier that always returns true bypass essential server authentication checks.
Potential impact
- An attacker may intercept TLS connections with a forged certificate.
- Sensitive data, session tokens, and API requests or responses may be intercepted or modified.
- Test-only bypass settings reaching production can undermine communication security.
Remediation
- Use the default trust store and
HostnameVerifier; do not bypass verification in selected environments. - If tests require a self-signed certificate, configure a separate trust store.
- Do not use custom verifiers or trust managers that accept every certificate or hostname.
Examples
Before
java
import javax.net.ssl.HttpsURLConnection;
public class UnsafeHostnameVerifier {
void configure(HttpsURLConnection conn) {
conn.setHostnameVerifier((hostname, session) -> true);
}
}
After
java
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
public class SafeTlsVerifier {
void configure(HttpsURLConnection conn) {
HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
conn.setHostnameVerifier(verifier);
}
}
Explanation:
- Before: Returning
truefor every hostname bypasses the check that the certificate belongs to the intended server. - After: The default hostname verifier retains the TLS library's normal verification flow.
Other verification bypasses
- Empty
checkClientTrustedorcheckServerTrustedmethods innew X509TrustManager() { ... }skip the corresponding certificate trust checks. - Always-accepting implementations bypass hostname verification whether defined as
class AlwaysTrueVerifier implements HostnameVerifieror anonymously asnew HostnameVerifier() { ... return true; }. - Kotlin's
HostnameVerifier { _, _ -> true }carries the same risk. Implementations usingobject : HostnameVerifier { ... }orobject : X509TrustManager { ... }must also perform real verification.