_newtls.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. # -*- test-case-name: twisted.test.test_ssl -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. This module implements memory BIO based TLS support. It is the preferred
  6. implementation and will be used whenever pyOpenSSL 0.10 or newer is installed
  7. (whenever L{twisted.protocols.tls} is importable).
  8. @since: 11.1
  9. """
  10. from __future__ import division, absolute_import
  11. from zope.interface import implementer
  12. from zope.interface import directlyProvides
  13. from twisted.internet.interfaces import ITLSTransport, ISSLTransport
  14. from twisted.internet.abstract import FileDescriptor
  15. from twisted.protocols.tls import TLSMemoryBIOFactory, TLSMemoryBIOProtocol
  16. class _BypassTLS(object):
  17. """
  18. L{_BypassTLS} is used as the transport object for the TLS protocol object
  19. used to implement C{startTLS}. Its methods skip any TLS logic which
  20. C{startTLS} enables.
  21. @ivar _base: A transport class L{_BypassTLS} has been mixed in with to which
  22. methods will be forwarded. This class is only responsible for sending
  23. bytes over the connection, not doing TLS.
  24. @ivar _connection: A L{Connection} which TLS has been started on which will
  25. be proxied to by this object. Any method which has its behavior
  26. altered after C{startTLS} will be skipped in favor of the base class's
  27. implementation. This allows the TLS protocol object to have direct
  28. access to the transport, necessary to actually implement TLS.
  29. """
  30. def __init__(self, base, connection):
  31. self._base = base
  32. self._connection = connection
  33. def __getattr__(self, name):
  34. """
  35. Forward any extra attribute access to the original transport object.
  36. For example, this exposes C{getHost}, the behavior of which does not
  37. change after TLS is enabled.
  38. """
  39. return getattr(self._connection, name)
  40. def write(self, data):
  41. """
  42. Write some bytes directly to the connection.
  43. """
  44. return self._base.write(self._connection, data)
  45. def writeSequence(self, iovec):
  46. """
  47. Write a some bytes directly to the connection.
  48. """
  49. return self._base.writeSequence(self._connection, iovec)
  50. def loseConnection(self, *args, **kwargs):
  51. """
  52. Close the underlying connection.
  53. """
  54. return self._base.loseConnection(self._connection, *args, **kwargs)
  55. def registerProducer(self, producer, streaming):
  56. """
  57. Register a producer with the underlying connection.
  58. """
  59. return self._base.registerProducer(self._connection, producer, streaming)
  60. def unregisterProducer(self):
  61. """
  62. Unregister a producer with the underlying connection.
  63. """
  64. return self._base.unregisterProducer(self._connection)
  65. def startTLS(transport, contextFactory, normal, bypass):
  66. """
  67. Add a layer of SSL to a transport.
  68. @param transport: The transport which will be modified. This can either by
  69. a L{FileDescriptor<twisted.internet.abstract.FileDescriptor>} or a
  70. L{FileHandle<twisted.internet.iocpreactor.abstract.FileHandle>}. The
  71. actual requirements of this instance are that it have:
  72. - a C{_tlsClientDefault} attribute indicating whether the transport is
  73. a client (C{True}) or a server (C{False})
  74. - a settable C{TLS} attribute which can be used to mark the fact
  75. that SSL has been started
  76. - settable C{getHandle} and C{getPeerCertificate} attributes so
  77. these L{ISSLTransport} methods can be added to it
  78. - a C{protocol} attribute referring to the L{IProtocol} currently
  79. connected to the transport, which can also be set to a new
  80. L{IProtocol} for the transport to deliver data to
  81. @param contextFactory: An SSL context factory defining SSL parameters for
  82. the new SSL layer.
  83. @type contextFactory: L{twisted.internet.interfaces.IOpenSSLContextFactory}
  84. @param normal: A flag indicating whether SSL will go in the same direction
  85. as the underlying transport goes. That is, if the SSL client will be
  86. the underlying client and the SSL server will be the underlying server.
  87. C{True} means it is the same, C{False} means they are switched.
  88. @type param: L{bool}
  89. @param bypass: A transport base class to call methods on to bypass the new
  90. SSL layer (so that the SSL layer itself can send its bytes).
  91. @type bypass: L{type}
  92. """
  93. # Figure out which direction the SSL goes in. If normal is True,
  94. # we'll go in the direction indicated by the subclass. Otherwise,
  95. # we'll go the other way (client = not normal ^ _tlsClientDefault,
  96. # in other words).
  97. if normal:
  98. client = transport._tlsClientDefault
  99. else:
  100. client = not transport._tlsClientDefault
  101. # If we have a producer, unregister it, and then re-register it below once
  102. # we've switched to TLS mode, so it gets hooked up correctly:
  103. producer, streaming = None, None
  104. if transport.producer is not None:
  105. producer, streaming = transport.producer, transport.streamingProducer
  106. transport.unregisterProducer()
  107. tlsFactory = TLSMemoryBIOFactory(contextFactory, client, None)
  108. tlsProtocol = TLSMemoryBIOProtocol(tlsFactory, transport.protocol, False)
  109. transport.protocol = tlsProtocol
  110. transport.getHandle = tlsProtocol.getHandle
  111. transport.getPeerCertificate = tlsProtocol.getPeerCertificate
  112. # Mark the transport as secure.
  113. directlyProvides(transport, ISSLTransport)
  114. # Remember we did this so that write and writeSequence can send the
  115. # data to the right place.
  116. transport.TLS = True
  117. # Hook it up
  118. transport.protocol.makeConnection(_BypassTLS(bypass, transport))
  119. # Restore producer if necessary:
  120. if producer:
  121. transport.registerProducer(producer, streaming)
  122. @implementer(ITLSTransport)
  123. class ConnectionMixin(object):
  124. """
  125. A mixin for L{twisted.internet.abstract.FileDescriptor} which adds an
  126. L{ITLSTransport} implementation.
  127. @ivar TLS: A flag indicating whether TLS is currently in use on this
  128. transport. This is not a good way for applications to check for TLS,
  129. instead use L{twisted.internet.interfaces.ISSLTransport}.
  130. """
  131. TLS = False
  132. def startTLS(self, ctx, normal=True):
  133. """
  134. @see: L{ITLSTransport.startTLS}
  135. """
  136. startTLS(self, ctx, normal, FileDescriptor)
  137. def write(self, bytes):
  138. """
  139. Write some bytes to this connection, passing them through a TLS layer if
  140. necessary, or discarding them if the connection has already been lost.
  141. """
  142. if self.TLS:
  143. if self.connected:
  144. self.protocol.write(bytes)
  145. else:
  146. FileDescriptor.write(self, bytes)
  147. def writeSequence(self, iovec):
  148. """
  149. Write some bytes to this connection, scatter/gather-style, passing them
  150. through a TLS layer if necessary, or discarding them if the connection
  151. has already been lost.
  152. """
  153. if self.TLS:
  154. if self.connected:
  155. self.protocol.writeSequence(iovec)
  156. else:
  157. FileDescriptor.writeSequence(self, iovec)
  158. def loseConnection(self):
  159. """
  160. Close this connection after writing all pending data.
  161. If TLS has been negotiated, perform a TLS shutdown.
  162. """
  163. if self.TLS:
  164. if self.connected and not self.disconnecting:
  165. self.protocol.loseConnection()
  166. else:
  167. FileDescriptor.loseConnection(self)
  168. def registerProducer(self, producer, streaming):
  169. """
  170. Register a producer.
  171. If TLS is enabled, the TLS connection handles this.
  172. """
  173. if self.TLS:
  174. # Registering a producer before we're connected shouldn't be a
  175. # problem. If we end up with a write(), that's already handled in
  176. # the write() code above, and there are no other potential
  177. # side-effects.
  178. self.protocol.registerProducer(producer, streaming)
  179. else:
  180. FileDescriptor.registerProducer(self, producer, streaming)
  181. def unregisterProducer(self):
  182. """
  183. Unregister a producer.
  184. If TLS is enabled, the TLS connection handles this.
  185. """
  186. if self.TLS:
  187. self.protocol.unregisterProducer()
  188. else:
  189. FileDescriptor.unregisterProducer(self)
  190. class ClientMixin(object):
  191. """
  192. A mixin for L{twisted.internet.tcp.Client} which just marks it as a client
  193. for the purposes of the default TLS handshake.
  194. @ivar _tlsClientDefault: Always C{True}, indicating that this is a client
  195. connection, and by default when TLS is negotiated this class will act as
  196. a TLS client.
  197. """
  198. _tlsClientDefault = True
  199. class ServerMixin(object):
  200. """
  201. A mixin for L{twisted.internet.tcp.Server} which just marks it as a server
  202. for the purposes of the default TLS handshake.
  203. @ivar _tlsClientDefault: Always C{False}, indicating that this is a server
  204. connection, and by default when TLS is negotiated this class will act as
  205. a TLS server.
  206. """
  207. _tlsClientDefault = False