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

Python ssl standard library:

import ssl

ctx = ssl._create_unverified_context() # Noncompliant: by default hostname verification is not done
ctx = ssl._create_stdlib_context() # Noncompliant: by default hostname verification is not done

ctx = ssl.create_default_context()
ctx.check_hostname = False # Noncompliant

ctx = ssl._create_default_https_context()
ctx.check_hostname = False # Noncompliant

Compliant Solution

Python ssl standard library:

import ssl

ctx = ssl._create_unverified_context()
ctx.check_hostname = True # Compliant

ctx = ssl._create_stdlib_context()
ctx.check_hostname = True # Compliant

ctx = ssl.create_default_context() # Compliant: by default hostname verification is enabled
ctx = ssl._create_default_https_context() # Compliant: by default hostname verification is enabled

See