To establish a SSL/TLS connection not vulnerable to man-in-the-middle attacks, it’s essential to make sure the server presents the right certificate.

The certificate’s hostname-specific data should match the server hostname.

It’s not recommended to re-invent the wheel by implementing custom hostname verification.

TLS/SSL libraries provide built-in hostname verification functions that should be used.

Noncompliant Code Example

When using the okhttp library, a custom unsecure hostname verifier accepting every hostname is used:

val builder = OkHttpClient.Builder()
builder.hostnameVerifier(object : HostnameVerifier {
  override fun verify(hostname: String?, session: SSLSession?): Boolean {
    return true // Noncompliant (s5527)
  }
})

Compliant Solution

When using the okhttp library, if hostnameVerifier method is not used to set a verifier, then a built-in secure one will be used:

val builder = OkHttpClient.Builder()

See