2121from pymongo .errors import ConfigurationError
2222
2323HAVE_SSL = True
24+ HAVE_PYSSL = True
2425
2526try :
26- import pymongo .pyopenssl_context as _ssl
27+ import pymongo .pyopenssl_context as _pyssl
2728except (ImportError , AttributeError ) as exc :
29+ HAVE_PYSSL = False
2830 if isinstance (exc , AttributeError ):
2931 warnings .warn (
3032 "Failed to use the installed version of PyOpenSSL. "
3537 UserWarning ,
3638 stacklevel = 2 ,
3739 )
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
4244
4345
4446if HAVE_SSL :
@@ -65,8 +67,13 @@ def get_ssl_context(
6567 allow_invalid_certificates : bool ,
6668 allow_invalid_hostnames : bool ,
6769 disable_ocsp_endpoint_check : bool ,
70+ is_sync : bool ,
6871 ) -> _ssl .SSLContext :
6972 """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
7077 verify_mode = CERT_NONE if allow_invalid_certificates else CERT_REQUIRED
7178 ctx = _ssl .SSLContext (_ssl .PROTOCOL_SSLv23 )
7279 if verify_mode != CERT_NONE :
@@ -80,21 +87,21 @@ def get_ssl_context(
8087 # up to date versions of MongoDB 2.4 and above already disable
8188 # SSLv2 and SSLv3, python disables SSLv2 by default in >= 2.7.7
8289 # 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
8794 if certfile is not None :
8895 try :
8996 ctx .load_cert_chain (certfile , None , passphrase )
90- except _ssl .SSLError as exc :
97+ except ssl_in_use .SSLError as exc :
9198 raise ConfigurationError (f"Private key doesn't match certificate: { exc } " ) from None
9299 if crlfile is not None :
93- if _ssl .IS_PYOPENSSL :
100+ if ssl_in_use .IS_PYOPENSSL :
94101 raise ConfigurationError ("tlsCRLFile cannot be used with PyOpenSSL" )
95102 # Match the server's behavior.
96103 ctx .verify_flags = getattr ( # type:ignore[attr-defined]
97- _ssl , "VERIFY_CRL_CHECK_LEAF" , 0
104+ ssl_in_use , "VERIFY_CRL_CHECK_LEAF" , 0
98105 )
99106 ctx .load_verify_locations (crlfile )
100107 if ca_certs is not None :
0 commit comments