import ssl def create_tls_context(purpose=ssl.Purpose.CLIENT_AUTH): """ Creates an SSL context configured for TLS 1.3. Args: purpose: The SSL purpose (e.g., CLIENT_AUTH, SERVER_AUTH). Returns: An SSLContext object configured for TLS 1.3. """ context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT if purpose == ssl.Purpose.CLIENT_AUTH else ssl.PROTOCOL_TLS_SERVER) # Require TLS 1.3 context.minimum_version = ssl.TLSVersion.TLSv1_3 # Recommended secure cipher suites (TLS 1.3 suites are handled automatically) # For compatibility with TLS 1.2 if needed, but minimum_version enforces 1.3 # context.set_ciphers('ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20') # Example: Load cert/key for server or client auth if needed # if purpose == ssl.Purpose.SERVER_AUTH: # context.load_cert_chain(certfile="path/to/cert.pem", keyfile="path/to/key.pem") # elif purpose == ssl.Purpose.CLIENT_AUTH: # context.load_verify_locations(cafile="path/to/ca.pem") # context.verify_mode = ssl.CERT_REQUIRED # Further hardening options: Disable insecure protocols context.options |= ssl.OP_NO_SSLv2 context.options |= ssl.OP_NO_SSLv3 context.options |= ssl.OP_NO_TLSv1 context.options |= ssl.OP_NO_TLSv1_1 # context.options |= ssl.OP_SINGLE_DH_USE # Consider if needed based on ciphers # context.options |= ssl.OP_SINGLE_ECDH_USE # Consider if needed based on ciphers # Enforce TLS 1.3 as the minimum required version context.minimum_version = ssl.TLSVersion.TLSv1_3 return context # Example usage (can be removed or kept for demonstration) if __name__ == '__main__': client_context = create_tls_context(ssl.Purpose.CLIENT_AUTH) print(f"Client Context Minimum TLS Version: {client_context.minimum_version}") # print(f"Client Context Ciphers: {client_context.get_ciphers()}") # Requires OpenSSL 1.1.1+ server_context = create_tls_context(ssl.Purpose.SERVER_AUTH) print(f"Server Context Minimum TLS Version: {server_context.minimum_version}") # print(f"Server Context Ciphers: {server_context.get_ciphers()}") # Requires OpenSSL 1.1.1+