21
21
from pymongo .errors import ConfigurationError
22
22
23
23
HAVE_SSL = True
24
+ HAVE_PYSSL = True
24
25
25
26
try :
26
- import pymongo .pyopenssl_context as _ssl
27
+ import pymongo .pyopenssl_context as _pyssl
27
28
except (ImportError , AttributeError ) as exc :
29
+ HAVE_PYSSL = False
28
30
if isinstance (exc , AttributeError ):
29
31
warnings .warn (
30
32
"Failed to use the installed version of PyOpenSSL. "
35
37
UserWarning ,
36
38
stacklevel = 2 ,
37
39
)
38
- try :
39
- import pymongo .ssl_context as _ssl # type: ignore[no-redef]
40
- except ImportError :
41
- HAVE_SSL = False
40
+ try :
41
+ import pymongo .ssl_context as _ssl
42
+ except ImportError :
43
+ HAVE_SSL = False
42
44
43
45
44
46
if HAVE_SSL :
@@ -65,8 +67,13 @@ def get_ssl_context(
65
67
allow_invalid_certificates : bool ,
66
68
allow_invalid_hostnames : bool ,
67
69
disable_ocsp_endpoint_check : bool ,
70
+ is_sync : bool ,
68
71
) -> _ssl .SSLContext :
69
72
"""Create and return an SSLContext object."""
73
+ if is_sync and HAVE_PYSSL :
74
+ ssl_in_use = _pyssl
75
+ else :
76
+ ssl_in_use = _ssl
70
77
verify_mode = CERT_NONE if allow_invalid_certificates else CERT_REQUIRED
71
78
ctx = _ssl .SSLContext (_ssl .PROTOCOL_SSLv23 )
72
79
if verify_mode != CERT_NONE :
@@ -80,21 +87,21 @@ def get_ssl_context(
80
87
# up to date versions of MongoDB 2.4 and above already disable
81
88
# SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7
82
89
# and >= 3.3.4 and SSLv3 in >= 3.4.3.
83
- ctx .options |= _ssl .OP_NO_SSLv2
84
- ctx .options |= _ssl .OP_NO_SSLv3
85
- ctx .options |= _ssl .OP_NO_COMPRESSION
86
- ctx .options |= _ssl .OP_NO_RENEGOTIATION
90
+ ctx .options |= ssl_in_use .OP_NO_SSLv2
91
+ ctx .options |= ssl_in_use .OP_NO_SSLv3
92
+ ctx .options |= ssl_in_use .OP_NO_COMPRESSION
93
+ ctx .options |= ssl_in_use .OP_NO_RENEGOTIATION
87
94
if certfile is not None :
88
95
try :
89
96
ctx .load_cert_chain (certfile , None , passphrase )
90
- except _ssl .SSLError as exc :
97
+ except ssl_in_use .SSLError as exc :
91
98
raise ConfigurationError (f"Private key doesn't match certificate: { exc } " ) from None
92
99
if crlfile is not None :
93
- if _ssl .IS_PYOPENSSL :
100
+ if ssl_in_use .IS_PYOPENSSL :
94
101
raise ConfigurationError ("tlsCRLFile cannot be used with PyOpenSSL" )
95
102
# Match the server's behavior.
96
103
ctx .verify_flags = getattr ( # type:ignore[attr-defined]
97
- _ssl , "VERIFY_CRL_CHECK_LEAF" , 0
104
+ ssl_in_use , "VERIFY_CRL_CHECK_LEAF" , 0
98
105
)
99
106
ctx .load_verify_locations (crlfile )
100
107
if ca_certs is not None :
0 commit comments