Lack of validation or insufficient validation of a security certificate can lead to host impersonation and sensitive data leaks.
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()
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()