Improper certificate validation High

Lack of validation or insufficient validation of a security certificate can lead to host impersonation and sensitive data leaks.

Detector ID
python/improper-certificate-validation@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1def create_connection_noncompliant():
2    import socket
3    import ssl
4    host, port = 'example.com', 443
5    with socket.socket(socket.AF_INET) as sock:
6        context = ssl.SSLContext()
7        # Noncompliant: security certificate validation disabled.
8        context.verify_mode = ssl.CERT_NONE
9        conn = context.wrap_socket(sock, server_hostname=host)
10        try:
11            conn.connect((host, port))
12            handle(conn)
13        finally:
14            conn.close()

Compliant example

1def create_connection_compliant():
2    import socket
3    import ssl
4    host, port = 'example.com', 443
5    with socket.socket(socket.AF_INET) as sock:
6        context = ssl.SSLContext()
7        # Compliant: security certificate validation enabled.
8        context.verify_mode = ssl.CERT_REQUIRED
9        conn = context.wrap_socket(sock, server_hostname=host)
10        try:
11            conn.connect((host, port))
12            handle(conn)
13        finally:
14            conn.close()