Description
Python deprecated the module-level ssl.wrap_socket function in 3.7 and removed it in 3.12. Wrap the socket with the wrap_socket() method of an ssl.SSLContext.
Potential impact
The old call fails on Python 3.12 or later. On earlier versions, skipping certificate and hostname checks can send sensitive data to someone impersonating the server.
Remediation
- On the client, use
ssl.create_default_context()to verify the server’s certificate chain. Add your private CA if needed and pass the destination hostname asserver_hostname. - Require at least TLS 1.2 and allow TLS 1.3 when supported.
Examples
To run the server excerpt, supply the server certificate, its private key and request-handling code. The example does not require a client certificate.
Before
python
# Historical ssl.wrap_socket API
import socket
import ssl
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
wrapped_socket = ssl.wrap_socket(sock)
wrapped_socket.connect(('example.com', 443))
After
Client
python
# SSLContext client
import socket
import ssl
hostname = 'www.python.org'
context = ssl.create_default_context()
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
print(ssock.version())
Server
python
# SSLContext server
import socket
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
sock.bind(('127.0.0.1', 8443))
sock.listen(5)
with context.wrap_socket(sock, server_side=True) as ssock:
conn, addr = ssock.accept()
...
Explanation
The client opens a TCP connection, then verifies the server with SSLContext.wrap_socket(). The server loads its own certificate and private key before accepting TLS connections.
References
- OWASP: Transport Layer Protection Cheat Sheet
- CWE: CWE-327: Use of a Broken or Risky Cryptographic Algorithm
- Python Documentation: ssl: TLS/SSL wrapper for socket objects
- Python 3.12: What's New In Python 3.12