U  W[lã @s|dZddlmZmZddlmZmZmZddlmZm Z m Z ze e eƒdƒWn8e k r†Z ze e ƒdkrn‚edƒ‚W5dZ [ XYnXddlmZmZmZdd lmZdd lmZdd lmZmZmZmZmZmZmZmZdd l m!Z!dd l"m#Z#ddl$m%Z%ddl&m'Z'ddl(m)Z)m*Z*eeƒGdd„de+ƒƒZ,eeeƒGdd„de)ƒƒZ-eeeƒGdd„de+ƒƒZ.Gdd„de*ƒ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. é)ÚdivisionÚabsolute_import)ÚErrorÚZeroReturnErrorÚ WantReadError)Ú TLSv1_METHODÚContextÚ ConnectionNz3argument must be an int, or have a fileno() method.z7twisted.protocols.tls requires pyOpenSSL 0.10 or newer.)Ú implementerÚ providedByÚdirectlyProvides)Úunicode)ÚFailure)Ú ISystemHandleÚ INegotiatedÚ IPushProducerÚILoggingContextÚIOpenSSLServerConnectionCreatorÚIOpenSSLClientConnectionCreatorÚIProtocolNegotiationFactoryÚIHandshakeListener)ÚCONNECTION_LOST)Ú _PullToPush)ÚProtocol)Ú_setAcceptableProtocols)ÚProtocolWrapperÚWrappingFactoryc@s4eZdZdZdZdd„Zdd„Zdd„Zd 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 ||_dS©N)Ú _producer)ÚselfÚproducer©r"ú7/usr/lib/python3/dist-packages/twisted/protocols/tls.pyÚ__init__Psz_ProducerMembrane.__init__cCs|jr dSd|_|j ¡dS)zP C{pauseProducing} the underlying producer, if it's not paused. NT)Ú_producerPausedrÚpauseProducing©r r"r"r#r&Tsz _ProducerMembrane.pauseProducingcCs|js dSd|_|j ¡dS)zM C{resumeProducing} the underlying producer, if it's paused. NF)r%rÚresumeProducingr'r"r"r#r(^sz!_ProducerMembrane.resumeProducingcCs|j ¡dS)z” C{stopProducing} the underlying producer. There is only a single source for this event, so it's simply passed on. N)rÚ stopProducingr'r"r"r#r)hsz_ProducerMembrane.stopProducingN) Ú__name__Ú __module__Ú __qualname__Ú__doc__r%r$r&r(r)r"r"r"r#rCs    rc@sÚeZdZdZdZdZdZdZdZd1dd„Z dd„Z d d „Z d d „Z d d„Z dd„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd „Zd!d"„Zd#d$„Zd%d&„Zd'd(„Zd)d*„Zed+d,„ƒZd-d.„Zd/d0„ZdS)2ÚTLSMemoryBIOProtocola 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)r ÚfactoryÚwrappedProtocolr/r"r"r#r$°szTLSMemoryBIOProtocol.__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'r"r"r#Ú getHandleµs zTLSMemoryBIOProtocol.getHandlecCsb|j |¡|_g|_t|ƒD]}t||ƒqt ||¡|j |¡|j rVt  ||¡|  ¡dS)z Connect this wrapper to the given transport and initialize the necessary L{OpenSSL.SSL.Connection} with a memory BIO. N) r0Ú_createConnectionr2Ú_appSendBufferr r rÚmakeConnectionZregisterProtocolr/rÚ_checkHandshakeStatus)r Ú transportZ interfacer"r"r#r6Âs     z#TLSMemoryBIOProtocol.makeConnectioncCst|jr dSz|j ¡Wn:tk r4| ¡Yn<tk rR| tƒ¡YnXd|_t   |j ¡rp|j   ¡dS)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) Ú_abortedr2Z do_handshakerÚ _flushSendBIOrÚ_tlsShutdownFinishedrÚ_handshakeDonerr r1ZhandshakeCompletedr'r"r"r#r7Ýs   z*TLSMemoryBIOProtocol._checkHandshakeStatuscCs6z|j d¡}Wntk r$YnX|j |¡dS)zh Read any bytes out of the send BIO and write them to the underlying transport. é€N)r2Zbio_readrr8Úwrite©r Úbytesr"r"r#r:ös z"TLSMemoryBIOProtocol._flushSendBIOcCs–|jsŠz|j d¡}Wn^tk r.YqŠYqtk rR| ¡| d¡Yqtk rttƒ}| |¡YqX|j st   ||¡q|  ¡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) Ú_lostTLSConnectionr2ZrecvrrÚ _shutdownTLSr;rrr9rÚ dataReceivedr:)r r@Zfailurer"r"r#Ú_flushReceiveBIOs z%TLSMemoryBIOProtocol._flushReceiveBIOcCs>|j |¡|js$| ¡|js$dS|jr2| ¡| ¡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)r2Z bio_writer<r7r5Ú_unbufferPendingWritesrDr?r"r"r#rC/s z!TLSMemoryBIOProtocol.dataReceivedcCsBz|j ¡}Wntk r&d}YnX| ¡|r>|j ¡dS)zQ Initiate, or reply to, the shutdown handshake of the TLS layer. FN)r2Zshutdownrr:r8ÚloseConnection)r ZshutdownSuccessr"r"r#rBMs z!TLSMemoryBIOProtocol._shutdownTLScCsT|dk r(t|jjdd…ƒdkr(ttƒ}|jdkr8||_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) ÚtupleÚvalueÚargsrrÚ_reasonrAr:r8rF©r Úreasonr"r"r#r;bs  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)rAr2Z bio_shutdownrDrLÚ connectedrÚconnectionLostrMr"r"r#rP„s   z#TLSMemoryBIOProtocol.connectionLostcCsF|js |jsdS|js$|js$| ¡d|_|jsB|jdkrB| ¡dS)zM Send a TLS close alert and close the underlying connection. NT)Ú disconnectingrOr<r5ÚabortConnectionrrBr'r"r"r#rF™s  z#TLSMemoryBIOProtocol.loseConnectioncCs"d|_d|_| ¡|j ¡dS)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)r9rQrBr8rRr'r"r"r#rR¬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)rLrRrMr"r"r#ÚfailVerification·s z%TLSMemoryBIOProtocol.failVerificationcCs4t|tƒrtdƒ‚|jr&|jdkr&dS| |¡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. z1Must write bytes to a TLS transport, not unicode.N)Ú isinstancer Ú TypeErrorrQrÚ_writer?r"r"r#r>Äs  zTLSMemoryBIOProtocol.writecCs$|j |¡|jdk r |j ¡dS)z¶ Put the given octets into L{TLSMemoryBIOProtocol._appSendBuffer}, and tell any listening producer that it should pause because we are now buffering. N)r5Úappendrr&)r Zoctetsr"r"r#Ú_bufferedWriteÖs  z#TLSMemoryBIOProtocol._bufferedWritecCsV|jg}|_|D]}| |¡q|jr,dS|jdk rD|j ¡dS|jrR| ¡dS)zY Un-buffer all waiting writes in L{TLSMemoryBIOProtocol._appSendBuffer}. N)r5rVrr(rQrB)r Z pendingWritesZ eachWriter"r"r#rEás   z+TLSMemoryBIOProtocol._unbufferPendingWritescCs¢|jr dSd}d}|t|ƒkrž||||…}z|j |¡}WnLtk rh| ||d…¡YqžYqtk rŠ| tƒ¡YqžYqX||7}|  ¡qdS)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) rAÚlenr2ÚsendrrXrr;rr:)r r@Z bufferSizeZ alreadySentZtoSendZsentr"r"r#rVüs    zTLSMemoryBIOProtocol._writecCs| d |¡¡dS)z} Write a sequence of application bytes by joining them into one string and passing them to L{write}. óN)r>Újoin)r Ziovecr"r"r#Ú writeSequence&sz"TLSMemoryBIOProtocol.writeSequencecCs |j ¡Sr)r2Zget_peer_certificater'r"r"r#ÚgetPeerCertificate.sz'TLSMemoryBIOProtocol.getPeerCertificatec Cspd}z|j ¡}Wnttfk r*YnX|dkr8|Sz|j ¡}Wnttfk r^YnX|dkrl|SdS)z9 @see: L{INegotiated.negotiatedProtocol} N)r[Nr[)r2Zget_alpn_proto_negotiatedÚNotImplementedErrorÚAttributeErrorZget_next_proto_negotiated)r Z protocolNamer"r"r#ÚnegotiatedProtocol2sz'TLSMemoryBIOProtocol.negotiatedProtocolcCsP|jr| ¡dS|s$t||ƒ}}t|ƒ}|j |d¡||_|sL| ¡dS)NT)rAr)rrr8ÚregisterProducerrZstartStreaming)r r!Z streamingZstreamingProducerr"r"r#rbNsz%TLSMemoryBIOProtocol.registerProducercCsV|jdkrdSt|jjtƒr(|jj ¡d|_d|_|j ¡|jrR|jsR|  ¡dS)NF) rrTrZ stopStreamingr%r8ÚunregisterProducerrQr5rBr'r"r"r#rcbs    z'TLSMemoryBIOProtocol.unregisterProducer)T) r*r+r,r-rLr<rArr9r$r3r6r7r:rDrCrBr;rPrFrRrSr>rXrErVr]r^Úpropertyrarbrcr"r"r"r#r.rs:6  +"   * r.c@s0eZdZdZdd„Zdd„Zdd„Zdd „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)r ZoldStyleContextFactoryr"r"r#r$~s z+_ContextFactoryToConnectionFactory.__init__cCs|j ¡}t|dƒS)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)rgrfr )r ÚprotocolÚcontextr"r"r#Ú_connectionForTLSs z4_ContextFactoryToConnectionFactory._connectionForTLScCs | |¡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} ©rj©r rhr"r"r#ÚserverConnectionForTLSsz9_ContextFactoryToConnectionFactory.serverConnectionForTLScCs | |¡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.serverConnectionForTLS}. @param protocol: The protocol initiating a TLS connection. @type protocol: L{TLSMemoryBIOProtocol} @return: a connection @rtype: L{OpenSSL.SSL.Connection} rkrlr"r"r#ÚclientConnectionForTLS¯sz9_ContextFactoryToConnectionFactory.clientConnectionForTLSN)r*r+r,r-r$rjrmrnr"r"r"r#ress  rec@s8eZdZdZeZdZdd„Zdd„Zdd„Z 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 ||¡|rt}nt}||_| |¡s2t|ƒ}||_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 reÚ_connectionCreator)r ZcontextFactoryZisClientÚwrappedFactoryZcreatorInterfacer"r"r#r$Ós+  zTLSMemoryBIOFactory.__init__cCs,t |j¡r|j ¡}n |jjj}d|fS)z„ Annotate the wrapped factory's log prefix with some text indicating TLS is in use. @rtype: C{str} z%s (TLS))rr rrÚ logPrefixÚ __class__r*)r rsr"r"r#rs s   zTLSMemoryBIOFactory.logPrefixcCs,t |j¡r(|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 rrZacceptableProtocolsZ get_contextr)r Ú connectionZ protocolsrir"r"r#Ú_applyProtocolNegotiations   z-TLSMemoryBIOFactory._applyProtocolNegotiationcCsN|j}|jtkr.| |¡}| |¡| ¡n| |¡}| |¡| ¡|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} )rqrprrnrvZset_connect_statermZset_accept_state)r Z tlsProtocolZconnectionCreatorrur"r"r#r4+s       z%TLSMemoryBIOFactory._createConnectionN) r*r+r,r-r.rhZnoisyr$rsrvr4r"r"r"r#roÂs 6ro)0r-Z __future__rrZ OpenSSL.SSLrrrrrr rUÚeÚstrÚ ImportErrorZzope.interfacer r r Ztwisted.python.compatr Ztwisted.python.failurerZtwisted.internet.interfacesrrrrrrrrZtwisted.internet.mainrZ"twisted.internet._producer_helpersrZtwisted.internet.protocolrZtwisted.internet._sslverifyrZtwisted.protocols.policiesrrÚobjectrr.reror"r"r"r#Ús:"   (    .N