| 1 | n/a | import collections |
|---|
| 2 | n/a | import warnings |
|---|
| 3 | n/a | try: |
|---|
| 4 | n/a | import ssl |
|---|
| 5 | n/a | except ImportError: # pragma: no cover |
|---|
| 6 | n/a | ssl = None |
|---|
| 7 | n/a | |
|---|
| 8 | n/a | from . import base_events |
|---|
| 9 | n/a | from . import compat |
|---|
| 10 | n/a | from . import protocols |
|---|
| 11 | n/a | from . import transports |
|---|
| 12 | n/a | from .log import logger |
|---|
| 13 | n/a | |
|---|
| 14 | n/a | |
|---|
| 15 | n/a | def _create_transport_context(server_side, server_hostname): |
|---|
| 16 | n/a | if server_side: |
|---|
| 17 | n/a | raise ValueError('Server side SSL needs a valid SSLContext') |
|---|
| 18 | n/a | |
|---|
| 19 | n/a | # Client side may pass ssl=True to use a default |
|---|
| 20 | n/a | # context; in that case the sslcontext passed is None. |
|---|
| 21 | n/a | # The default is secure for client connections. |
|---|
| 22 | n/a | if hasattr(ssl, 'create_default_context'): |
|---|
| 23 | n/a | # Python 3.4+: use up-to-date strong settings. |
|---|
| 24 | n/a | sslcontext = ssl.create_default_context() |
|---|
| 25 | n/a | if not server_hostname: |
|---|
| 26 | n/a | sslcontext.check_hostname = False |
|---|
| 27 | n/a | else: |
|---|
| 28 | n/a | # Fallback for Python 3.3. |
|---|
| 29 | n/a | sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 30 | n/a | sslcontext.options |= ssl.OP_NO_SSLv2 |
|---|
| 31 | n/a | sslcontext.options |= ssl.OP_NO_SSLv3 |
|---|
| 32 | n/a | sslcontext.set_default_verify_paths() |
|---|
| 33 | n/a | sslcontext.verify_mode = ssl.CERT_REQUIRED |
|---|
| 34 | n/a | return sslcontext |
|---|
| 35 | n/a | |
|---|
| 36 | n/a | |
|---|
| 37 | n/a | def _is_sslproto_available(): |
|---|
| 38 | n/a | return hasattr(ssl, "MemoryBIO") |
|---|
| 39 | n/a | |
|---|
| 40 | n/a | |
|---|
| 41 | n/a | # States of an _SSLPipe. |
|---|
| 42 | n/a | _UNWRAPPED = "UNWRAPPED" |
|---|
| 43 | n/a | _DO_HANDSHAKE = "DO_HANDSHAKE" |
|---|
| 44 | n/a | _WRAPPED = "WRAPPED" |
|---|
| 45 | n/a | _SHUTDOWN = "SHUTDOWN" |
|---|
| 46 | n/a | |
|---|
| 47 | n/a | |
|---|
| 48 | n/a | class _SSLPipe(object): |
|---|
| 49 | n/a | """An SSL "Pipe". |
|---|
| 50 | n/a | |
|---|
| 51 | n/a | An SSL pipe allows you to communicate with an SSL/TLS protocol instance |
|---|
| 52 | n/a | through memory buffers. It can be used to implement a security layer for an |
|---|
| 53 | n/a | existing connection where you don't have access to the connection's file |
|---|
| 54 | n/a | descriptor, or for some reason you don't want to use it. |
|---|
| 55 | n/a | |
|---|
| 56 | n/a | An SSL pipe can be in "wrapped" and "unwrapped" mode. In unwrapped mode, |
|---|
| 57 | n/a | data is passed through untransformed. In wrapped mode, application level |
|---|
| 58 | n/a | data is encrypted to SSL record level data and vice versa. The SSL record |
|---|
| 59 | n/a | level is the lowest level in the SSL protocol suite and is what travels |
|---|
| 60 | n/a | as-is over the wire. |
|---|
| 61 | n/a | |
|---|
| 62 | n/a | An SslPipe initially is in "unwrapped" mode. To start SSL, call |
|---|
| 63 | n/a | do_handshake(). To shutdown SSL again, call unwrap(). |
|---|
| 64 | n/a | """ |
|---|
| 65 | n/a | |
|---|
| 66 | n/a | max_size = 256 * 1024 # Buffer size passed to read() |
|---|
| 67 | n/a | |
|---|
| 68 | n/a | def __init__(self, context, server_side, server_hostname=None): |
|---|
| 69 | n/a | """ |
|---|
| 70 | n/a | The *context* argument specifies the ssl.SSLContext to use. |
|---|
| 71 | n/a | |
|---|
| 72 | n/a | The *server_side* argument indicates whether this is a server side or |
|---|
| 73 | n/a | client side transport. |
|---|
| 74 | n/a | |
|---|
| 75 | n/a | The optional *server_hostname* argument can be used to specify the |
|---|
| 76 | n/a | hostname you are connecting to. You may only specify this parameter if |
|---|
| 77 | n/a | the _ssl module supports Server Name Indication (SNI). |
|---|
| 78 | n/a | """ |
|---|
| 79 | n/a | self._context = context |
|---|
| 80 | n/a | self._server_side = server_side |
|---|
| 81 | n/a | self._server_hostname = server_hostname |
|---|
| 82 | n/a | self._state = _UNWRAPPED |
|---|
| 83 | n/a | self._incoming = ssl.MemoryBIO() |
|---|
| 84 | n/a | self._outgoing = ssl.MemoryBIO() |
|---|
| 85 | n/a | self._sslobj = None |
|---|
| 86 | n/a | self._need_ssldata = False |
|---|
| 87 | n/a | self._handshake_cb = None |
|---|
| 88 | n/a | self._shutdown_cb = None |
|---|
| 89 | n/a | |
|---|
| 90 | n/a | @property |
|---|
| 91 | n/a | def context(self): |
|---|
| 92 | n/a | """The SSL context passed to the constructor.""" |
|---|
| 93 | n/a | return self._context |
|---|
| 94 | n/a | |
|---|
| 95 | n/a | @property |
|---|
| 96 | n/a | def ssl_object(self): |
|---|
| 97 | n/a | """The internal ssl.SSLObject instance. |
|---|
| 98 | n/a | |
|---|
| 99 | n/a | Return None if the pipe is not wrapped. |
|---|
| 100 | n/a | """ |
|---|
| 101 | n/a | return self._sslobj |
|---|
| 102 | n/a | |
|---|
| 103 | n/a | @property |
|---|
| 104 | n/a | def need_ssldata(self): |
|---|
| 105 | n/a | """Whether more record level data is needed to complete a handshake |
|---|
| 106 | n/a | that is currently in progress.""" |
|---|
| 107 | n/a | return self._need_ssldata |
|---|
| 108 | n/a | |
|---|
| 109 | n/a | @property |
|---|
| 110 | n/a | def wrapped(self): |
|---|
| 111 | n/a | """ |
|---|
| 112 | n/a | Whether a security layer is currently in effect. |
|---|
| 113 | n/a | |
|---|
| 114 | n/a | Return False during handshake. |
|---|
| 115 | n/a | """ |
|---|
| 116 | n/a | return self._state == _WRAPPED |
|---|
| 117 | n/a | |
|---|
| 118 | n/a | def do_handshake(self, callback=None): |
|---|
| 119 | n/a | """Start the SSL handshake. |
|---|
| 120 | n/a | |
|---|
| 121 | n/a | Return a list of ssldata. A ssldata element is a list of buffers |
|---|
| 122 | n/a | |
|---|
| 123 | n/a | The optional *callback* argument can be used to install a callback that |
|---|
| 124 | n/a | will be called when the handshake is complete. The callback will be |
|---|
| 125 | n/a | called with None if successful, else an exception instance. |
|---|
| 126 | n/a | """ |
|---|
| 127 | n/a | if self._state != _UNWRAPPED: |
|---|
| 128 | n/a | raise RuntimeError('handshake in progress or completed') |
|---|
| 129 | n/a | self._sslobj = self._context.wrap_bio( |
|---|
| 130 | n/a | self._incoming, self._outgoing, |
|---|
| 131 | n/a | server_side=self._server_side, |
|---|
| 132 | n/a | server_hostname=self._server_hostname) |
|---|
| 133 | n/a | self._state = _DO_HANDSHAKE |
|---|
| 134 | n/a | self._handshake_cb = callback |
|---|
| 135 | n/a | ssldata, appdata = self.feed_ssldata(b'', only_handshake=True) |
|---|
| 136 | n/a | assert len(appdata) == 0 |
|---|
| 137 | n/a | return ssldata |
|---|
| 138 | n/a | |
|---|
| 139 | n/a | def shutdown(self, callback=None): |
|---|
| 140 | n/a | """Start the SSL shutdown sequence. |
|---|
| 141 | n/a | |
|---|
| 142 | n/a | Return a list of ssldata. A ssldata element is a list of buffers |
|---|
| 143 | n/a | |
|---|
| 144 | n/a | The optional *callback* argument can be used to install a callback that |
|---|
| 145 | n/a | will be called when the shutdown is complete. The callback will be |
|---|
| 146 | n/a | called without arguments. |
|---|
| 147 | n/a | """ |
|---|
| 148 | n/a | if self._state == _UNWRAPPED: |
|---|
| 149 | n/a | raise RuntimeError('no security layer present') |
|---|
| 150 | n/a | if self._state == _SHUTDOWN: |
|---|
| 151 | n/a | raise RuntimeError('shutdown in progress') |
|---|
| 152 | n/a | assert self._state in (_WRAPPED, _DO_HANDSHAKE) |
|---|
| 153 | n/a | self._state = _SHUTDOWN |
|---|
| 154 | n/a | self._shutdown_cb = callback |
|---|
| 155 | n/a | ssldata, appdata = self.feed_ssldata(b'') |
|---|
| 156 | n/a | assert appdata == [] or appdata == [b''] |
|---|
| 157 | n/a | return ssldata |
|---|
| 158 | n/a | |
|---|
| 159 | n/a | def feed_eof(self): |
|---|
| 160 | n/a | """Send a potentially "ragged" EOF. |
|---|
| 161 | n/a | |
|---|
| 162 | n/a | This method will raise an SSL_ERROR_EOF exception if the EOF is |
|---|
| 163 | n/a | unexpected. |
|---|
| 164 | n/a | """ |
|---|
| 165 | n/a | self._incoming.write_eof() |
|---|
| 166 | n/a | ssldata, appdata = self.feed_ssldata(b'') |
|---|
| 167 | n/a | assert appdata == [] or appdata == [b''] |
|---|
| 168 | n/a | |
|---|
| 169 | n/a | def feed_ssldata(self, data, only_handshake=False): |
|---|
| 170 | n/a | """Feed SSL record level data into the pipe. |
|---|
| 171 | n/a | |
|---|
| 172 | n/a | The data must be a bytes instance. It is OK to send an empty bytes |
|---|
| 173 | n/a | instance. This can be used to get ssldata for a handshake initiated by |
|---|
| 174 | n/a | this endpoint. |
|---|
| 175 | n/a | |
|---|
| 176 | n/a | Return a (ssldata, appdata) tuple. The ssldata element is a list of |
|---|
| 177 | n/a | buffers containing SSL data that needs to be sent to the remote SSL. |
|---|
| 178 | n/a | |
|---|
| 179 | n/a | The appdata element is a list of buffers containing plaintext data that |
|---|
| 180 | n/a | needs to be forwarded to the application. The appdata list may contain |
|---|
| 181 | n/a | an empty buffer indicating an SSL "close_notify" alert. This alert must |
|---|
| 182 | n/a | be acknowledged by calling shutdown(). |
|---|
| 183 | n/a | """ |
|---|
| 184 | n/a | if self._state == _UNWRAPPED: |
|---|
| 185 | n/a | # If unwrapped, pass plaintext data straight through. |
|---|
| 186 | n/a | if data: |
|---|
| 187 | n/a | appdata = [data] |
|---|
| 188 | n/a | else: |
|---|
| 189 | n/a | appdata = [] |
|---|
| 190 | n/a | return ([], appdata) |
|---|
| 191 | n/a | |
|---|
| 192 | n/a | self._need_ssldata = False |
|---|
| 193 | n/a | if data: |
|---|
| 194 | n/a | self._incoming.write(data) |
|---|
| 195 | n/a | |
|---|
| 196 | n/a | ssldata = [] |
|---|
| 197 | n/a | appdata = [] |
|---|
| 198 | n/a | try: |
|---|
| 199 | n/a | if self._state == _DO_HANDSHAKE: |
|---|
| 200 | n/a | # Call do_handshake() until it doesn't raise anymore. |
|---|
| 201 | n/a | self._sslobj.do_handshake() |
|---|
| 202 | n/a | self._state = _WRAPPED |
|---|
| 203 | n/a | if self._handshake_cb: |
|---|
| 204 | n/a | self._handshake_cb(None) |
|---|
| 205 | n/a | if only_handshake: |
|---|
| 206 | n/a | return (ssldata, appdata) |
|---|
| 207 | n/a | # Handshake done: execute the wrapped block |
|---|
| 208 | n/a | |
|---|
| 209 | n/a | if self._state == _WRAPPED: |
|---|
| 210 | n/a | # Main state: read data from SSL until close_notify |
|---|
| 211 | n/a | while True: |
|---|
| 212 | n/a | chunk = self._sslobj.read(self.max_size) |
|---|
| 213 | n/a | appdata.append(chunk) |
|---|
| 214 | n/a | if not chunk: # close_notify |
|---|
| 215 | n/a | break |
|---|
| 216 | n/a | |
|---|
| 217 | n/a | elif self._state == _SHUTDOWN: |
|---|
| 218 | n/a | # Call shutdown() until it doesn't raise anymore. |
|---|
| 219 | n/a | self._sslobj.unwrap() |
|---|
| 220 | n/a | self._sslobj = None |
|---|
| 221 | n/a | self._state = _UNWRAPPED |
|---|
| 222 | n/a | if self._shutdown_cb: |
|---|
| 223 | n/a | self._shutdown_cb() |
|---|
| 224 | n/a | |
|---|
| 225 | n/a | elif self._state == _UNWRAPPED: |
|---|
| 226 | n/a | # Drain possible plaintext data after close_notify. |
|---|
| 227 | n/a | appdata.append(self._incoming.read()) |
|---|
| 228 | n/a | except (ssl.SSLError, ssl.CertificateError) as exc: |
|---|
| 229 | n/a | if getattr(exc, 'errno', None) not in ( |
|---|
| 230 | n/a | ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE, |
|---|
| 231 | n/a | ssl.SSL_ERROR_SYSCALL): |
|---|
| 232 | n/a | if self._state == _DO_HANDSHAKE and self._handshake_cb: |
|---|
| 233 | n/a | self._handshake_cb(exc) |
|---|
| 234 | n/a | raise |
|---|
| 235 | n/a | self._need_ssldata = (exc.errno == ssl.SSL_ERROR_WANT_READ) |
|---|
| 236 | n/a | |
|---|
| 237 | n/a | # Check for record level data that needs to be sent back. |
|---|
| 238 | n/a | # Happens for the initial handshake and renegotiations. |
|---|
| 239 | n/a | if self._outgoing.pending: |
|---|
| 240 | n/a | ssldata.append(self._outgoing.read()) |
|---|
| 241 | n/a | return (ssldata, appdata) |
|---|
| 242 | n/a | |
|---|
| 243 | n/a | def feed_appdata(self, data, offset=0): |
|---|
| 244 | n/a | """Feed plaintext data into the pipe. |
|---|
| 245 | n/a | |
|---|
| 246 | n/a | Return an (ssldata, offset) tuple. The ssldata element is a list of |
|---|
| 247 | n/a | buffers containing record level data that needs to be sent to the |
|---|
| 248 | n/a | remote SSL instance. The offset is the number of plaintext bytes that |
|---|
| 249 | n/a | were processed, which may be less than the length of data. |
|---|
| 250 | n/a | |
|---|
| 251 | n/a | NOTE: In case of short writes, this call MUST be retried with the SAME |
|---|
| 252 | n/a | buffer passed into the *data* argument (i.e. the id() must be the |
|---|
| 253 | n/a | same). This is an OpenSSL requirement. A further particularity is that |
|---|
| 254 | n/a | a short write will always have offset == 0, because the _ssl module |
|---|
| 255 | n/a | does not enable partial writes. And even though the offset is zero, |
|---|
| 256 | n/a | there will still be encrypted data in ssldata. |
|---|
| 257 | n/a | """ |
|---|
| 258 | n/a | assert 0 <= offset <= len(data) |
|---|
| 259 | n/a | if self._state == _UNWRAPPED: |
|---|
| 260 | n/a | # pass through data in unwrapped mode |
|---|
| 261 | n/a | if offset < len(data): |
|---|
| 262 | n/a | ssldata = [data[offset:]] |
|---|
| 263 | n/a | else: |
|---|
| 264 | n/a | ssldata = [] |
|---|
| 265 | n/a | return (ssldata, len(data)) |
|---|
| 266 | n/a | |
|---|
| 267 | n/a | ssldata = [] |
|---|
| 268 | n/a | view = memoryview(data) |
|---|
| 269 | n/a | while True: |
|---|
| 270 | n/a | self._need_ssldata = False |
|---|
| 271 | n/a | try: |
|---|
| 272 | n/a | if offset < len(view): |
|---|
| 273 | n/a | offset += self._sslobj.write(view[offset:]) |
|---|
| 274 | n/a | except ssl.SSLError as exc: |
|---|
| 275 | n/a | # It is not allowed to call write() after unwrap() until the |
|---|
| 276 | n/a | # close_notify is acknowledged. We return the condition to the |
|---|
| 277 | n/a | # caller as a short write. |
|---|
| 278 | n/a | if exc.reason == 'PROTOCOL_IS_SHUTDOWN': |
|---|
| 279 | n/a | exc.errno = ssl.SSL_ERROR_WANT_READ |
|---|
| 280 | n/a | if exc.errno not in (ssl.SSL_ERROR_WANT_READ, |
|---|
| 281 | n/a | ssl.SSL_ERROR_WANT_WRITE, |
|---|
| 282 | n/a | ssl.SSL_ERROR_SYSCALL): |
|---|
| 283 | n/a | raise |
|---|
| 284 | n/a | self._need_ssldata = (exc.errno == ssl.SSL_ERROR_WANT_READ) |
|---|
| 285 | n/a | |
|---|
| 286 | n/a | # See if there's any record level data back for us. |
|---|
| 287 | n/a | if self._outgoing.pending: |
|---|
| 288 | n/a | ssldata.append(self._outgoing.read()) |
|---|
| 289 | n/a | if offset == len(view) or self._need_ssldata: |
|---|
| 290 | n/a | break |
|---|
| 291 | n/a | return (ssldata, offset) |
|---|
| 292 | n/a | |
|---|
| 293 | n/a | |
|---|
| 294 | n/a | class _SSLProtocolTransport(transports._FlowControlMixin, |
|---|
| 295 | n/a | transports.Transport): |
|---|
| 296 | n/a | |
|---|
| 297 | n/a | def __init__(self, loop, ssl_protocol, app_protocol): |
|---|
| 298 | n/a | self._loop = loop |
|---|
| 299 | n/a | # SSLProtocol instance |
|---|
| 300 | n/a | self._ssl_protocol = ssl_protocol |
|---|
| 301 | n/a | self._app_protocol = app_protocol |
|---|
| 302 | n/a | self._closed = False |
|---|
| 303 | n/a | |
|---|
| 304 | n/a | def get_extra_info(self, name, default=None): |
|---|
| 305 | n/a | """Get optional transport information.""" |
|---|
| 306 | n/a | return self._ssl_protocol._get_extra_info(name, default) |
|---|
| 307 | n/a | |
|---|
| 308 | n/a | def set_protocol(self, protocol): |
|---|
| 309 | n/a | self._app_protocol = protocol |
|---|
| 310 | n/a | |
|---|
| 311 | n/a | def get_protocol(self): |
|---|
| 312 | n/a | return self._app_protocol |
|---|
| 313 | n/a | |
|---|
| 314 | n/a | def is_closing(self): |
|---|
| 315 | n/a | return self._closed |
|---|
| 316 | n/a | |
|---|
| 317 | n/a | def close(self): |
|---|
| 318 | n/a | """Close the transport. |
|---|
| 319 | n/a | |
|---|
| 320 | n/a | Buffered data will be flushed asynchronously. No more data |
|---|
| 321 | n/a | will be received. After all buffered data is flushed, the |
|---|
| 322 | n/a | protocol's connection_lost() method will (eventually) called |
|---|
| 323 | n/a | with None as its argument. |
|---|
| 324 | n/a | """ |
|---|
| 325 | n/a | self._closed = True |
|---|
| 326 | n/a | self._ssl_protocol._start_shutdown() |
|---|
| 327 | n/a | |
|---|
| 328 | n/a | # On Python 3.3 and older, objects with a destructor part of a reference |
|---|
| 329 | n/a | # cycle are never destroyed. It's not more the case on Python 3.4 thanks |
|---|
| 330 | n/a | # to the PEP 442. |
|---|
| 331 | n/a | if compat.PY34: |
|---|
| 332 | n/a | def __del__(self): |
|---|
| 333 | n/a | if not self._closed: |
|---|
| 334 | n/a | warnings.warn("unclosed transport %r" % self, ResourceWarning, |
|---|
| 335 | n/a | source=self) |
|---|
| 336 | n/a | self.close() |
|---|
| 337 | n/a | |
|---|
| 338 | n/a | def pause_reading(self): |
|---|
| 339 | n/a | """Pause the receiving end. |
|---|
| 340 | n/a | |
|---|
| 341 | n/a | No data will be passed to the protocol's data_received() |
|---|
| 342 | n/a | method until resume_reading() is called. |
|---|
| 343 | n/a | """ |
|---|
| 344 | n/a | self._ssl_protocol._transport.pause_reading() |
|---|
| 345 | n/a | |
|---|
| 346 | n/a | def resume_reading(self): |
|---|
| 347 | n/a | """Resume the receiving end. |
|---|
| 348 | n/a | |
|---|
| 349 | n/a | Data received will once again be passed to the protocol's |
|---|
| 350 | n/a | data_received() method. |
|---|
| 351 | n/a | """ |
|---|
| 352 | n/a | self._ssl_protocol._transport.resume_reading() |
|---|
| 353 | n/a | |
|---|
| 354 | n/a | def set_write_buffer_limits(self, high=None, low=None): |
|---|
| 355 | n/a | """Set the high- and low-water limits for write flow control. |
|---|
| 356 | n/a | |
|---|
| 357 | n/a | These two values control when to call the protocol's |
|---|
| 358 | n/a | pause_writing() and resume_writing() methods. If specified, |
|---|
| 359 | n/a | the low-water limit must be less than or equal to the |
|---|
| 360 | n/a | high-water limit. Neither value can be negative. |
|---|
| 361 | n/a | |
|---|
| 362 | n/a | The defaults are implementation-specific. If only the |
|---|
| 363 | n/a | high-water limit is given, the low-water limit defaults to an |
|---|
| 364 | n/a | implementation-specific value less than or equal to the |
|---|
| 365 | n/a | high-water limit. Setting high to zero forces low to zero as |
|---|
| 366 | n/a | well, and causes pause_writing() to be called whenever the |
|---|
| 367 | n/a | buffer becomes non-empty. Setting low to zero causes |
|---|
| 368 | n/a | resume_writing() to be called only once the buffer is empty. |
|---|
| 369 | n/a | Use of zero for either limit is generally sub-optimal as it |
|---|
| 370 | n/a | reduces opportunities for doing I/O and computation |
|---|
| 371 | n/a | concurrently. |
|---|
| 372 | n/a | """ |
|---|
| 373 | n/a | self._ssl_protocol._transport.set_write_buffer_limits(high, low) |
|---|
| 374 | n/a | |
|---|
| 375 | n/a | def get_write_buffer_size(self): |
|---|
| 376 | n/a | """Return the current size of the write buffer.""" |
|---|
| 377 | n/a | return self._ssl_protocol._transport.get_write_buffer_size() |
|---|
| 378 | n/a | |
|---|
| 379 | n/a | def write(self, data): |
|---|
| 380 | n/a | """Write some data bytes to the transport. |
|---|
| 381 | n/a | |
|---|
| 382 | n/a | This does not block; it buffers the data and arranges for it |
|---|
| 383 | n/a | to be sent out asynchronously. |
|---|
| 384 | n/a | """ |
|---|
| 385 | n/a | if not isinstance(data, (bytes, bytearray, memoryview)): |
|---|
| 386 | n/a | raise TypeError("data: expecting a bytes-like instance, got {!r}" |
|---|
| 387 | n/a | .format(type(data).__name__)) |
|---|
| 388 | n/a | if not data: |
|---|
| 389 | n/a | return |
|---|
| 390 | n/a | self._ssl_protocol._write_appdata(data) |
|---|
| 391 | n/a | |
|---|
| 392 | n/a | def can_write_eof(self): |
|---|
| 393 | n/a | """Return True if this transport supports write_eof(), False if not.""" |
|---|
| 394 | n/a | return False |
|---|
| 395 | n/a | |
|---|
| 396 | n/a | def abort(self): |
|---|
| 397 | n/a | """Close the transport immediately. |
|---|
| 398 | n/a | |
|---|
| 399 | n/a | Buffered data will be lost. No more data will be received. |
|---|
| 400 | n/a | The protocol's connection_lost() method will (eventually) be |
|---|
| 401 | n/a | called with None as its argument. |
|---|
| 402 | n/a | """ |
|---|
| 403 | n/a | self._ssl_protocol._abort() |
|---|
| 404 | n/a | |
|---|
| 405 | n/a | |
|---|
| 406 | n/a | class SSLProtocol(protocols.Protocol): |
|---|
| 407 | n/a | """SSL protocol. |
|---|
| 408 | n/a | |
|---|
| 409 | n/a | Implementation of SSL on top of a socket using incoming and outgoing |
|---|
| 410 | n/a | buffers which are ssl.MemoryBIO objects. |
|---|
| 411 | n/a | """ |
|---|
| 412 | n/a | |
|---|
| 413 | n/a | def __init__(self, loop, app_protocol, sslcontext, waiter, |
|---|
| 414 | n/a | server_side=False, server_hostname=None, |
|---|
| 415 | n/a | call_connection_made=True): |
|---|
| 416 | n/a | if ssl is None: |
|---|
| 417 | n/a | raise RuntimeError('stdlib ssl module not available') |
|---|
| 418 | n/a | |
|---|
| 419 | n/a | if not sslcontext: |
|---|
| 420 | n/a | sslcontext = _create_transport_context(server_side, server_hostname) |
|---|
| 421 | n/a | |
|---|
| 422 | n/a | self._server_side = server_side |
|---|
| 423 | n/a | if server_hostname and not server_side: |
|---|
| 424 | n/a | self._server_hostname = server_hostname |
|---|
| 425 | n/a | else: |
|---|
| 426 | n/a | self._server_hostname = None |
|---|
| 427 | n/a | self._sslcontext = sslcontext |
|---|
| 428 | n/a | # SSL-specific extra info. More info are set when the handshake |
|---|
| 429 | n/a | # completes. |
|---|
| 430 | n/a | self._extra = dict(sslcontext=sslcontext) |
|---|
| 431 | n/a | |
|---|
| 432 | n/a | # App data write buffering |
|---|
| 433 | n/a | self._write_backlog = collections.deque() |
|---|
| 434 | n/a | self._write_buffer_size = 0 |
|---|
| 435 | n/a | |
|---|
| 436 | n/a | self._waiter = waiter |
|---|
| 437 | n/a | self._loop = loop |
|---|
| 438 | n/a | self._app_protocol = app_protocol |
|---|
| 439 | n/a | self._app_transport = _SSLProtocolTransport(self._loop, |
|---|
| 440 | n/a | self, self._app_protocol) |
|---|
| 441 | n/a | # _SSLPipe instance (None until the connection is made) |
|---|
| 442 | n/a | self._sslpipe = None |
|---|
| 443 | n/a | self._session_established = False |
|---|
| 444 | n/a | self._in_handshake = False |
|---|
| 445 | n/a | self._in_shutdown = False |
|---|
| 446 | n/a | # transport, ex: SelectorSocketTransport |
|---|
| 447 | n/a | self._transport = None |
|---|
| 448 | n/a | self._call_connection_made = call_connection_made |
|---|
| 449 | n/a | |
|---|
| 450 | n/a | def _wakeup_waiter(self, exc=None): |
|---|
| 451 | n/a | if self._waiter is None: |
|---|
| 452 | n/a | return |
|---|
| 453 | n/a | if not self._waiter.cancelled(): |
|---|
| 454 | n/a | if exc is not None: |
|---|
| 455 | n/a | self._waiter.set_exception(exc) |
|---|
| 456 | n/a | else: |
|---|
| 457 | n/a | self._waiter.set_result(None) |
|---|
| 458 | n/a | self._waiter = None |
|---|
| 459 | n/a | |
|---|
| 460 | n/a | def connection_made(self, transport): |
|---|
| 461 | n/a | """Called when the low-level connection is made. |
|---|
| 462 | n/a | |
|---|
| 463 | n/a | Start the SSL handshake. |
|---|
| 464 | n/a | """ |
|---|
| 465 | n/a | self._transport = transport |
|---|
| 466 | n/a | self._sslpipe = _SSLPipe(self._sslcontext, |
|---|
| 467 | n/a | self._server_side, |
|---|
| 468 | n/a | self._server_hostname) |
|---|
| 469 | n/a | self._start_handshake() |
|---|
| 470 | n/a | |
|---|
| 471 | n/a | def connection_lost(self, exc): |
|---|
| 472 | n/a | """Called when the low-level connection is lost or closed. |
|---|
| 473 | n/a | |
|---|
| 474 | n/a | The argument is an exception object or None (the latter |
|---|
| 475 | n/a | meaning a regular EOF is received or the connection was |
|---|
| 476 | n/a | aborted or closed). |
|---|
| 477 | n/a | """ |
|---|
| 478 | n/a | if self._session_established: |
|---|
| 479 | n/a | self._session_established = False |
|---|
| 480 | n/a | self._loop.call_soon(self._app_protocol.connection_lost, exc) |
|---|
| 481 | n/a | self._transport = None |
|---|
| 482 | n/a | self._app_transport = None |
|---|
| 483 | n/a | self._wakeup_waiter(exc) |
|---|
| 484 | n/a | |
|---|
| 485 | n/a | def pause_writing(self): |
|---|
| 486 | n/a | """Called when the low-level transport's buffer goes over |
|---|
| 487 | n/a | the high-water mark. |
|---|
| 488 | n/a | """ |
|---|
| 489 | n/a | self._app_protocol.pause_writing() |
|---|
| 490 | n/a | |
|---|
| 491 | n/a | def resume_writing(self): |
|---|
| 492 | n/a | """Called when the low-level transport's buffer drains below |
|---|
| 493 | n/a | the low-water mark. |
|---|
| 494 | n/a | """ |
|---|
| 495 | n/a | self._app_protocol.resume_writing() |
|---|
| 496 | n/a | |
|---|
| 497 | n/a | def data_received(self, data): |
|---|
| 498 | n/a | """Called when some SSL data is received. |
|---|
| 499 | n/a | |
|---|
| 500 | n/a | The argument is a bytes object. |
|---|
| 501 | n/a | """ |
|---|
| 502 | n/a | try: |
|---|
| 503 | n/a | ssldata, appdata = self._sslpipe.feed_ssldata(data) |
|---|
| 504 | n/a | except ssl.SSLError as e: |
|---|
| 505 | n/a | if self._loop.get_debug(): |
|---|
| 506 | n/a | logger.warning('%r: SSL error %s (reason %s)', |
|---|
| 507 | n/a | self, e.errno, e.reason) |
|---|
| 508 | n/a | self._abort() |
|---|
| 509 | n/a | return |
|---|
| 510 | n/a | |
|---|
| 511 | n/a | for chunk in ssldata: |
|---|
| 512 | n/a | self._transport.write(chunk) |
|---|
| 513 | n/a | |
|---|
| 514 | n/a | for chunk in appdata: |
|---|
| 515 | n/a | if chunk: |
|---|
| 516 | n/a | self._app_protocol.data_received(chunk) |
|---|
| 517 | n/a | else: |
|---|
| 518 | n/a | self._start_shutdown() |
|---|
| 519 | n/a | break |
|---|
| 520 | n/a | |
|---|
| 521 | n/a | def eof_received(self): |
|---|
| 522 | n/a | """Called when the other end of the low-level stream |
|---|
| 523 | n/a | is half-closed. |
|---|
| 524 | n/a | |
|---|
| 525 | n/a | If this returns a false value (including None), the transport |
|---|
| 526 | n/a | will close itself. If it returns a true value, closing the |
|---|
| 527 | n/a | transport is up to the protocol. |
|---|
| 528 | n/a | """ |
|---|
| 529 | n/a | try: |
|---|
| 530 | n/a | if self._loop.get_debug(): |
|---|
| 531 | n/a | logger.debug("%r received EOF", self) |
|---|
| 532 | n/a | |
|---|
| 533 | n/a | self._wakeup_waiter(ConnectionResetError) |
|---|
| 534 | n/a | |
|---|
| 535 | n/a | if not self._in_handshake: |
|---|
| 536 | n/a | keep_open = self._app_protocol.eof_received() |
|---|
| 537 | n/a | if keep_open: |
|---|
| 538 | n/a | logger.warning('returning true from eof_received() ' |
|---|
| 539 | n/a | 'has no effect when using ssl') |
|---|
| 540 | n/a | finally: |
|---|
| 541 | n/a | self._transport.close() |
|---|
| 542 | n/a | |
|---|
| 543 | n/a | def _get_extra_info(self, name, default=None): |
|---|
| 544 | n/a | if name in self._extra: |
|---|
| 545 | n/a | return self._extra[name] |
|---|
| 546 | n/a | else: |
|---|
| 547 | n/a | return self._transport.get_extra_info(name, default) |
|---|
| 548 | n/a | |
|---|
| 549 | n/a | def _start_shutdown(self): |
|---|
| 550 | n/a | if self._in_shutdown: |
|---|
| 551 | n/a | return |
|---|
| 552 | n/a | self._in_shutdown = True |
|---|
| 553 | n/a | self._write_appdata(b'') |
|---|
| 554 | n/a | |
|---|
| 555 | n/a | def _write_appdata(self, data): |
|---|
| 556 | n/a | self._write_backlog.append((data, 0)) |
|---|
| 557 | n/a | self._write_buffer_size += len(data) |
|---|
| 558 | n/a | self._process_write_backlog() |
|---|
| 559 | n/a | |
|---|
| 560 | n/a | def _start_handshake(self): |
|---|
| 561 | n/a | if self._loop.get_debug(): |
|---|
| 562 | n/a | logger.debug("%r starts SSL handshake", self) |
|---|
| 563 | n/a | self._handshake_start_time = self._loop.time() |
|---|
| 564 | n/a | else: |
|---|
| 565 | n/a | self._handshake_start_time = None |
|---|
| 566 | n/a | self._in_handshake = True |
|---|
| 567 | n/a | # (b'', 1) is a special value in _process_write_backlog() to do |
|---|
| 568 | n/a | # the SSL handshake |
|---|
| 569 | n/a | self._write_backlog.append((b'', 1)) |
|---|
| 570 | n/a | self._loop.call_soon(self._process_write_backlog) |
|---|
| 571 | n/a | |
|---|
| 572 | n/a | def _on_handshake_complete(self, handshake_exc): |
|---|
| 573 | n/a | self._in_handshake = False |
|---|
| 574 | n/a | |
|---|
| 575 | n/a | sslobj = self._sslpipe.ssl_object |
|---|
| 576 | n/a | try: |
|---|
| 577 | n/a | if handshake_exc is not None: |
|---|
| 578 | n/a | raise handshake_exc |
|---|
| 579 | n/a | |
|---|
| 580 | n/a | peercert = sslobj.getpeercert() |
|---|
| 581 | n/a | if not hasattr(self._sslcontext, 'check_hostname'): |
|---|
| 582 | n/a | # Verify hostname if requested, Python 3.4+ uses check_hostname |
|---|
| 583 | n/a | # and checks the hostname in do_handshake() |
|---|
| 584 | n/a | if (self._server_hostname |
|---|
| 585 | n/a | and self._sslcontext.verify_mode != ssl.CERT_NONE): |
|---|
| 586 | n/a | ssl.match_hostname(peercert, self._server_hostname) |
|---|
| 587 | n/a | except BaseException as exc: |
|---|
| 588 | n/a | if self._loop.get_debug(): |
|---|
| 589 | n/a | if isinstance(exc, ssl.CertificateError): |
|---|
| 590 | n/a | logger.warning("%r: SSL handshake failed " |
|---|
| 591 | n/a | "on verifying the certificate", |
|---|
| 592 | n/a | self, exc_info=True) |
|---|
| 593 | n/a | else: |
|---|
| 594 | n/a | logger.warning("%r: SSL handshake failed", |
|---|
| 595 | n/a | self, exc_info=True) |
|---|
| 596 | n/a | self._transport.close() |
|---|
| 597 | n/a | if isinstance(exc, Exception): |
|---|
| 598 | n/a | self._wakeup_waiter(exc) |
|---|
| 599 | n/a | return |
|---|
| 600 | n/a | else: |
|---|
| 601 | n/a | raise |
|---|
| 602 | n/a | |
|---|
| 603 | n/a | if self._loop.get_debug(): |
|---|
| 604 | n/a | dt = self._loop.time() - self._handshake_start_time |
|---|
| 605 | n/a | logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3) |
|---|
| 606 | n/a | |
|---|
| 607 | n/a | # Add extra info that becomes available after handshake. |
|---|
| 608 | n/a | self._extra.update(peercert=peercert, |
|---|
| 609 | n/a | cipher=sslobj.cipher(), |
|---|
| 610 | n/a | compression=sslobj.compression(), |
|---|
| 611 | n/a | ssl_object=sslobj, |
|---|
| 612 | n/a | ) |
|---|
| 613 | n/a | if self._call_connection_made: |
|---|
| 614 | n/a | self._app_protocol.connection_made(self._app_transport) |
|---|
| 615 | n/a | self._wakeup_waiter() |
|---|
| 616 | n/a | self._session_established = True |
|---|
| 617 | n/a | # In case transport.write() was already called. Don't call |
|---|
| 618 | n/a | # immediately _process_write_backlog(), but schedule it: |
|---|
| 619 | n/a | # _on_handshake_complete() can be called indirectly from |
|---|
| 620 | n/a | # _process_write_backlog(), and _process_write_backlog() is not |
|---|
| 621 | n/a | # reentrant. |
|---|
| 622 | n/a | self._loop.call_soon(self._process_write_backlog) |
|---|
| 623 | n/a | |
|---|
| 624 | n/a | def _process_write_backlog(self): |
|---|
| 625 | n/a | # Try to make progress on the write backlog. |
|---|
| 626 | n/a | if self._transport is None: |
|---|
| 627 | n/a | return |
|---|
| 628 | n/a | |
|---|
| 629 | n/a | try: |
|---|
| 630 | n/a | for i in range(len(self._write_backlog)): |
|---|
| 631 | n/a | data, offset = self._write_backlog[0] |
|---|
| 632 | n/a | if data: |
|---|
| 633 | n/a | ssldata, offset = self._sslpipe.feed_appdata(data, offset) |
|---|
| 634 | n/a | elif offset: |
|---|
| 635 | n/a | ssldata = self._sslpipe.do_handshake( |
|---|
| 636 | n/a | self._on_handshake_complete) |
|---|
| 637 | n/a | offset = 1 |
|---|
| 638 | n/a | else: |
|---|
| 639 | n/a | ssldata = self._sslpipe.shutdown(self._finalize) |
|---|
| 640 | n/a | offset = 1 |
|---|
| 641 | n/a | |
|---|
| 642 | n/a | for chunk in ssldata: |
|---|
| 643 | n/a | self._transport.write(chunk) |
|---|
| 644 | n/a | |
|---|
| 645 | n/a | if offset < len(data): |
|---|
| 646 | n/a | self._write_backlog[0] = (data, offset) |
|---|
| 647 | n/a | # A short write means that a write is blocked on a read |
|---|
| 648 | n/a | # We need to enable reading if it is paused! |
|---|
| 649 | n/a | assert self._sslpipe.need_ssldata |
|---|
| 650 | n/a | if self._transport._paused: |
|---|
| 651 | n/a | self._transport.resume_reading() |
|---|
| 652 | n/a | break |
|---|
| 653 | n/a | |
|---|
| 654 | n/a | # An entire chunk from the backlog was processed. We can |
|---|
| 655 | n/a | # delete it and reduce the outstanding buffer size. |
|---|
| 656 | n/a | del self._write_backlog[0] |
|---|
| 657 | n/a | self._write_buffer_size -= len(data) |
|---|
| 658 | n/a | except BaseException as exc: |
|---|
| 659 | n/a | if self._in_handshake: |
|---|
| 660 | n/a | # BaseExceptions will be re-raised in _on_handshake_complete. |
|---|
| 661 | n/a | self._on_handshake_complete(exc) |
|---|
| 662 | n/a | else: |
|---|
| 663 | n/a | self._fatal_error(exc, 'Fatal error on SSL transport') |
|---|
| 664 | n/a | if not isinstance(exc, Exception): |
|---|
| 665 | n/a | # BaseException |
|---|
| 666 | n/a | raise |
|---|
| 667 | n/a | |
|---|
| 668 | n/a | def _fatal_error(self, exc, message='Fatal error on transport'): |
|---|
| 669 | n/a | # Should be called from exception handler only. |
|---|
| 670 | n/a | if isinstance(exc, base_events._FATAL_ERROR_IGNORE): |
|---|
| 671 | n/a | if self._loop.get_debug(): |
|---|
| 672 | n/a | logger.debug("%r: %s", self, message, exc_info=True) |
|---|
| 673 | n/a | else: |
|---|
| 674 | n/a | self._loop.call_exception_handler({ |
|---|
| 675 | n/a | 'message': message, |
|---|
| 676 | n/a | 'exception': exc, |
|---|
| 677 | n/a | 'transport': self._transport, |
|---|
| 678 | n/a | 'protocol': self, |
|---|
| 679 | n/a | }) |
|---|
| 680 | n/a | if self._transport: |
|---|
| 681 | n/a | self._transport._force_close(exc) |
|---|
| 682 | n/a | |
|---|
| 683 | n/a | def _finalize(self): |
|---|
| 684 | n/a | if self._transport is not None: |
|---|
| 685 | n/a | self._transport.close() |
|---|
| 686 | n/a | |
|---|
| 687 | n/a | def _abort(self): |
|---|
| 688 | n/a | if self._transport is not None: |
|---|
| 689 | n/a | try: |
|---|
| 690 | n/a | self._transport.abort() |
|---|
| 691 | n/a | finally: |
|---|
| 692 | n/a | self._finalize() |
|---|