Enforce TLS 1.2 Minimum in Python
Create an SSL context with a minimum TLS version of 1.2 to enforce secure connections.
Python code
11 linesimport ssl
def get_min_tls_version():
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context.minimum_version
if __name__ == "__main__":
min_version = get_min_tls_version()
print(f"Minimum TLS version set to: {min_version.name} (value: {min_version})")
print(f"Is at least TLS 1.2: {min_version >= ssl.TLSVersion.TLSv1_2}")
Output
Minimum TLS version set to: TLSv1_2 (value: 771)
Is at least TLS 1.2: True
How it works
The ssl.SSLContext is created with PROTOCOL_TLS_CLIENT, which configures the context for client-side TLS connections with default certificate validation. Setting minimum_version to TLSVersion.TLSv1_2 ensures that older, insecure protocols like SSLv3 and TLS 1.0/1.1 are rejected. The name attribute of TLSVersion provides a human-readable label, and the integer value corresponds to the protocol's internal representation. Comparing versions with >= confirms the minimum is met.
Common mistakes
- Forgetting to set `check_hostname` and `load_default_certs` for real client connections
- Using `PROTOCOL_TLS` instead of `PROTOCOL_TLS_CLIENT`, which may not enable proper defaults
- Assuming `minimum_version` is set by default; it falls back to system defaults if not explicit
Variations
- Use `context.set_ciphers` to also restrict weak cipher suites
- Set `context.minimum_version` directly on a context from `ssl.create_default_context()`
Real-world use cases
- Securing connections to internal services that still support old TLS versions but must enforce 1.2+
- Compliance audits where PCI-DSS or HIPAA require minimum TLS 1.2 for data transmission
- Client-side code that calls third-party APIs with strict security policies and needs guaranteed TLS 1.2
Sponsored
More from Auth & security at scale
- ACME LetsEncrypt Mock Challenge Server in Python medium
- AES GCM encryption and decryption in Python medium
- Build a Mock OIDC Userinfo Endpoint in Python with Flask easy
- ChaCha20-Poly1305 mock in Python medium
- ECDH key agreement in Python with cryptography medium
- Fetch Secrets from a Mock Secrets Manager in Python easy
Keep learning
Related tutorials and quizzes for this topic.