This function is a vendored version of the same function in urllib3 We vendor this function to ensure that the SSL contexts we construct always use the std lib SSLContext instead of pyopenssl.
(
ssl_version=None, cert_reqs=None, options=None, ciphers=None
)
| 104 | |
| 105 | |
| 106 | def create_urllib3_context( |
| 107 | ssl_version=None, cert_reqs=None, options=None, ciphers=None |
| 108 | ): |
| 109 | """This function is a vendored version of the same function in urllib3 |
| 110 | |
| 111 | We vendor this function to ensure that the SSL contexts we construct |
| 112 | always use the std lib SSLContext instead of pyopenssl. |
| 113 | """ |
| 114 | # PROTOCOL_TLS is deprecated in Python 3.10 |
| 115 | if not ssl_version or ssl_version == PROTOCOL_TLS: |
| 116 | ssl_version = PROTOCOL_TLS_CLIENT |
| 117 | |
| 118 | context = SSLContext(ssl_version) |
| 119 | |
| 120 | if ciphers: |
| 121 | context.set_ciphers(ciphers) |
| 122 | elif DEFAULT_CIPHERS: |
| 123 | context.set_ciphers(DEFAULT_CIPHERS) |
| 124 | |
| 125 | # Setting the default here, as we may have no ssl module on import |
| 126 | cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs |
| 127 | |
| 128 | if options is None: |
| 129 | options = 0 |
| 130 | # SSLv2 is easily broken and is considered harmful and dangerous |
| 131 | options |= OP_NO_SSLv2 |
| 132 | # SSLv3 has several problems and is now dangerous |
| 133 | options |= OP_NO_SSLv3 |
| 134 | # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ |
| 135 | # (issue urllib3#309) |
| 136 | options |= OP_NO_COMPRESSION |
| 137 | # TLSv1.2 only. Unless set explicitly, do not request tickets. |
| 138 | # This may save some bandwidth on wire, and although the ticket is encrypted, |
| 139 | # there is a risk associated with it being on wire, |
| 140 | # if the server is not rotating its ticketing keys properly. |
| 141 | options |= OP_NO_TICKET |
| 142 | |
| 143 | context.options |= options |
| 144 | |
| 145 | # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is |
| 146 | # necessary for conditional client cert authentication with TLS 1.3. |
| 147 | # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older |
| 148 | # versions of Python. We only enable on Python 3.7.4+ or if certificate |
| 149 | # verification is enabled to work around Python issue #37428 |
| 150 | # See: https://bugs.python.org/issue37428 |
| 151 | if ( |
| 152 | cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4) |
| 153 | ) and getattr(context, "post_handshake_auth", None) is not None: |
| 154 | context.post_handshake_auth = True |
| 155 | |
| 156 | def disable_check_hostname(): |
| 157 | if ( |
| 158 | getattr(context, "check_hostname", None) is not None |
| 159 | ): # Platform-specific: Python 3.2 |
| 160 | # We do our own verification, including fingerprints and alternative |
| 161 | # hostnames. So disable it here |
| 162 | context.check_hostname = False |
| 163 |
no test coverage detected