sslproto.py 24 KB

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