ssltransport.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. from __future__ import annotations
  2. import io
  3. import socket
  4. import ssl
  5. import typing
  6. from ..exceptions import ProxySchemeUnsupported
  7. if typing.TYPE_CHECKING:
  8. from typing_extensions import Self
  9. from .ssl_ import _TYPE_PEER_CERT_RET, _TYPE_PEER_CERT_RET_DICT
  10. _WriteBuffer = typing.Union[bytearray, memoryview]
  11. _ReturnValue = typing.TypeVar("_ReturnValue")
  12. SSL_BLOCKSIZE = 16384
  13. class SSLTransport:
  14. """
  15. The SSLTransport wraps an existing socket and establishes an SSL connection.
  16. Contrary to Python's implementation of SSLSocket, it allows you to chain
  17. multiple TLS connections together. It's particularly useful if you need to
  18. implement TLS within TLS.
  19. The class supports most of the socket API operations.
  20. """
  21. @staticmethod
  22. def _validate_ssl_context_for_tls_in_tls(ssl_context: ssl.SSLContext) -> None:
  23. """
  24. Raises a ProxySchemeUnsupported if the provided ssl_context can't be used
  25. for TLS in TLS.
  26. The only requirement is that the ssl_context provides the 'wrap_bio'
  27. methods.
  28. """
  29. if not hasattr(ssl_context, "wrap_bio"):
  30. raise ProxySchemeUnsupported(
  31. "TLS in TLS requires SSLContext.wrap_bio() which isn't "
  32. "available on non-native SSLContext"
  33. )
  34. def __init__(
  35. self,
  36. socket: socket.socket,
  37. ssl_context: ssl.SSLContext,
  38. server_hostname: str | None = None,
  39. suppress_ragged_eofs: bool = True,
  40. ) -> None:
  41. """
  42. Create an SSLTransport around socket using the provided ssl_context.
  43. """
  44. self.incoming = ssl.MemoryBIO()
  45. self.outgoing = ssl.MemoryBIO()
  46. self.suppress_ragged_eofs = suppress_ragged_eofs
  47. self.socket = socket
  48. self.sslobj = ssl_context.wrap_bio(
  49. self.incoming, self.outgoing, server_hostname=server_hostname
  50. )
  51. # Perform initial handshake.
  52. self._ssl_io_loop(self.sslobj.do_handshake)
  53. def __enter__(self) -> Self:
  54. return self
  55. def __exit__(self, *_: typing.Any) -> None:
  56. self.close()
  57. def fileno(self) -> int:
  58. return self.socket.fileno()
  59. def read(self, len: int = 1024, buffer: typing.Any | None = None) -> int | bytes:
  60. return self._wrap_ssl_read(len, buffer)
  61. def recv(self, buflen: int = 1024, flags: int = 0) -> int | bytes:
  62. if flags != 0:
  63. raise ValueError("non-zero flags not allowed in calls to recv")
  64. return self._wrap_ssl_read(buflen)
  65. def recv_into(
  66. self,
  67. buffer: _WriteBuffer,
  68. nbytes: int | None = None,
  69. flags: int = 0,
  70. ) -> None | int | bytes:
  71. if flags != 0:
  72. raise ValueError("non-zero flags not allowed in calls to recv_into")
  73. if nbytes is None:
  74. nbytes = len(buffer)
  75. return self.read(nbytes, buffer)
  76. def sendall(self, data: bytes, flags: int = 0) -> None:
  77. if flags != 0:
  78. raise ValueError("non-zero flags not allowed in calls to sendall")
  79. count = 0
  80. with memoryview(data) as view, view.cast("B") as byte_view:
  81. amount = len(byte_view)
  82. while count < amount:
  83. v = self.send(byte_view[count:])
  84. count += v
  85. def send(self, data: bytes, flags: int = 0) -> int:
  86. if flags != 0:
  87. raise ValueError("non-zero flags not allowed in calls to send")
  88. return self._ssl_io_loop(self.sslobj.write, data)
  89. def makefile(
  90. self,
  91. mode: str,
  92. buffering: int | None = None,
  93. *,
  94. encoding: str | None = None,
  95. errors: str | None = None,
  96. newline: str | None = None,
  97. ) -> typing.BinaryIO | typing.TextIO | socket.SocketIO:
  98. """
  99. Python's httpclient uses makefile and buffered io when reading HTTP
  100. messages and we need to support it.
  101. This is unfortunately a copy and paste of socket.py makefile with small
  102. changes to point to the socket directly.
  103. """
  104. if not set(mode) <= {"r", "w", "b"}:
  105. raise ValueError(f"invalid mode {mode!r} (only r, w, b allowed)")
  106. writing = "w" in mode
  107. reading = "r" in mode or not writing
  108. assert reading or writing
  109. binary = "b" in mode
  110. rawmode = ""
  111. if reading:
  112. rawmode += "r"
  113. if writing:
  114. rawmode += "w"
  115. raw = socket.SocketIO(self, rawmode) # type: ignore[arg-type]
  116. self.socket._io_refs += 1 # type: ignore[attr-defined]
  117. if buffering is None:
  118. buffering = -1
  119. if buffering < 0:
  120. buffering = io.DEFAULT_BUFFER_SIZE
  121. if buffering == 0:
  122. if not binary:
  123. raise ValueError("unbuffered streams must be binary")
  124. return raw
  125. buffer: typing.BinaryIO
  126. if reading and writing:
  127. buffer = io.BufferedRWPair(raw, raw, buffering) # type: ignore[assignment]
  128. elif reading:
  129. buffer = io.BufferedReader(raw, buffering)
  130. else:
  131. assert writing
  132. buffer = io.BufferedWriter(raw, buffering)
  133. if binary:
  134. return buffer
  135. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  136. text.mode = mode # type: ignore[misc]
  137. return text
  138. def unwrap(self) -> None:
  139. self._ssl_io_loop(self.sslobj.unwrap)
  140. def close(self) -> None:
  141. self.socket.close()
  142. @typing.overload
  143. def getpeercert(
  144. self, binary_form: typing.Literal[False] = ...
  145. ) -> _TYPE_PEER_CERT_RET_DICT | None: ...
  146. @typing.overload
  147. def getpeercert(self, binary_form: typing.Literal[True]) -> bytes | None: ...
  148. def getpeercert(self, binary_form: bool = False) -> _TYPE_PEER_CERT_RET:
  149. return self.sslobj.getpeercert(binary_form) # type: ignore[return-value]
  150. def version(self) -> str | None:
  151. return self.sslobj.version()
  152. def cipher(self) -> tuple[str, str, int] | None:
  153. return self.sslobj.cipher()
  154. def selected_alpn_protocol(self) -> str | None:
  155. return self.sslobj.selected_alpn_protocol()
  156. def shared_ciphers(self) -> list[tuple[str, str, int]] | None:
  157. return self.sslobj.shared_ciphers()
  158. def compression(self) -> str | None:
  159. return self.sslobj.compression()
  160. def settimeout(self, value: float | None) -> None:
  161. self.socket.settimeout(value)
  162. def gettimeout(self) -> float | None:
  163. return self.socket.gettimeout()
  164. def _decref_socketios(self) -> None:
  165. self.socket._decref_socketios() # type: ignore[attr-defined]
  166. def _wrap_ssl_read(self, len: int, buffer: bytearray | None = None) -> int | bytes:
  167. try:
  168. return self._ssl_io_loop(self.sslobj.read, len, buffer)
  169. except ssl.SSLError as e:
  170. if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs:
  171. return 0 # eof, return 0.
  172. else:
  173. raise
  174. # func is sslobj.do_handshake or sslobj.unwrap
  175. @typing.overload
  176. def _ssl_io_loop(self, func: typing.Callable[[], None]) -> None: ...
  177. # func is sslobj.write, arg1 is data
  178. @typing.overload
  179. def _ssl_io_loop(self, func: typing.Callable[[bytes], int], arg1: bytes) -> int: ...
  180. # func is sslobj.read, arg1 is len, arg2 is buffer
  181. @typing.overload
  182. def _ssl_io_loop(
  183. self,
  184. func: typing.Callable[[int, bytearray | None], bytes],
  185. arg1: int,
  186. arg2: bytearray | None,
  187. ) -> bytes: ...
  188. def _ssl_io_loop(
  189. self,
  190. func: typing.Callable[..., _ReturnValue],
  191. arg1: None | bytes | int = None,
  192. arg2: bytearray | None = None,
  193. ) -> _ReturnValue:
  194. """Performs an I/O loop between incoming/outgoing and the socket."""
  195. should_loop = True
  196. ret = None
  197. while should_loop:
  198. errno = None
  199. try:
  200. if arg1 is None and arg2 is None:
  201. ret = func()
  202. elif arg2 is None:
  203. ret = func(arg1)
  204. else:
  205. ret = func(arg1, arg2)
  206. except ssl.SSLError as e:
  207. if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE):
  208. # WANT_READ, and WANT_WRITE are expected, others are not.
  209. raise e
  210. errno = e.errno
  211. buf = self.outgoing.read()
  212. self.socket.sendall(buf)
  213. if errno is None:
  214. should_loop = False
  215. elif errno == ssl.SSL_ERROR_WANT_READ:
  216. buf = self.socket.recv(SSL_BLOCKSIZE)
  217. if buf:
  218. self.incoming.write(buf)
  219. else:
  220. self.incoming.write_eof()
  221. return typing.cast(_ReturnValue, ret)