Debian Codegraph @

src/urllib3/contrib/pyopenssl.py

raw ◀ ▶
1 Debian patch touch this file
1 """
2 Module for using pyOpenSSL as a TLS backend. This module was relevant before
3 the standard library ``ssl`` module supported SNI, but now that we've dropped
4 support for Python 2.7 all relevant Python versions support SNI so
5 **this module is no longer recommended**.
6
7 This needs the following packages installed:
8
9 * `pyOpenSSL`_ (tested with 19.0.0)
10 * `cryptography`_ (minimum 2.3, from pyopenssl)
11 * `idna`_ (minimum 2.1, from cryptography)
12
13 However, pyOpenSSL depends on cryptography, so while we use all three directly here we
14 end up having relatively few packages required.
15
16 You can install them with the following command:
17
18 .. code-block:: bash
19
20 $ python -m pip install pyopenssl cryptography idna
21
22 To activate certificate checking, call
23 :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code
24 before you begin making HTTP requests. This can be done in a ``sitecustomize``
25 module, or at any other time before your application begins using ``urllib3``,
26 like this:
27
28 .. code-block:: python
29
30 try:
31 import urllib3.contrib.pyopenssl
32 urllib3.contrib.pyopenssl.inject_into_urllib3()
33 except ImportError:
34 pass
35
36 .. _pyopenssl: https://www.pyopenssl.org
37 .. _cryptography: https://cryptography.io
38 .. _idna: https://github.com/kjd/idna
39 """
40
41 from __future__ import annotations
42
43 import OpenSSL.SSL # type: ignore[import-not-found]
44 from cryptography import x509
•45 from cryptography.hazmat.primitives.serialization import load_pem_private_key
46 from cryptography.x509.oid import NameOID
47
48 try:
49 from cryptography.x509 import UnsupportedExtension # type: ignore[attr-defined]
50 except ImportError:
51 # UnsupportedExtension is gone in cryptography >= 2.1.0
52 class UnsupportedExtension(Exception): # type: ignore[no-redef]
53 pass
54
55
56 import logging
57 import ssl
58 import typing
59 from io import BytesIO
60 from socket import socket as socket_cls
61
62 from .. import util
63
64 if typing.TYPE_CHECKING:
65 from OpenSSL.crypto import X509 # type: ignore[import-not-found]
66
67
68 __all__ = ["inject_into_urllib3", "extract_from_urllib3"]
69
70 # Map from urllib3 to PyOpenSSL compatible parameter-values.
71 _openssl_versions: dict[int, int] = {
72 util.ssl_.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined]
73 util.ssl_.PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined]
74 ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,
75 }
76
77 if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"):
78 _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD
79
80 if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"):
81 _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD
82
83
84 _stdlib_to_openssl_verify = {
85 ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
86 ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
87 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER
88 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
89 }
90 _openssl_to_stdlib_verify = {v: k for k, v in _stdlib_to_openssl_verify.items()}
91
92 # The SSLvX values are the most likely to be missing in the future
93 # but we check them all just to be sure.
94 _OP_NO_SSLv2_OR_SSLv3: int = getattr(OpenSSL.SSL, "OP_NO_SSLv2", 0) | getattr(
95 OpenSSL.SSL, "OP_NO_SSLv3", 0
96 )
97 _OP_NO_TLSv1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1", 0)
98 _OP_NO_TLSv1_1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_1", 0)
99 _OP_NO_TLSv1_2: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_2", 0)
100 _OP_NO_TLSv1_3: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_3", 0)
101
102 _openssl_to_ssl_minimum_version: dict[int, int] = {
103 ssl.TLSVersion.MINIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3,
104 ssl.TLSVersion.TLSv1: _OP_NO_SSLv2_OR_SSLv3,
105 ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1,
106 ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1,
107 ssl.TLSVersion.TLSv1_3: (
108 _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2
109 ),
110 ssl.TLSVersion.MAXIMUM_SUPPORTED: (
111 _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2
112 ),
113 }
114 _openssl_to_ssl_maximum_version: dict[int, int] = {
115 ssl.TLSVersion.MINIMUM_SUPPORTED: (
116 _OP_NO_SSLv2_OR_SSLv3
117 | _OP_NO_TLSv1
118 | _OP_NO_TLSv1_1
119 | _OP_NO_TLSv1_2
120 | _OP_NO_TLSv1_3
121 ),
122 ssl.TLSVersion.TLSv1: (
123 _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3
124 ),
125 ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3,
126 ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_3,
127 ssl.TLSVersion.TLSv1_3: _OP_NO_SSLv2_OR_SSLv3,
128 ssl.TLSVersion.MAXIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3,
129 }
130
131 # OpenSSL will only write 16K at a time
132 SSL_WRITE_BLOCKSIZE = 16384
133
134 orig_util_SSLContext = util.ssl_.SSLContext
135
136
137 log = logging.getLogger(__name__)
138
139
140 def inject_into_urllib3() -> None:
141 "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support."
142
143 _validate_dependencies_met()
144
145 util.SSLContext = PyOpenSSLContext # type: ignore[assignment]
146 util.ssl_.SSLContext = PyOpenSSLContext # type: ignore[assignment]
147 util.IS_PYOPENSSL = True
148 util.ssl_.IS_PYOPENSSL = True
149
150
151 def extract_from_urllib3() -> None:
152 "Undo monkey-patching by :func:`inject_into_urllib3`."
153
154 util.SSLContext = orig_util_SSLContext
155 util.ssl_.SSLContext = orig_util_SSLContext
156 util.IS_PYOPENSSL = False
157 util.ssl_.IS_PYOPENSSL = False
158
159
160 def _validate_dependencies_met() -> None:
161 """
162 Verifies that PyOpenSSL's package-level dependencies have been met.
163 Throws `ImportError` if they are not met.
164 """
165 # Method added in `cryptography==1.1`; not available in older versions
166 from cryptography.x509.extensions import Extensions
167
168 if getattr(Extensions, "get_extension_for_class", None) is None:
169 raise ImportError(
170 "'cryptography' module missing required functionality. "
171 "Try upgrading to v1.3.4 or newer."
172 )
173
174 # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509
175 # attribute is only present on those versions.
176 from OpenSSL.crypto import X509
177
178 x509 = X509()
179 if getattr(x509, "_x509", None) is None:
180 raise ImportError(
181 "'pyOpenSSL' module missing required functionality. "
182 "Try upgrading to v0.14 or newer."
183 )
184
185
186 def _dnsname_to_stdlib(name: str) -> str | None:
187 """
188 Converts a dNSName SubjectAlternativeName field to the form used by the
189 standard library on the given Python version.
190
191 Cryptography produces a dNSName as a unicode string that was idna-decoded
192 from ASCII bytes. We need to idna-encode that string to get it back, and
193 then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
194 uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).
195
196 If the name cannot be idna-encoded then we return None signalling that
197 the name given should be skipped.
198 """
199
200 def idna_encode(name: str) -> bytes | None:
201 """
202 Borrowed wholesale from the Python Cryptography Project. It turns out
203 that we can't just safely call `idna.encode`: it can explode for
204 wildcard names. This avoids that problem.
205 """
206 import idna
207
208 try:
209 for prefix in ["*.", "."]:
210 if name.startswith(prefix):
211 name = name[len(prefix) :]
212 return prefix.encode("ascii") + idna.encode(name)
213 return idna.encode(name)
214 except idna.core.IDNAError:
215 return None
216
217 # Don't send IPv6 addresses through the IDNA encoder.
218 if ":" in name:
219 return name
220
221 encoded_name = idna_encode(name)
222 if encoded_name is None:
223 return None
224 return encoded_name.decode("utf-8")
225
226
227 def get_subj_alt_name(peer_cert: X509) -> list[tuple[str, str]]:
228 """
229 Given an PyOpenSSL certificate, provides all the subject alternative names.
230 """
231 cert = peer_cert.to_cryptography()
232
233 # We want to find the SAN extension. Ask Cryptography to locate it (it's
234 # faster than looping in Python)
235 try:
236 ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
237 except x509.ExtensionNotFound:
238 # No such extension, return the empty list.
239 return []
240 except (
241 x509.DuplicateExtension,
242 UnsupportedExtension,
243 x509.UnsupportedGeneralNameType,
244 UnicodeError,
245 ) as e:
246 # A problem has been found with the quality of the certificate. Assume
247 # no SAN field is present.
248 log.warning(
249 "A problem was encountered with the certificate that prevented "
250 "urllib3 from finding the SubjectAlternativeName field. This can "
251 "affect certificate validation. The error was %s",
252 e,
253 )
254 return []
255
256 # We want to return dNSName and iPAddress fields. We need to cast the IPs
257 # back to strings because the match_hostname function wants them as
258 # strings.
259 # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
260 # decoded. This is pretty frustrating, but that's what the standard library
261 # does with certificates, and so we need to attempt to do the same.
262 # We also want to skip over names which cannot be idna encoded.
263 names = [
264 ("DNS", name)
265 for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
266 if name is not None
267 ]
268 names.extend(
269 ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress)
270 )
271
272 return names
273
274
•275 def _get_common_name(peer_cert: X509) -> str | None:
276 """
277 Given a pyOpenSSL certificate, return the subject's common name.
278 """
279 cert = peer_cert.to_cryptography()
280 names = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
281 return typing.cast(str, names[0].value) if names else None
282
283
284 class WrappedSocket:
285 """API-compatibility wrapper for Python OpenSSL's Connection-class."""
286
287 def __init__(
288 self,
289 connection: OpenSSL.SSL.Connection,
290 socket: socket_cls,
291 suppress_ragged_eofs: bool = True,
292 ) -> None:
293 self.connection = connection
294 self.socket = socket
295 self.suppress_ragged_eofs = suppress_ragged_eofs
296 self._io_refs = 0
297 self._closed = False
298
299 def fileno(self) -> int:
300 return self.socket.fileno()
301
302 # Copy-pasted from Python 3.5 source code
303 def _decref_socketios(self) -> None:
304 if self._io_refs > 0:
305 self._io_refs -= 1
306 if self._closed:
307 self.close()
308
309 def recv(self, *args: typing.Any, **kwargs: typing.Any) -> bytes:
310 try:
311 data = self.connection.recv(*args, **kwargs)
312 except OpenSSL.SSL.SysCallError as e:
313 if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):
314 return b""
315 else:
316 raise OSError(e.args[0], str(e)) from e
317 except OpenSSL.SSL.ZeroReturnError:
318 if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
319 return b""
320 else:
321 raise
322 except OpenSSL.SSL.WantReadError as e:
323 if not util.wait_for_read(self.socket, self.socket.gettimeout()):
324 raise TimeoutError("The read operation timed out") from e
325 else:
326 return self.recv(*args, **kwargs)
327
328 # TLS 1.3 post-handshake authentication
329 except OpenSSL.SSL.Error as e:
330 raise ssl.SSLError(f"read error: {e!r}") from e
331 else:
332 return data # type: ignore[no-any-return]
333
334 def recv_into(self, *args: typing.Any, **kwargs: typing.Any) -> int:
335 try:
336 return self.connection.recv_into(*args, **kwargs) # type: ignore[no-any-return]
337 except OpenSSL.SSL.SysCallError as e:
338 if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):
339 return 0
340 else:
341 raise OSError(e.args[0], str(e)) from e
342 except OpenSSL.SSL.ZeroReturnError:
343 if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
344 return 0
345 else:
346 raise
347 except OpenSSL.SSL.WantReadError as e:
348 if not util.wait_for_read(self.socket, self.socket.gettimeout()):
349 raise TimeoutError("The read operation timed out") from e
350 else:
351 return self.recv_into(*args, **kwargs)
352
353 # TLS 1.3 post-handshake authentication
354 except OpenSSL.SSL.Error as e:
355 raise ssl.SSLError(f"read error: {e!r}") from e
356
357 def settimeout(self, timeout: float) -> None:
358 return self.socket.settimeout(timeout)
359
360 def _send_until_done(self, data: bytes) -> int:
361 while True:
362 try:
363 return self.connection.send(data) # type: ignore[no-any-return]
364 except OpenSSL.SSL.WantWriteError as e:
365 if not util.wait_for_write(self.socket, self.socket.gettimeout()):
366 raise TimeoutError() from e
367 continue
368 except OpenSSL.SSL.SysCallError as e:
369 raise OSError(e.args[0], str(e)) from e
370
371 def sendall(self, data: bytes) -> None:
372 total_sent = 0
373 while total_sent < len(data):
374 sent = self._send_until_done(
375 data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE]
376 )
377 total_sent += sent
378
379 def shutdown(self, how: int) -> None:
380 try:
381 self.connection.shutdown()
382 except OpenSSL.SSL.Error as e:
383 raise ssl.SSLError(f"shutdown error: {e!r}") from e
384
385 def close(self) -> None:
386 self._closed = True
387 if self._io_refs <= 0:
388 self._real_close()
389
390 def _real_close(self) -> None:
391 try:
392 return self.connection.close() # type: ignore[no-any-return]
393 except OpenSSL.SSL.Error:
394 return
395
396 def getpeercert(
397 self, binary_form: bool = False
398 ) -> dict[str, list[typing.Any]] | None:
399 x509 = self.connection.get_peer_certificate()
400
401 if not x509:
402 return x509 # type: ignore[no-any-return]
403
404 if binary_form:
405 return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) # type: ignore[no-any-return]
406
407 return {
•408 "subject": ((("commonName", _get_common_name(x509)),),), # type: ignore[dict-item]
409 "subjectAltName": get_subj_alt_name(x509),
410 }
411
412 def version(self) -> str:
413 return self.connection.get_protocol_version_name() # type: ignore[no-any-return]
414
415 def selected_alpn_protocol(self) -> str | None:
416 alpn_proto = self.connection.get_alpn_proto_negotiated()
417 return alpn_proto.decode() if alpn_proto else None
418
419
420 WrappedSocket.makefile = socket_cls.makefile # type: ignore[attr-defined]
421
422
423 class PyOpenSSLContext:
424 """
425 I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible
426 for translating the interface of the standard library ``SSLContext`` object
427 to calls into PyOpenSSL.
428 """
429
430 def __init__(self, protocol: int) -> None:
431 self.protocol = _openssl_versions[protocol]
432 self._ctx = OpenSSL.SSL.Context(self.protocol)
433 self._options = 0
434 self.check_hostname = False
435 self._minimum_version: int = ssl.TLSVersion.MINIMUM_SUPPORTED
436 self._maximum_version: int = ssl.TLSVersion.MAXIMUM_SUPPORTED
437 self._verify_flags: int = ssl.VERIFY_X509_TRUSTED_FIRST
438
439 @property
440 def options(self) -> int:
441 return self._options
442
443 @options.setter
444 def options(self, value: int) -> None:
445 self._options = value
446 self._set_ctx_options()
447
448 @property
449 def verify_flags(self) -> int:
450 return self._verify_flags
451
452 @verify_flags.setter
453 def verify_flags(self, value: int) -> None:
454 self._verify_flags = value
455 self._ctx.get_cert_store().set_flags(self._verify_flags)
456
457 @property
458 def verify_mode(self) -> int:
459 return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]
460
461 @verify_mode.setter
462 def verify_mode(self, value: ssl.VerifyMode) -> None:
463 self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback)
464
465 def set_default_verify_paths(self) -> None:
466 self._ctx.set_default_verify_paths()
467
468 def set_ciphers(self, ciphers: bytes | str) -> None:
469 if isinstance(ciphers, str):
470 ciphers = ciphers.encode("utf-8")
471 self._ctx.set_cipher_list(ciphers)
472
473 def load_verify_locations(
474 self,
475 cafile: str | None = None,
476 capath: str | None = None,
477 cadata: bytes | None = None,
478 ) -> None:
479 if cafile is not None:
480 cafile = cafile.encode("utf-8") # type: ignore[assignment]
481 if capath is not None:
482 capath = capath.encode("utf-8") # type: ignore[assignment]
483 try:
484 self._ctx.load_verify_locations(cafile, capath)
485 if cadata is not None:
486 self._ctx.load_verify_locations(BytesIO(cadata))
487 except OpenSSL.SSL.Error as e:
488 raise ssl.SSLError(f"unable to load trusted certificates: {e!r}") from e
489
490 def load_cert_chain(
491 self,
492 certfile: str,
493 keyfile: str | None = None,
•494 password: str | bytes | None = None,
495 ) -> None:
496 try:
497 self._ctx.use_certificate_chain_file(certfile)
498 if password is not None:
499 if not isinstance(password, bytes):
•500 password = password.encode("utf-8")
501 # pyOpenSSL added cryptography-key support in 24.3.0.
502 # Keep using the older password-callback path until 2026's
503 # versions because set_passwd_cb() became deprecated in 26.3.0.
504 if int(OpenSSL.__version__.split(".")[0]) >= 26:
505 with open(keyfile or certfile, "rb") as key_file:
506 private_key = load_pem_private_key(key_file.read(), password)
507 # cryptography's loader returns a wider private-key union
508 # than pyOpenSSL accepts, so we add `type: ignore` here.
509 self._ctx.use_privatekey(private_key) # type: ignore[arg-type]
510 else:
511 self._ctx.set_passwd_cb(lambda *_: password)
512 self._ctx.use_privatekey_file(keyfile or certfile)
513 else:
514 self._ctx.use_privatekey_file(keyfile or certfile)
515 except (OpenSSL.SSL.Error, TypeError, ValueError) as e:
516 raise ssl.SSLError(f"Unable to load certificate chain: {e!r}") from e
517
518 def set_alpn_protocols(self, protocols: list[bytes | str]) -> None:
519 protocols = [util.util.to_bytes(p, "ascii") for p in protocols]
520 return self._ctx.set_alpn_protos(protocols) # type: ignore[no-any-return]
521
522 def wrap_socket(
523 self,
524 sock: socket_cls,
525 server_side: bool = False,
526 do_handshake_on_connect: bool = True,
527 suppress_ragged_eofs: bool = True,
528 server_hostname: bytes | str | None = None,
529 ) -> WrappedSocket:
530 cnx = OpenSSL.SSL.Connection(self._ctx, sock)
531
532 # If server_hostname is an IP, don't use it for SNI, per RFC6066 Section 3
533 if server_hostname and not util.ssl_.is_ipaddress(server_hostname):
534 if isinstance(server_hostname, str):
535 server_hostname = server_hostname.encode("utf-8")
536 cnx.set_tlsext_host_name(server_hostname)
537
538 cnx.set_connect_state()
539
540 while True:
541 try:
542 cnx.do_handshake()
543 except OpenSSL.SSL.WantReadError as e:
544 if not util.wait_for_read(sock, sock.gettimeout()):
545 raise TimeoutError("select timed out") from e
546 continue
547 except OpenSSL.SSL.Error as e:
548 raise ssl.SSLError(f"bad handshake: {e!r}") from e
549 break
550
551 return WrappedSocket(cnx, sock)
552
553 def _set_ctx_options(self) -> None:
554 self._ctx.set_options(
555 self._options
556 | _openssl_to_ssl_minimum_version[self._minimum_version]
557 | _openssl_to_ssl_maximum_version[self._maximum_version]
558 )
559
560 @property
561 def minimum_version(self) -> int:
562 return self._minimum_version
563
564 @minimum_version.setter
565 def minimum_version(self, minimum_version: int) -> None:
566 self._minimum_version = minimum_version
567 self._set_ctx_options()
568
569 @property
570 def maximum_version(self) -> int:
571 return self._maximum_version
572
573 @maximum_version.setter
574 def maximum_version(self, maximum_version: int) -> None:
575 self._maximum_version = maximum_version
576 self._set_ctx_options()
577
578
579 def _verify_callback(
580 cnx: OpenSSL.SSL.Connection,
581 x509: X509,
582 err_no: int,
583 err_depth: int,
584 return_code: int,
585 ) -> bool:
586 return err_no == 0