o b~ @sJdZddlmZmZmZmZmZmZz eeedWney2Z z e e dkr*e ddZ [ wwddl m Z mZmZddlmZddlmZdd lmZmZmZmZmZmZmZmZdd lmZdd lm Z dd l!m"Z"m#Z#dd l$m%Z%eeGdddZ&eeeGddde"Z'eeeGdddZ(Gddde#Z)dS)a Implementation of a TLS transport (L{ISSLTransport}) as an L{IProtocol} layered on top of any L{ITransport} implementation, based on U{OpenSSL}'s memory BIO features. L{TLSMemoryBIOFactory} is a L{WrappingFactory} which wraps protocols created by the factory it wraps with L{TLSMemoryBIOProtocol}. L{TLSMemoryBIOProtocol} intercedes between the underlying transport and the wrapped protocol to implement SSL and TLS. Typical usage of this module looks like this:: from twisted.protocols.tls import TLSMemoryBIOFactory from twisted.internet.protocol import ServerFactory from twisted.internet.ssl import PrivateCertificate from twisted.internet import reactor from someapplication import ApplicationProtocol serverFactory = ServerFactory() serverFactory.protocol = ApplicationProtocol certificate = PrivateCertificate.loadPEM(certPEMData) contextFactory = certificate.options() tlsFactory = TLSMemoryBIOFactory(contextFactory, False, serverFactory) reactor.listenTCP(12345, tlsFactory) reactor.run() This API offers somewhat more flexibility than L{twisted.internet.interfaces.IReactorSSL}; for example, a L{TLSMemoryBIOProtocol} instance can use another instance of L{TLSMemoryBIOProtocol} as its transport, yielding TLS over TLS - useful to implement onion routing. It can also be used to run TLS over unusual transports, such as UNIX sockets and stdio. ) ConnectionContextError TLSv1_METHOD WantReadErrorZeroReturnErrorNz3argument must be an int, or have a fileno() method.z7twisted.protocols.tls requires pyOpenSSL 0.10 or newer.)directlyProvides implementer providedBy) _PullToPush)_setAcceptableProtocols)IHandshakeListenerILoggingContext INegotiatedIOpenSSLClientConnectionCreatorIOpenSSLServerConnectionCreatorIProtocolNegotiationFactory IPushProducer ISystemHandle)CONNECTION_LOST)Protocol)ProtocolWrapperWrappingFactory)Failurec@s4eZdZdZdZddZddZddZd d Zd S) _ProducerMembranea Stand-in for producer registered with a L{TLSMemoryBIOProtocol} transport. Ensures that producer pause/resume events from the undelying transport are coordinated with pause/resume events from the TLS layer. @ivar _producer: The application-layer producer. FcCs ||_dSN) _producer)selfproducerr7/usr/lib/python3/dist-packages/twisted/protocols/tls.py__init__Y z_ProducerMembrane.__init__cCs|jrdSd|_|jdS)zP C{pauseProducing} the underlying producer, if it's not paused. NT)_producerPausedrpauseProducingrrrr r$\z _ProducerMembrane.pauseProducingcCs|jsdSd|_|jdS)zM C{resumeProducing} the underlying producer, if it's paused. NF)r#rresumeProducingr%rrr r'er&z!_ProducerMembrane.resumeProducingcCs|jdS)z C{stopProducing} the underlying producer. There is only a single source for this event, so it's simply passed on. N)r stopProducingr%rrr r(nsz_ProducerMembrane.stopProducingN) __name__ __module__ __qualname____doc__r#r!r$r'r(rrrr rLs  rc@seZdZdZdZdZdZdZdZd1ddZ ddZ d d Z d d Z d dZ ddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zed+d,Zd-d.Zd/d0ZdS)2TLSMemoryBIOProtocola L{TLSMemoryBIOProtocol} is a protocol wrapper which uses OpenSSL via a memory BIO to encrypt bytes written to it before sending them on to the underlying transport and decrypts bytes received from the underlying transport before delivering them to the wrapped protocol. In addition to producer events from the underlying transport, the need to wait for reads before a write can proceed means the L{TLSMemoryBIOProtocol} may also want to pause a producer. Pause/resume events are therefore merged using the L{_ProducerMembrane} wrapper. Non-streaming (pull) producers are supported by wrapping them with L{_PullToPush}. @ivar _tlsConnection: The L{OpenSSL.SSL.Connection} instance which is encrypted and decrypting this connection. @ivar _lostTLSConnection: A flag indicating whether connection loss has already been dealt with (C{True}) or not (C{False}). TLS disconnection is distinct from the underlying connection being lost. @ivar _appSendBuffer: application-level (cleartext) data that is waiting to be transferred to the TLS buffer, but can't be because the TLS connection is handshaking. @type _appSendBuffer: L{list} of L{bytes} @ivar _connectWrapped: A flag indicating whether or not to call C{makeConnection} on the wrapped protocol. This is for the reactor's L{twisted.internet.interfaces.ITLSTransport.startTLS} implementation, since it has a protocol which it has already called C{makeConnection} on, and which has no interest in a new transport. See #3821. @ivar _handshakeDone: A flag indicating whether or not the handshake is known to have completed successfully (C{True}) or not (C{False}). This is used to control error reporting behavior. If the handshake has not completed, the underlying L{OpenSSL.SSL.Error} will be passed to the application's C{connectionLost} method. If it has completed, any unexpected L{OpenSSL.SSL.Error} will be turned into a L{ConnectionLost}. This is weird; however, it is simply an attempt at a faithful re-implementation of the behavior provided by L{twisted.internet.ssl}. @ivar _reason: If an unexpected L{OpenSSL.SSL.Error} occurs which causes the connection to be lost, it is saved here. If appropriate, this may be used as the reason passed to the application protocol's C{connectionLost} method. @ivar _producer: The current producer registered via C{registerProducer}, or L{None} if no producer has been registered or a previous one was unregistered. @ivar _aborted: C{abortConnection} has been called. No further data will be received to the wrapped protocol's C{dataReceived}. @type _aborted: L{bool} NFTcCst|||||_dSr)rr!_connectWrapped)rfactorywrappedProtocolr.rrr r!s zTLSMemoryBIOProtocol.__init__cCs|jS)ai Return the L{OpenSSL.SSL.Connection} object being used to encrypt and decrypt this connection. This is done for the benefit of L{twisted.internet.ssl.Certificate}'s C{peerFromTransport} and C{hostFromTransport} methods only. A different system handle may be returned by future versions of this method. )_tlsConnectionr%rrr getHandles zTLSMemoryBIOProtocol.getHandlecCsb|j||_g|_t|D]}t||qt|||j||j r+t ||| dS)z Connect this wrapper to the given transport and initialize the necessary L{OpenSSL.SSL.Connection} with a memory BIO. N) r/_createConnectionr1_appSendBufferr rrmakeConnectionregisterProtocolr.r_checkHandshakeStatus)r transport interfacerrr r5s      z#TLSMemoryBIOProtocol.makeConnectioncCsx|jrdSz|jWnty|YdSty)|tYdSwd|_t |j r:|j dSdS)a( Ask OpenSSL to proceed with a handshake in progress. Initially, this just sends the ClientHello; after some bytes have been stuffed in to the C{Connection} object by C{dataReceived}, it will then respond to any C{Certificate} or C{KeyExchange} messages. NT) _abortedr1 do_handshaker _flushSendBIOr_tlsShutdownFinishedr_handshakeDoner r r0handshakeCompletedr%rrr r7s    z*TLSMemoryBIOProtocol._checkHandshakeStatuscCs6z|jd}Wn tyYdSw|j|dS)zh Read any bytes out of the send BIO and write them to the underlying transport. N)r1bio_readrr8writerbytesrrr r<s  z"TLSMemoryBIOProtocol._flushSendBIOcCs|jsBz|jd}Wn*tyYn.ty%||dYnty5t}||Yn w|j s?t |||jr| dS)ae Try to receive any application-level bytes which are now available because of a previous write into the receive BIO. This will take care of delivering any application-level bytes which are received to the protocol, as well as handling of the various exceptions which can come from trying to get such bytes. r@N) _lostTLSConnectionr1recvrr _shutdownTLSr=rrr:r dataReceivedr<)rrDfailurerrr _flushReceiveBIOs       z%TLSMemoryBIOProtocol._flushReceiveBIOcCs>|j||js||jsdS|jr||dS)z Deliver any received bytes to the receive BIO and then read and deliver to the application any application-level data which becomes available as a result of this. N)r1 bio_writer>r7r4_unbufferPendingWritesrJrCrrr rH/s  z!TLSMemoryBIOProtocol.dataReceivedcCsDz|j}Wn tyd}Ynw||r |jdSdS)zQ Initiate, or reply to, the shutdown handshake of the TLS layer. FN)r1shutdownrr<r8loseConnection)rshutdownSuccessrrr rGLs z!TLSMemoryBIOProtocol._shutdownTLScCsT|durt|jjdddkrtt}|jdur||_d|_||j dS)a Called when TLS connection has gone away; tell underlying transport to disconnect. @param reason: a L{Failure} whose value is an L{Exception} if we want to report that failure through to the wrapped protocol's C{connectionLost}, or L{None} if the C{reason} that C{connectionLost} should receive should be coming from the underlying transport. @type reason: L{Failure} or L{None} N)zUnexpected EOFT) tuplevalueargsrr_reasonrEr<r8rNrreasonrrr r=`s  z)TLSMemoryBIOProtocol._tlsShutdownFinishedcCsJ|js|j|d|_|jp|}d|_d|_t||d|_dS)z Handle the possible repetition of calls to this method (due to either the underlying transport going away or due to an error at the TLS layer) and make sure the base implementation only gets invoked once. TNF)rEr1 bio_shutdownrJrU connectedrconnectionLostrVrrr rZs    z#TLSMemoryBIOProtocol.connectionLostcCsN|js|jsdS|js|js|d|_|js#|jdur%|dSdSdS)zM Send a TLS close alert and close the underlying connection. NT) disconnectingrYr>r4abortConnectionrrGr%rrr rNs   z#TLSMemoryBIOProtocol.loseConnectioncCs"d|_d|_||jdS)z Tear down TLS state so that if the connection is aborted mid-handshake we don't deliver any further data from the application. TN)r:r[rGr8r\r%rrr r\sz$TLSMemoryBIOProtocol.abortConnectioncCs||_|dS)a, Abort the connection during connection setup, giving a reason that certificate verification failed. @param reason: The reason that the verification failed; reported to the application protocol's C{connectionLost} method. @type reason: L{Failure} N)rUr\rVrrr failVerifications z%TLSMemoryBIOProtocol.failVerificationcCs4t|tr td|jr|jdurdS||dS)z Process the given application bytes and send any resulting TLS traffic which arrives in the send BIO. If C{loseConnection} was called, subsequent calls to C{write} will drop the bytes on the floor. z-Must write bytes to a TLS transport, not str.N) isinstancestr TypeErrorr[r_writerCrrr rBs zTLSMemoryBIOProtocol.writecCs(|j||jdur|jdSdS)z Put the given octets into L{TLSMemoryBIOProtocol._appSendBuffer}, and tell any listening producer that it should pause because we are now buffering. N)r4appendrr$)roctetsrrr _bufferedWrites  z#TLSMemoryBIOProtocol._bufferedWritecCsZ|jg}|_|D]}||q |jrdS|jdur"|jdS|jr+|dSdS)zY Un-buffer all waiting writes in L{TLSMemoryBIOProtocol._appSendBuffer}. N)r4rarr'r[rG)r pendingWrites eachWriterrr rLs    z+TLSMemoryBIOProtocol._unbufferPendingWritescCs|jrdSd}d}|t|krR||||}z|j|}Wn"ty2|||dYdStyA|tYdSw||7}| |t|ksdSdS)a^ Process the given application bytes and send any resulting TLS traffic which arrives in the send BIO. This may be called by C{dataReceived} with bytes that were buffered before C{loseConnection} was called, which is why this function doesn't check for disconnection but accepts the bytes regardless. Ni@r) rElenr1sendrrdrr=rr<)rrD bufferSize alreadySenttoSendsentrrr ras$      zTLSMemoryBIOProtocol._writecCs|d|dS)z} Write a sequence of application bytes by joining them into one string and passing them to L{write}. N)rBjoin)riovecrrr writeSequencesz"TLSMemoryBIOProtocol.writeSequencecCs |jSr)r1get_peer_certificater%rrr getPeerCertificate"r"z'TLSMemoryBIOProtocol.getPeerCertificatec Csld}z|j}Wn ttfyYnw|dvr|Sz|j}Wn ttfy-Ynw|dkr4|SdS)z9 @see: L{INegotiated.negotiatedProtocol} N)rmNrm)r1get_alpn_proto_negotiatedNotImplementedErrorAttributeErrorget_next_proto_negotiated)r protocolNamerrr negotiatedProtocol%s z'TLSMemoryBIOProtocol.negotiatedProtocolcCsT|jr |dS|st||}}t|}|j|d||_|s(|dSdS)NT)rEr(r rr8registerProducerrstartStreaming)rr streamingstreamingProducerrrr ry@s z%TLSMemoryBIOProtocol.registerProducercCs^|jdurdSt|jjtr|jjd|_d|_|j|jr+|js-| dSdSdS)NF) rr^r stopStreamingr#r8unregisterProducerr[r4rGr%rrr r~Ss     z'TLSMemoryBIOProtocol.unregisterProducer)T) r)r*r+r,rUr>rErr:r!r2r5r7r<rJrHrGr=rZrNr\r]rBrdrLrarprrpropertyrxryr~rrrr r-xs<6   *!   )  r-c@s0eZdZdZddZddZddZdd Zd S) "_ContextFactoryToConnectionFactorya Adapter wrapping a L{twisted.internet.interfaces.IOpenSSLContextFactory} into a L{IOpenSSLClientConnectionCreator} or L{IOpenSSLServerConnectionCreator}. See U{https://twistedmatrix.com/trac/ticket/7215} for work that should make this unnecessary. cCs|||_dS)a( Construct a L{_ContextFactoryToConnectionFactory} with a L{twisted.internet.interfaces.IOpenSSLContextFactory}. Immediately call C{getContext} on C{oldStyleContextFactory} in order to force advance parameter checking, since old-style context factories don't actually check that their arguments to L{OpenSSL} are correct. @param oldStyleContextFactory: A factory that can produce contexts. @type oldStyleContextFactory: L{twisted.internet.interfaces.IOpenSSLContextFactory} N) getContext_oldStyleContextFactory)roldStyleContextFactoryrrr r!ns z+_ContextFactoryToConnectionFactory.__init__cCs|j}t|dS)z Create an L{OpenSSL.SSL.Connection} object. @param protocol: The protocol initiating a TLS connection. @type protocol: L{TLSMemoryBIOProtocol} @return: a connection @rtype: L{OpenSSL.SSL.Connection} N)rrr)rprotocolcontextrrr _connectionForTLS~s z4_ContextFactoryToConnectionFactory._connectionForTLScC ||S)a Construct an OpenSSL server connection from the wrapped old-style context factory. @note: Since old-style context factories don't distinguish between clients and servers, this is exactly the same as L{_ContextFactoryToConnectionFactory.clientConnectionForTLS}. @param protocol: The protocol initiating a TLS connection. @type protocol: L{TLSMemoryBIOProtocol} @return: a connection @rtype: L{OpenSSL.SSL.Connection} rrrrrr serverConnectionForTLS z9_ContextFactoryToConnectionFactory.serverConnectionForTLScCr)a Construct an OpenSSL server connection from the wrapped old-style context factory. @note: Since old-style context factories don't distinguish between clients and servers, this is exactly the same as L{_ContextFactoryToConnectionFactory.serverConnectionForTLS}. @param protocol: The protocol initiating a TLS connection. @type protocol: L{TLSMemoryBIOProtocol} @return: a connection @rtype: L{OpenSSL.SSL.Connection} rrrrr clientConnectionForTLSrz9_ContextFactoryToConnectionFactory.clientConnectionForTLSN)r)r*r+r,r!rrrrrrr rcs   rc@s8eZdZdZeZdZddZddZddZ d d Z d S) TLSMemoryBIOFactorya L{TLSMemoryBIOFactory} adds TLS to connections. @ivar _creatorInterface: the interface which L{_connectionCreator} is expected to implement. @type _creatorInterface: L{zope.interface.interfaces.IInterface} @ivar _connectionCreator: a callable which creates an OpenSSL Connection object. @type _connectionCreator: 1-argument callable taking L{TLSMemoryBIOProtocol} and returning L{OpenSSL.SSL.Connection}. FcCs<t|||r t}nt}||_||st|}||_dS)a2 Create a L{TLSMemoryBIOFactory}. @param contextFactory: Configuration parameters used to create an OpenSSL connection. In order of preference, what you should pass here should be: 1. L{twisted.internet.ssl.CertificateOptions} (if you're writing a server) or the result of L{twisted.internet.ssl.optionsForClientTLS} (if you're writing a client). If you want security you should really use one of these. 2. If you really want to implement something yourself, supply a provider of L{IOpenSSLClientConnectionCreator} or L{IOpenSSLServerConnectionCreator}. 3. If you really have to, supply a L{twisted.internet.ssl.ContextFactory}. This will likely be deprecated at some point so please upgrade to the new interfaces. @type contextFactory: L{IOpenSSLClientConnectionCreator} or L{IOpenSSLServerConnectionCreator}, or, for compatibility with older code, anything implementing L{twisted.internet.interfaces.IOpenSSLContextFactory}. See U{https://twistedmatrix.com/trac/ticket/7215} for information on the upcoming deprecation of passing a L{twisted.internet.ssl.ContextFactory} here. @param isClient: Is this a factory for TLS client connections; in other words, those that will send a C{ClientHello} greeting? L{True} if so, L{False} otherwise. This flag determines what interface is expected of C{contextFactory}. If L{True}, C{contextFactory} should provide L{IOpenSSLClientConnectionCreator}; otherwise it should provide L{IOpenSSLServerConnectionCreator}. @type isClient: L{bool} @param wrappedFactory: A factory which will create the application-level protocol. @type wrappedFactory: L{twisted.internet.interfaces.IProtocolFactory} N)rr!rr_creatorInterfacer r_connectionCreator)rcontextFactoryisClientwrappedFactorycreatorInterfacerrr r!s +  zTLSMemoryBIOFactory.__init__cCs,t|jr |j}n|jjj}|dS)z Annotate the wrapped factory's log prefix with some text indicating TLS is in use. @rtype: C{str} z (TLS))rr r logPrefix __class__r))rrrrr rs    zTLSMemoryBIOFactory.logPrefixcCs,t|jr|j}|}t||dS)a8 Applies ALPN/NPN protocol neogitation to the connection, if the factory supports it. @param connection: The OpenSSL connection object to have ALPN/NPN added to it. @type connection: L{OpenSSL.SSL.Connection} @return: Nothing @rtype: L{None} N)rr racceptableProtocols get_contextr )r connection protocolsrrrr _applyProtocolNegotiations  z-TLSMemoryBIOFactory._applyProtocolNegotiationcCsP|j}|jtur||}||||S||}||||S)a8 Create an OpenSSL connection and set it up good. @param tlsProtocol: The protocol which is establishing the connection. @type tlsProtocol: L{TLSMemoryBIOProtocol} @return: an OpenSSL connection object for C{tlsProtocol} to use @rtype: L{OpenSSL.SSL.Connection} )rrrrrset_connect_staterset_accept_state)r tlsProtocolconnectionCreatorrrrr r3s    z%TLSMemoryBIOFactory._createConnectionN) r)r*r+r,r-rnoisyr!rrr3rrrr rs 5 r)*r, OpenSSL.SSLrrrrrrr`er_ ImportErrorzope.interfacerr r "twisted.internet._producer_helpersr twisted.internet._sslverifyr twisted.internet.interfacesr rrrrrrrtwisted.internet.mainrtwisted.internet.protocolrtwisted.protocols.policiesrrtwisted.python.failurerrr-rrrrrr s8 #    (  +mJ