---
title: TLS Clients Must Validate Server Certificates
impact: CRITICAL
impactDescription: prevents Man-in-the-Middle (MitM) attacks by ensuring the server identity is authentic
tags: tls, certificates, validation, mitm, security, kotlin
---

## TLS Clients Must Validate Server Certificates

Disabling TLS certificate validation or trusting all certificates allows an attacker to intercept, read, and modify your traffic by presenting a self-signed or forged certificate. This completely bypasses the security provided by TLS.

**Incorrect (disabled validation / trust-all):**

```kotlin
// DANGEROUS: Trusting all certificates in OkHttp
val trustAllCerts = arrayOf<X509TrustManager>(object : X509TrustManager {
    override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
    override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}
    override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
})

// DANGEROUS: Trust-all SSL context
val sslContext = SSLContext.getInstance("SSL").apply {
    init(null, trustAllCerts, SecureRandom())
}

// DANGEROUS: Ignoring Hostname verification
val hostnameVerifier = HostnameVerifier { _, _ -> true }
```

**Correct (proper validation):**

```kotlin
// 1. Default Behavior (Uses System Trust Store) - Safe
val client = OkHttpClient() // Validates against trusted root CAs

// 2. Custom CA for internal/private services
val caInputStream: InputStream = File("internal-ca.pem").inputStream()
val certificateFactory = CertificateFactory.getInstance("X.509")
val ca = certificateFactory.generateCertificate(caInputStream)

val keyStore = KeyStore.getInstance(KeyStore.getDefaultType()).apply {
    load(null, null)
    setCertificateEntry("ca", ca)
}

val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply {
    init(keyStore)
}

val client = OkHttpClient.Builder()
    .sslSocketFactory(sslContext.socketFactory, trustManagerFactory.trustManagers[0] as X509TrustManager)
    .build()
```

**Security Checklist:**
- Never use code that explicitly bypasses `checkServerTrusted`.
- Do not return `true` from a custom `HostnameVerifier` without validation.
- In production, ensure no "trust-all" SSL factories are instantiated.
- For mobile apps, consider **Certificate Pinning** for high-security endpoints.

**Tools:** SSLyze, Qualys SSL Labs, OWASP ZAP, Manual Review
