ϪfZdZddlZddlZddlmZmZmZmZddlm Z ddl m Z ddl m Z ddlmZddlmZdd lmZdd lmZ dd lmamZdd lmadd lmZmZddlm Z Gdde jBZ"Gdde jBZ#GddejHZ%GddejHZ&e ejNGddejHZ(dZ)dZ*GddZ+t.Gddt2jXZ-Gd d!eeZ.Gd"d#eZ/Gd$d%e/Z0Gd&d'eZ1Gd(d)ee+Z2Gd*d+Z3Gd,d-eZ4Gd.d/eZ5y#e$rdZeYwxYw)0z Tests for twisted SSL support. N)defer interfacesprotocolreactor)ConnectionDone)waitUntilAllDisconnected)basic)FilePath)platform)ProperlyCloseFilesMixin)TestCase)SSLcrypto)ssl)ClientTLSContextcertPathc dxaayN)rr7/usr/lib/python3/dist-packages/twisted/test/test_ssl.py_noSSLrscr) implementerc8eZdZdZgdZddgZdZdZdZdZ y ) UnintelligentProtocola @ivar deferred: a deferred that will fire at connection lost. @type deferred: L{defer.Deferred} @cvar pretext: text sent before TLS is set up. @type pretext: C{bytes} @cvar posttext: text sent after TLS is set up. @type posttext: C{bytes} )s first lineslast thing before tls startsSTARTTLSsfirst thing after tls startedslast thing everc6tj|_yrrDeferreddeferredselfs r__init__zUnintelligentProtocol.__init__7( rcH|jD]}|j|yr)pretextsendLine)r"ls rconnectionMadez$UnintelligentProtocol.connectionMade:s! A MM!  rc|dk(ru|jjt|jj|j D]}|j ||jjyy)NREADY) transportstartTLSrfactoryclientposttextr'loseConnection)r"liner(s r lineReceivedz"UnintelligentProtocol.lineReceived>s` 8  NN # #$4$6 8K8K L]] ! a  ! NN ) ) + rc:|jjdyrr callbackr"reasons rconnectionLostz$UnintelligentProtocol.connectionLostE t$rN) __name__ __module__ __qualname____doc__r&r0r#r)r3r9rrrrr's. LG02DEH),%rrc0eZdZdZddZdZdZdZdZy) LineCollectoraJ @ivar deferred: a deferred that will fire at connection lost. @type deferred: L{defer.Deferred} @ivar doTLS: whether the protocol is initiate TLS or not. @type doTLS: C{bool} @ivar fillBuffer: if set to True, it will send lots of data once C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XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXr+)privateKeyFileNamecertificateFileName) r.rFappendrCranger'rBServerTLSContextrr,r-server setRawMode)r"r2xctxs rr3zLineCollector.lineReceived_s !!$' ; s/AMM+./ MM( #zz&'/(0''T\\-@-@A! rcv|jxj|z c_|jjyr)r.rEr,r1r"datas rrawDataReceivedzLineCollector.rawDataReceivedos' $ %%'rc:|jjdyrr5r7s rr9zLineCollector.connectionLostsr:rNF) r;r<r=r>r#r)r3rTr9rrrr@r@Is  )  " (%rr@ceZdZdZdZy)SingleLineServerProtocolzK A protocol that sends a single line of data at C{connectionMade}. cn|jjd|jjy)N+OK )r,writegetPeerCertificater!s rr)z'SingleLineServerProtocol.connectionMade|s% 34 ))+rN)r;r<r=r>r)rrrrXrXws ,rrXc"eZdZdZdZdZdZy)RecordingClientProtocolzv @ivar deferred: a deferred that will fire with first received content. @type deferred: L{defer.Deferred} c6tj|_yrrr!s rr#z RecordingClientProtocol.__init__r$rc8|jjyr)r,r\r!s rr)z&RecordingClientProtocol.connectionMades ))+rc:|jj|yrr5rRs r dataReceivedz$RecordingClientProtocol.dataReceivedr:rN)r;r<r=r>r#r)rbrrrr^r^s ),%rr^ceZdZdZdZdZy) ImmediatelyDisconnectingProtocolz A protocol that disconnect immediately on connection. It fires the C{connectionDisconnected} deferred of its factory on connetion lost. c8|jjyrr,r1r!s rhandshakeCompletedz3ImmediatelyDisconnectingProtocol.handshakeCompleteds %%'rcN|jjjdyr)r.connectionDisconnectedr6r7s rr9z/ImmediatelyDisconnectingProtocol.connectionLosts ++44T:rN)r;r<r=r>rgr9rrrrdrds (;rrdctj}|jtjdtj}|j }||_||_|j||j|dtj}|jd|jd|jd|j|j |j|j |j|j!|j|d|||fS)z Create a certificate for given C{organization} and C{organizationalUnit}. @return: a tuple of (key, request, certificate) objects. imd5r<)rPKey generate_keyTYPE_RSAX509Req get_subjectOOU set_pubkeysignX509set_serial_numbergmtime_adj_notBeforegmtime_adj_notAfter set_issuer set_subject get_pubkey) organizationorganizationalUnitpkeyreqsubjectcerts rgenerateCertificateObjectsrs ;;=Dfoot, .. CooGGI#GJNN4HHT5 ;;=D1a R OOCOO%&S__&'OOCNN$%IIdE d?rcdt||\}}}d|tjfd|tjfd|tjffD]e\}}}t j j||fjd} t| j|tj|gy)z Create certificate files key, req and cert prefixed by C{basename} for given C{organization} and C{organizationalUnit}. keyrrzutf-8N) rrdump_privatekeydump_certificate_requestdump_certificateosextsepjoinencoder setContent FILETYPE_PEM) basenamer~rrrrextobjdumpFuncfNames rgenerateCertificateFilesrs 1?QROD#t f,,- V445 v../GS(  #/66w?""8F,?,?#EF GrceZdZdZdZdZy)ContextGeneratingMixinah Offer methods to create L{ssl.DefaultOpenSSLContextFactory} for both client and server. @ivar clientBase: prefix of client certificate files. @type clientBase: C{str} @ivar serverBase: prefix of server certificate files. @type serverBase: C{str} @ivar clientCtxFactory: a generated context factory to be used in L{IReactorSSL.connectSSL}. @type clientCtxFactory: L{ssl.DefaultOpenSSLContextFactory} @ivar serverCtxFactory: a generated context factory to be used in L{IReactorSSL.listenSSL}. @type serverCtxFactory: L{ssl.DefaultOpenSSLContextFactory} c|j}t|||tjtj j |dftj j |dfg|i|}||fS)Nrr)mktemprrDefaultOpenSSLContextFactoryrrr)r"orgorgUnitargskwArgsbaseserverCtxFactorys rmakeContextFactoryz)ContextGeneratingMixin.makeContextFactoryst{{} sG4;; IINND%= ) IINND&> *    %%%rc|j|i|\|_|_|j|i|\|_|_yr)r clientBaseclientCtxFactory serverBaser)r" clientArgs clientKwArgs serverArgs serverKwArgss rsetupServerAndClientz+ContextGeneratingMixin.setupServerAndClientsS1H1H1H 2 '2 ..2I1H1H 2 '2 ..rN)r;r<r=r>rrrrrrrs& & rrceZdZdZdZdZy)rLzf A context factory with a default method set to L{OpenSSL.SSL.SSLv23_METHOD}. Fcptj|d<tjj|g|i|y)N sslmethod)r SSLv23_METHODrrr#)r"rkws rr#zServerTLSContext.__init__s/!//B{O  , , 5 5d HT HR HrN)r;r<r=r>isClientr#rrrrLrLs  IrrLcReZdZdZej eddZdZdZ dZ dZ y)StolenTCPTestszc For SSL transports, test many of the same things which are tested for TCP transports. N2Reactor does not support SSL, cannot run SSL testsctjjttj }|j }tj||||S)zY Create an SSL server with a certificate using L{IReactorSSL.listenSSL}.  interface) rPrivateCertificateloadPEMr r getContentoptionsr listenSSL)r"address portNumberr.rcontextFactorys r createServerzStolenTCPTests.createServer sK%%--hx.@.K.K.MN  WnPWXXrcPtj}|j|||S)zG Create an SSL client using L{IReactorSSL.connectSSL}. )rCertificateOptions connectSSL)r"rr clientCreatorrs r connectClientzStolenTCPTests.connectClients'//1''^LLrc"tjS)z Return L{OpenSSL.SSL.Error} as the expected error type which will be raised by a write to the L{OpenSSL.SSL.Connection} object after it has been closed. )rErrorr!s rgetHandleExceptionTypez%StolenTCPTests.getHandleExceptionTypes yyrc >tjtjtjdtjtjdtjdtjdtjdS)a4 Return a L{hamcrest.core.matcher.Matcher} for the argument L{OpenSSL.SSL.Error} will be constructed with for this case. This is basically just a random OpenSSL implementation detail. It would be better if this test worked in a way which did not require this. z SSL routines SSL_writessl_write_internalzprotocol is shutdown)hamcrestcontainsequal_toany_ofr!s rgetHandleErrorCodeMatcherz(StolenTCPTests.getHandleErrorCodeMatcher#s{    !!.1%%k2%%&:;%%b) !!"89   r) r;r<r=r>r IReactorSSLrskiprrrrrrrrrs9 zgt,4CYM rrcfeZdZdZej eddZdZdZ dZ dZ d dZ dZ dZd Zy) TLSTestsz Tests for startTLS support. @ivar fillBuffer: forwarded to L{LineCollector.fillBuffer} @type fillBuffer: C{bool} NrFc|jj$|jjj|jj%|jjjyyr) clientProtor,r1 serverProtor!s rtearDownzTLSTests.tearDownJs[    % % 1    & & 5 5 7    % % 1    & & 5 5 7 2rc|_tjx}|_fd|_|rd|_nd|_|_tjx}|_fd|_|rd|_nd|_tjd|d}|j|jtjd|jj|t!j"j$j$gS)a Helper method to run TLS tests. @param clientProto: protocol instance attached to the client connection. @param serverProto: protocol instance attached to the server connection. @param clientIsServer: flag indicated if client should initiate startTLS instead of server. @return: a L{defer.Deferred} that will fire when both connections are lost. cSrrrsrz#TLSTests._runTest..`krFTcSrrrsrrz#TLSTests._runTest..hrrr 127.0.0.1r)rr ClientFactory clientFactoryrMr/r ServerFactory serverFactoryr listenTCP addCleanup stopListening connectTCPgetHostportr gatherResultsr )r"rrclientIsServercfsfrs `` r_runTestzTLSTests._runTestPs'"*"8"8"::T ) BIBI&"*"8"8"::T ) BIBI  B+> **+; (;(;R@""K$8$8+:N:N#OPPrcfd}jttdj}|j |S)z~ Test for server and client startTLS: client should received data both before and after the startTLS. cjjjtjtj zyr) assertEqualrrFrr&r0)ignorer"s rcheckz TLSTests.test_TLS..check{5   ""((%--0E0N0NN rTrrr@rC addCallbackr"rds` rtest_TLSzTLSTests.test_TLSus8   MM/1=t3W X}}U##rcfd}jttdj}|j |S)z Test for server startTLS not followed by a startTLS in client: the data received after server startTLS should be received as raw. cjjjtjj jj dy)NzNo encrypted bytes received)rrrFrr& assertTruerEignoredr"s rrz"TLSTests.test_unTLS..checksA   T//557L7T7T U OOD..668U VrFrrs` r test_unTLSzTLSTests.test_unTLSs=  W MM ! #]5$//%J }}U##rcfd}jtdjtd}|j |S)z: Test startTLS first initiated by client. cjjjtjtj zyr)rrrFrr&r0rs rrz)TLSTests.test_backwardsTLS..checkrrT)rr@rCrrrs` rtest_backwardsTLSzTLSTests.test_backwardsTLSs?   MM $ 02G2I4 }}U##rrV)r;r<r=r>rrrrrCrrrrrrrrrrrr:sMzgt,4CJKK8 #QJ $ $$rrc>eZdZdZej eddZdZy)SpammyTLSTestszA Test TLS features with bytes sitting in the out buffer. NrT) r;r<r=r>rrrrrCrrrrrs(zgt,4CJrrcJeZdZejeddZdZdZdZ dZ y)BufferingTestsNrc6|jj$|jjj|jj$|jjjt t |j|jgSr)rr,r1rrrr!s rrzBufferingTests.tearDownst    % % 1    & & 5 5 7    % % 1    & & 5 5 7'$2B2BDDTDT1UVVrc~tx|_tx|_t j }t j x}|_fd|_fd|_tjtt}tj}tjd||d}|j|jtj d|j#j$||}|j|j&j(j+|j,dS)NcSrrrsrrz6BufferingTests.test_openSSLBuffering..+rcSrrrsrrz6BufferingTests.test_openSSLBuffering..r rrrrrZ)rXrr^rrrrr/rrrClientContextFactoryrrrrrrr disconnectr rr) r"rMr/sCTXcCTXrclientConnectorrrs @@rtest_openSSLBufferingz$BufferingTests.test_openSSLBufferings)A)CC d&)@)BB d&'')'5577--//(C'')  FDKH **+!,, ,,fd  223##//   4  r) r;r<r=rrrrrrrrrrrrrs1zgt,4CKKW rrcReZdZdZej eddZdZdZ dZ dZ y)ConnectionLostTestsz' SSL connection closing tests. Nrcd}j||dzfi||dzfitj}tj|_t j d|j x_}tj}t|_tj|_ t jd|jj|j |jj#fdS)Ntwisted.test.test_ssl, client, serverrrc8jjSr) serverPortr) ignoredResultr"s rrz=ConnectionLostTests.testImmediateDisconnect..s$//"?"?"Ar)rrrProtocolrrrrrrdrrrirrrrr)r"rserverProtocolFactoryrclientProtocolFactorys` rtestImmediateDisconnectz+ConnectionLostTests.testImmediateDisconnects% !! # " #R#sZ/?)@" !) 6 6 8)1):):&'.'8'8 $d&;&;(  *!) 6 6 8)I&7<~~7G4     % % !  ! !  %;;GG A  rcttjGddtj}d}|j ||dzfi||dzfi|tj }fd|_tjd||j}|j|j|tj}fd|_tjd |jj||j d }t#j$j&j)|j&j)|gS) z Both sides of SSL connection close connection; the connections should close cleanly, and only after the underlying TCP connection has disconnected. c"eZdZdZdZdZdZy)MConnectionLostTests.test_bothSidesLoseConnection..CloseAfterHandshakeFc6tj|_yr)rrdoner!s rr#zVConnectionLostTests.test_bothSidesLoseConnection..CloseAfterHandshake.__init__s!NN, rc8|jjyrrfr!s rrgz`ConnectionLostTests.test_bothSidesLoseConnection..CloseAfterHandshake.handshakeCompleted s--/rc>|jj||`yr)r$errbackr7s rr9z\ConnectionLostTests.test_bothSidesLoseConnection..CloseAfterHandshake.connectionLost s !!&)IrN)r;r<r=gotDatar#rgr9rrrCloseAfterHandshaker"sG - 0 rr)rrrcSrrserverProtocolsrrzBConnectionLostTests.test_bothSidesLoseConnection..rrcSrrclientProtocolsrrzBConnectionLostTests.test_bothSidesLoseConnection..r-rrc.|jtyr)trapr)failures r checkResultzEConnectionLostTests.test_bothSidesLoseConnection..checkResult&s LL (r)rrIHandshakeListenerrrrrrrrrrrrrrrrrr$ addErrback) r"r)rrrrr4r0r,s @@rtest_bothSidesLoseConnectionz0ConnectionLostTests.test_bothSidesLoseConnectionsF Z22 3 ("3"3  4 & !! # " #R#sZ/?)@" -. ( 6 6 8)?&&&q*?AVAVW   001,. ( 6 6 8)?&     % % !  ! !   )""##..{;##..{;   rcD d}|j||dzfi||dzfid}|jjjtj |t j}tj |j _ tj} fd|_tjd||jx|_}t j}tj |j _ tj"} fd|_tj$d|j'j(||jt j*||gd }|j-|j.S) Nrrrcy)NFr)as rverifyz4ConnectionLostTests.testFailedVerify..verify6srcSrrr+srrz6ConnectionLostTests.testFailedVerify..?r-rrcSrrr/srrz6ConnectionLostTests.testFailedVerify..Hr-rrT) consumeErrors)rr getContext set_verifyr VERIFY_PEERrrrrr6r9rrrrrrrrr DeferredListr _cbLostConns) r"rr;serverConnLostrrclientConnLostrdlr0r,s @@rtestFailedVerifyz$ConnectionLostTests.testFailedVerify0sd% !! # " #R#sZ/?)@"   ((*55coovN)!**,(6(?(?% ( 6 6 8)?&'.'8'8 $d&;&;(  *)!**,(6(?(?% ( 6 6 8)?&     % % !  ! !     @PT U~~d//00rcD|\\}}\}}|j||j|tjg}tjrddlm}|j||j||j||jjS)Nr)ConnectionLost) assertFalserrr isWindowstwisted.internet.errorrIrJr2rr)r"resultssSuccesssResultcSuccesscResultacceptableErrorsrIs rrCz ConnectionLostTests._cbLostConnsSs3:070h " "II;     =  # #N 3 &' &',,..r) r;r<r=r>rrrrrr7rGrCrrrrrs9zgt,4C 82 h!1F/rrc(eZdZdZdZdZdZdZy) FakeContextzK L{OpenSSL.SSL.Context} double which can more easily be inspected. c ||_d|_y)Nr)_method_options)r"methods rr#zFakeContext.__init__ss  rc.|xj|zc_yr)rW)r"rs r set_optionszFakeContext.set_optionsws  rcyrrr"fileNames ruse_certificate_filez FakeContext.use_certificate_filez rcyrrr\s ruse_privatekey_filezFakeContext.use_privatekey_file}r_rN)r;r<r=r>r#rZr^rarrrrTrTns!  rrTcReZdZdZej eddZdZdZ dZ dZ y)!DefaultOpenSSLContextFactoryTestsz8 Tests for L{ssl.DefaultOpenSSLContextFactory}. Nrctjttt|_|jj |_y)N)_contextFactory)rrrrTrr?contextr!s rsetUpz'DefaultOpenSSLContextFactoryTests.setUps6">> h  **557 rcb|j|jjtj|j|jj tj ztj |j|jj tjzy)z L{ssl.DefaultOpenSSLContextFactory.getContext} returns an SSL context which can use SSLv3 or TLSv1 but not SSLv2. N) rrfrVr TLS_METHODrW OP_NO_SSLv2rJ OP_NO_TLSv1_2r!s r test_methodz-DefaultOpenSSLContextFactoryTests.test_methodsp --s~~> ..@#//R ..1B1BBCrc|jtjtjt |j y)z Instantiating L{ssl.DefaultOpenSSLContextFactory} with a certificate filename which does not identify an existing file results in the initializer raising L{OpenSSL.SSL.Error}. N) assertRaisesrrrrrrr!s rtest_missingCertificateFilez=DefaultOpenSSLContextFactoryTests.test_missingCertificateFiles+  IIs774;;= rc|jtjtj|j t y)z Instantiating L{ssl.DefaultOpenSSLContextFactory} with a private key filename which does not identify an existing file results in the initializer raising L{OpenSSL.SSL.Error}. N)rnrrrrrrr!s rtest_missingPrivateKeyFilezrrrrrgrlrorqrrrrcrcs8zgt,4C8 D  rrccFeZdZdZej eddZdZdZ y)ClientContextFactoryTestsz0 Tests for L{ssl.ClientContextFactory}. Nrctj|_t|j_|jj |_yr)rr rrTrer?rfr!s rrgzClientContextFactoryTests.setUps7!668.9+**557 rc|j|jjtj|j|jj tj ztj |j|jj tjz|j|jj tjzy)z L{ssl.ClientContextFactory.getContext} returns a context which can use TLSv1.2 or 1.3 but nothing earlier. N) rrfrVrrirWrjr OP_NO_SSLv3 OP_NO_TLSv1r!s rrlz%ClientContextFactoryTests.test_methods --s~~> ..@#//R  --?@  --?@r) r;r<r=r>rrrrrgrlrrrrsrss.zgt,4C8 Arrs)6r>rrtwisted.internetrrrrrLrtwisted.internet.testingrtwisted.protocolsr twisted.python.filepathr twisted.python.runtimer twisted.test.test_tcpr twisted.trial.unittestr OpenSSLrrrtwisted.test.ssl_helpersrr ImportErrorrzope.interfacer LineReceiverrr@rrXr^r5rdrrrrrLrrrrrrTrcrsrrrrst AA1=#,+9+  #$C'%E..%D+%E&&+%\,x00, %h// %  Z * *+ ;x'8'8 ;, ;8 G & & R? I3;; I4 ,h4 ng$xg$TX& X& RS/($:S/l  &0 0 fAAu   H sE%%E87E8