-
-
Notifications
You must be signed in to change notification settings - Fork 98
Add TLSSocket abstraction for uniform SSL/TLS handling
#799
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| [mypy] | ||
| python_version = 3.8 | ||
| python_version = 3.9 | ||
| color_output = true | ||
| error_summary = true | ||
| files = | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,5 @@ | ||
| """Utilities to manage open connections.""" | ||
|
|
||
| import io | ||
| import os | ||
| import selectors | ||
| import socket | ||
|
|
@@ -10,7 +9,6 @@ | |
|
|
||
| from . import errors | ||
| from ._compat import IS_WINDOWS | ||
| from .makefile import MakeFile | ||
|
|
||
|
|
||
| try: | ||
|
|
@@ -293,50 +291,22 @@ def _from_server_socket(self, server_socket): # noqa: C901 # FIXME | |
| if hasattr(s, 'settimeout'): | ||
| s.settimeout(self.server.timeout) | ||
|
|
||
| mf = MakeFile | ||
| ssl_env = {} | ||
|
|
||
| # if ssl cert and key are set, we try to be a secure HTTP server | ||
| if self.server.ssl_adapter is not None: | ||
| try: | ||
| s, ssl_env = self.server.ssl_adapter.wrap(s) | ||
| except errors.FatalSSLAlert as tls_connection_drop_error: | ||
| self.server.error_log( | ||
| f'Client {addr!s} lost — peer dropped the TLS ' | ||
| 'connection suddenly, during handshake: ' | ||
| f'{tls_connection_drop_error!s}', | ||
| ) | ||
| return None | ||
| except errors.NoSSLError as http_over_https_err: | ||
| except errors.FatalSSLAlert as tls_connection_error: | ||
| self.server.error_log( | ||
| f'Client {addr!s} attempted to speak plain HTTP into ' | ||
| 'a TCP connection configured for TLS-only traffic — ' | ||
| 'trying to send back a plain HTTP error response: ' | ||
| f'{http_over_https_err!s}', | ||
| f'Failed to establish SSL connection with {addr!s}: ' | ||
| f'{tls_connection_error!s}', | ||
| ) | ||
| msg = ( | ||
| 'The client sent a plain HTTP request, but ' | ||
| 'this server only speaks HTTPS on this port.' | ||
| ) | ||
| buf = [ | ||
| '%s 400 Bad Request\r\n' % self.server.protocol, | ||
| 'Content-Length: %s\r\n' % len(msg), | ||
| 'Content-Type: text/plain\r\n\r\n', | ||
| msg, | ||
| ] | ||
|
|
||
| wfile = mf(s, 'wb', io.DEFAULT_BUFFER_SIZE) | ||
| try: | ||
| wfile.write(''.join(buf).encode('ISO-8859-1')) | ||
| except OSError as ex: | ||
| if ex.args[0] not in errors.socket_errors_to_ignore: | ||
| raise | ||
| return None | ||
| mf = self.server.ssl_adapter.makefile | ||
| # Re-apply our timeout since we may have a new socket object | ||
| if hasattr(s, 'settimeout'): | ||
| s.settimeout(self.server.timeout) | ||
| except errors.NoSSLError: | ||
| return self._send_bad_request_plain_http_error(s, addr) | ||
|
|
||
| conn = self.server.ConnectionClass(self.server, s, mf) | ||
| conn = self.server.ConnectionClass(self.server, s) | ||
|
|
||
| if not isinstance(self.server.bind_addr, (str, bytes)): | ||
| # optional values | ||
|
|
@@ -381,6 +351,43 @@ def _from_server_socket(self, server_socket): # noqa: C901 # FIXME | |
| return None | ||
| raise | ||
|
|
||
| def _send_bad_request_plain_http_error(self, sock, addr): | ||
| """Send Bad Request 400 response, and close the socket.""" | ||
| self.server.error_log( | ||
| f'Client {addr!s} attempted to speak plain HTTP into ' | ||
| 'a TCP connection configured for TLS-only traffic — ' | ||
| 'Sending 400 Bad Request.', | ||
| ) | ||
|
|
||
| msg = ( | ||
| 'The client sent a plain HTTP request, but this server ' | ||
| 'only speaks HTTPS on this port.' | ||
| ) | ||
|
|
||
| response_parts = [ | ||
| f'{self.server.protocol} 400 Bad Request\r\n', | ||
| 'Content-Type: text/plain\r\n', | ||
| f'Content-Length: {len(msg)}\r\n', | ||
| 'Connection: close\r\n', | ||
| '\r\n', | ||
| msg, | ||
| ] | ||
| response_bytes = ''.join(response_parts).encode('ISO-8859-1') | ||
|
|
||
| try: | ||
| # Handle both raw sockets and SSL connections | ||
| if hasattr(sock, 'sendall'): | ||
| sock.sendall(response_bytes) | ||
| else: | ||
| # Fallback for older PyOpenSSL or SSL objects | ||
| sock.send(response_bytes) | ||
| sock.shutdown(socket.SHUT_WR) | ||
| except OSError as ex: | ||
| if ex.args[0] not in errors.socket_errors_to_ignore: | ||
| raise | ||
|
|
||
| sock.close() | ||
|
|
||
|
Comment on lines
+354
to
+390
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This method (or a simplified/standalone variant) could go into a separate PR so that we'd accept it earlier and have a smaller patch here.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sure. Will do. |
||
| def close(self): | ||
| """Close all monitored connections.""" | ||
| for _, conn in self._selector.connections: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,6 +2,7 @@ | |
|
|
||
| # prefer slower Python-based io module | ||
| import _pyio as io | ||
| import io as stdlib_io | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is this needed? |
||
| import socket | ||
|
|
||
|
|
||
|
|
@@ -38,9 +39,16 @@ def _flush_unlocked(self): | |
| class StreamReader(io.BufferedReader): | ||
| """Socket stream reader.""" | ||
|
|
||
| def __init__(self, sock, mode='r', bufsize=io.DEFAULT_BUFFER_SIZE): | ||
| """Initialize socket stream reader.""" | ||
| super().__init__(socket.SocketIO(sock, mode), bufsize) | ||
| def __init__(self, sock, bufsize=io.DEFAULT_BUFFER_SIZE): | ||
| """Initialize with socket or raw IO object.""" | ||
| # If already a RawIOBase (like TLSSocket), use directly | ||
| if isinstance(sock, (io.RawIOBase, stdlib_io.RawIOBase)): | ||
| raw_io = sock | ||
| else: | ||
| # Wrap raw socket with SocketIO | ||
| raw_io = socket.SocketIO(sock, 'rb') | ||
|
|
||
| super().__init__(raw_io, bufsize) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is still checking obscure properties of objects to infer TLS relation. We shouldn't be relying on whether something is TLS or not in here. This is an abstraction leak no matter the method of checking. |
||
| self.bytes_read = 0 | ||
|
|
||
| def read(self, *args, **kwargs): | ||
|
|
@@ -57,19 +65,20 @@ def has_data(self): | |
| class StreamWriter(BufferedWriter): | ||
| """Socket stream writer.""" | ||
|
|
||
| def __init__(self, sock, mode='w', bufsize=io.DEFAULT_BUFFER_SIZE): | ||
| """Initialize socket stream writer.""" | ||
| super().__init__(socket.SocketIO(sock, mode), bufsize) | ||
| def __init__(self, sock, bufsize=io.DEFAULT_BUFFER_SIZE): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Removing arguments or changing their order is a backwards incompatible change. We should avoid those and at least have a deprecation period to allow for downstream adoption. Deprecations would have to be dedicated multi-stage coordinated processes. |
||
| """Initialize with socket or raw IO object.""" | ||
| # If already a RawIOBase (like TLSSocket), use directly | ||
| if isinstance(sock, (io.RawIOBase, stdlib_io.RawIOBase)): | ||
| raw_io = sock | ||
| else: | ||
| # Wrap raw socket with SocketIO | ||
| raw_io = socket.SocketIO(sock, 'wb') | ||
|
|
||
| super().__init__(raw_io, bufsize) | ||
| self.bytes_written = 0 | ||
|
|
||
| def write(self, val, *args, **kwargs): | ||
| """Capture bytes written.""" | ||
| res = super().write(val, *args, **kwargs) | ||
| self.bytes_written += len(val) | ||
| return res | ||
|
|
||
|
|
||
| def MakeFile(sock, mode='r', bufsize=io.DEFAULT_BUFFER_SIZE): | ||
| """File object attached to a socket object.""" | ||
| cls = StreamReader if 'r' in mode else StreamWriter | ||
| return cls(sock, mode, bufsize) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -83,7 +83,7 @@ | |
|
|
||
| from . import __version__, connections, errors | ||
| from ._compat import IS_PPC, bton | ||
| from .makefile import MakeFile, StreamWriter | ||
| from .makefile import StreamReader, StreamWriter | ||
| from .workers import threadpool | ||
|
|
||
|
|
||
|
|
@@ -1275,19 +1275,18 @@ class HTTPConnection: | |
| # Fields set by ConnectionManager. | ||
| last_used = None | ||
|
|
||
| def __init__(self, server, sock, makefile=MakeFile): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We'll probably have to keep this for a while (with a sentinel default). And issue a warning when the value isn't that sentinel. |
||
| def __init__(self, server, sock): | ||
| """Initialize HTTPConnection instance. | ||
|
|
||
| Args: | ||
| server (HTTPServer): web server object receiving this request | ||
| sock (socket._socketobject): the raw socket object (usually | ||
| TCP) for this connection | ||
| makefile (file): a fileobject class for reading from the socket | ||
| """ | ||
| self.server = server | ||
| self.socket = sock | ||
| self.rfile = makefile(sock, 'rb', self.rbufsize) | ||
| self.wfile = makefile(sock, 'wb', self.wbufsize) | ||
| self.rfile = StreamReader(sock, self.rbufsize) | ||
| self.wfile = StreamWriter(sock, self.wbufsize) | ||
| self.requests_seen = 0 | ||
|
|
||
| self.peercreds_enabled = self.server.peercreds_enabled | ||
|
|
@@ -1363,7 +1362,7 @@ def _handle_no_ssl(self, req): | |
| except AttributeError: | ||
| # self.socket is of OpenSSL.SSL.Connection type | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh, look — another abstraction leak to fight.. |
||
| resp_sock = self.socket._socket | ||
| self.wfile = StreamWriter(resp_sock, 'wb', self.wbufsize) | ||
| self.wfile = StreamWriter(resp_sock, self.wbufsize) | ||
| msg = ( | ||
| 'The client sent a plain HTTP request, but ' | ||
| 'this server only speaks HTTPS on this port.' | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This would have to go into a separate PR and be coupled with changes to the core packaging metadata, linting configuration, dev env and CI setup.