Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ssltransport.py 8.8KB

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