ϪfYpdZddlZddlZddlZddlmZddlmZddlm Z ddl m Z m Z m Z mZddlmZddlmZmZmZdd lmZdd lmZdd lmZdd lmZdd lmZddlm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&m'Z'm(Z(dZ)dZ*dZ+dZ,edrddl-Z-ddl.m/Z/ddl0m1Z1m2Z2m3Z3m4Z4m5Z5ddl6m7Z7ddl8m9Z9ddl:m;Z;ddlm?Z?m@Z@mAZAddlBmCZCddl mDZD e/je/jZGeGjd e/je/jZGeGjdnd!Z)e)Z*e)Z+e)Z,e)sdd"l mLZMdd#lNmOZOmPZPdd$lQmRZRd%ZSd&ZTeeUjjd'jZYejfd(Z[d)Z\dpd*Z]d+Z^dqd,Z_ drd-Z`d.ZaGd/d0e jZcGd1d2e jZdGd3d4ZeGd5d6e'ZfGd7d8ZgGd9d:ZhGd;dehe(ZjGd?d@e'ZkGdAdBe(ZlGdCdDe'ZmdqdEZnGdFdGe(ZoGdHdIe(ZpGdJdKe(ZqGdLdMZrGdNdOZsGdPdQZtGdRdSe(ZuGdTdUe(ZvGdVdWe(ZwGdXdYe(ZxGdZd[e(ZyGd\d]e(ZzGd^d_Z{Gd`daZ|Gdbdce(Z}GdddeZ~GdfdgZGdhdie'ZGdjdke'ZGdldme(ZGdndoe'Zy#eIeJf$rdZ+Y*wxYw#eI$rd Z,YwxYw)sz+ Tests for L{twisted.internet._sslverify}. N)skipIf) implementer)Version)defer interfacesprotocolreactor) _idnaText)CertificateErrorConnectionClosedConnectionLost)Clock) nativeString)FilePath) getModule) requireModule)connectedServerAndClient)SetAsideModule)util)SkipTestSynchronousTestCaseTestCaseOpenSSL)SSL) FILETYPE_PEMTYPE_RSAX509PKeyget_elliptic_curves)x509)default_backend)hashes)rsa)Encoding NoEncryption PrivateFormat)NameOID)sslcyNcs =/usr/lib/python3/dist-packages/twisted/test/test_sslverify.pyr0:zINPN is deprecated (and OpenSSL 1.0.1 or greater required for NPN support)cyr+r,r-s r/r0r0Cr1r2z2OpenSSL 1.0.2 or greater required for ALPN supportz"OpenSSL is required for SSL tests.) _sslverify)VerificationError platformTrust)TLSMemoryBIOFactorya -----BEGIN CERTIFICATE----- MIIC2jCCAkMCAjA5MA0GCSqGSIb3DQEBBAUAMIG0MQswCQYDVQQGEwJVUzEiMCAG A1UEAxMZZXhhbXBsZS50d2lzdGVkbWF0cml4LmNvbTEPMA0GA1UEBxMGQm9zdG9u MRwwGgYDVQQKExNUd2lzdGVkIE1hdHJpeCBMYWJzMRYwFAYDVQQIEw1NYXNzYWNo dXNldHRzMScwJQYJKoZIhvcNAQkBFhhub2JvZHlAdHdpc3RlZG1hdHJpeC5jb20x ETAPBgNVBAsTCFNlY3VyaXR5MB4XDTA2MDgxNjAxMDEwOFoXDTA3MDgxNjAxMDEw OFowgbQxCzAJBgNVBAYTAlVTMSIwIAYDVQQDExlleGFtcGxlLnR3aXN0ZWRtYXRy aXguY29tMQ8wDQYDVQQHEwZCb3N0b24xHDAaBgNVBAoTE1R3aXN0ZWQgTWF0cml4 IExhYnMxFjAUBgNVBAgTDU1hc3NhY2h1c2V0dHMxJzAlBgkqhkiG9w0BCQEWGG5v Ym9keUB0d2lzdGVkbWF0cml4LmNvbTERMA8GA1UECxMIU2VjdXJpdHkwgZ8wDQYJ KoZIhvcNAQEBBQADgY0AMIGJAoGBAMzH8CDF/U91y/bdbdbJKnLgnyvQ9Ig9ZNZp 8hpsu4huil60zF03+Lexg2l1FIfURScjBuaJMR6HiMYTMjhzLuByRZ17KW4wYkGi KXstz03VIKy4Tjc+v4aXFI4XdRw10gGMGQlGGscXF/RSoN84VoDKBfOMWdXeConJ VyC4w3iJAgMBAAEwDQYJKoZIhvcNAQEEBQADgYEAviMT4lBoxOgQy32LIgZ4lVCj JNOiZYg8GMQ6y0ugp86X80UjOvkGtNf/R7YgED/giKRN/q/XJiLJDEhzknkocwmO S+4b2XpiaZYxRyKWwL221O7CGmtWYyZl2+92YYmmCiNzWQPfP6BOMlfax0AGLHls fXzCWdG0O/3Lk2SRM0I= -----END CERTIFICATE----- a -----BEGIN CERTIFICATE----- MIIC3jCCAkcCAjA6MA0GCSqGSIb3DQEBBAUAMIG2MQswCQYDVQQGEwJVUzEiMCAG A1UEAxMZZXhhbXBsZS50d2lzdGVkbWF0cml4LmNvbTEPMA0GA1UEBxMGQm9zdG9u MRwwGgYDVQQKExNUd2lzdGVkIE1hdHJpeCBMYWJzMRYwFAYDVQQIEw1NYXNzYWNo dXNldHRzMSkwJwYJKoZIhvcNAQkBFhpzb21lYm9keUB0d2lzdGVkbWF0cml4LmNv bTERMA8GA1UECxMIU2VjdXJpdHkwHhcNMDYwODE2MDEwMTU2WhcNMDcwODE2MDEw MTU2WjCBtjELMAkGA1UEBhMCVVMxIjAgBgNVBAMTGWV4YW1wbGUudHdpc3RlZG1h dHJpeC5jb20xDzANBgNVBAcTBkJvc3RvbjEcMBoGA1UEChMTVHdpc3RlZCBNYXRy aXggTGFiczEWMBQGA1UECBMNTWFzc2FjaHVzZXR0czEpMCcGCSqGSIb3DQEJARYa c29tZWJvZHlAdHdpc3RlZG1hdHJpeC5jb20xETAPBgNVBAsTCFNlY3VyaXR5MIGf MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnm+WBlgFNbMlHehib9ePGGDXF+Nz4 CjGuUmVBaXCRCiVjg3kSDecwqfb0fqTksBZ+oQ1UBjMcSh7OcvFXJZnUesBikGWE JE4V8Bjh+RmbJ1ZAlUPZ40bAkww0OpyIRAGMvKG+4yLFTO4WDxKmfDcrOb6ID8WJ e1u+i3XGkIf/5QIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAD4Oukm3YYkhedUepBEA vvXIQhVDqL7mk6OqYdXmNj6R7ZMC8WWvGZxrzDI1bZuB+4aIxxd1FXC3UOHiR/xg i9cDl1y8P/qRp4aEBNF6rI0D4AxTbfnHQx4ERDAOShJdYZs/2zifPJ6va6YvrEyr yqDtGhklsWW3ZwBzEh5VEOUp -----END CERTIFICATE----- z server.pemct|S)zQ Each time we're called, return the next integer in the natural numbers. )next)counters r/r:r:s =r2c t}|jtdt}|j d|j d|j |jfD]0}|jD]\}}t||t|2|jt|j||j|d||fS)Niri3md5)r generate_keyrrgmtime_adj_notBeforegmtime_adj_notAfter get_issuer get_subjectitemssetattrrset_serial_numberr: set_pubkeysign)kwkeypair certificatexnamekvs r/makeCertificaterMsfG 4(&K$$Q'##$67'');+B+B+DD/HHJ /DAq E1l1o . //!!'),7#We$ K r2c tjtjtjdg}tjtjtjdg}t j ddd}tjddt}|j}tjj|j|jt j j|z j!t j j|zj#tj$j|j'tj(dd d j+|t-j.t }tjddt}|j} t1j2|} tj4| g} tjj|j|jt j j|z j!t j j|zj#tj$j|j'tj(dd d j'tj>| d j+|t-j.t } t@jBjE|jGtHjJ} t@jLjEdjO|jQtHjJtRjTtW| jGtHjJg} | | fS#t6$r8tj8|j;d j=dg} Y6wxYw)a~ Create a self-signed CA certificate and server certificate signed by the CA. @param serviceIdentity: The identity (hostname) of the server. @type serviceIdentity: L{unicode} @return: a 2-tuple of C{(certificate_authority_certificate, server_certificate)} @rtype: L{tuple} of (L{sslverify.Certificate}, L{sslverify.PrivateCertificate}) zTesting Example CAzTesting Example Serverrii)public_exponentkey_sizebackendT )ca path_length)critical) private_key algorithmrRidnaasciiFN ),r!Name NameAttributer( COMMON_NAMEdatetime timedeltar$generate_private_keyr" public_keyCertificateBuilder subject_name issuer_namenot_valid_beforetodaynot_valid_after serial_numberrandom_serial_number add_extensionBasicConstraintsrFr#SHA256 ipaddress ip_address IPAddress ValueErrorDNSNameencodedecodeSubjectAlternativeName sslverify CertificateloadPEM public_bytesr%PEMPrivateCertificatejoin private_bytesr'TraditionalOpenSSLr&)serviceIdentitycommonNameForCAcommonNameForServeroneDayprivateKeyForCApublicKeyForCA caCertificateprivateKeyForServerpublicKeyForServer ipAddresssubjectAlternativeNamesserverCertificate caSelfCert serverCerts r/!certificatesForAuthorityAndServerrskii  G//1E FGO))  G//1I JK  1a (F..o6GO%//1N ! o & _ %  (++113f< = **002V; < t002 3 N #   ! !Tq 9   'mmo#%  &22o6G-779>((9 $(>>)#<"= ! ) * _ %  (++113f< = **002V; < t002 3 & '   ! !U =     ' '(? @   'mmo#%  !,&&..}/I/I(,,/WXJ--55 #11LL!44 N "..x||<    J z !!W  LL//7>>wG H#  s9P=QQc Gddtj}Gddtj}| | tj} fd|_tj} fd|_t}t |d|| t |d || t fd  fd | \}}} | j || | fS) a Common implementation code for both L{loopbackTLSConnection} and L{loopbackTLSConnectionInMemory}. Creates a loopback TLS connection using the provided server and client context factories. @param serverOpts: An OpenSSL context factory for the server. @type serverOpts: C{OpenSSLCertificateOptions}, or any class with an equivalent API. @param clientOpts: An OpenSSL context factory for the client. @type clientOpts: C{OpenSSLCertificateOptions}, or any class with an equivalent API. @return: 5-tuple of server-tls-protocol, server-inner-protocol, client-tls-protocol, client-inner-protocol and L{IOPump} @rtype: L{tuple} ceZdZdZdZy)._loopbackTLSConnection..GreetingServer greetings!cN|jj|jyr+ transportwritegreetingselfs r/connectionMadez=_loopbackTLSConnection..GreetingServer.connectionMades NN  /r2N)__name__ __module__ __qualname__rrr,r2r/GreetingServerr s   0r2rc eZdZdZdZdZdZy)/_loopbackTLSConnection..ListeningClientr2Nc.|xj|z c_yr+datarrs r/ dataReceivedz<_loopbackTLSConnection..ListeningClient.dataReceiveds II Ir2c||_yr+ lostReasonrreasons r/connectionLostz>_loopbackTLSConnection..ListeningClient.connectionLosts $DOr2)rrrrrrrr,r2r/ListeningClientrs   %r2rcSr+r,clientWrappedProtosr/r0z(_loopbackTLSConnection.. *<r2cSr+r,serverWrappedProtosr/r0z(_loopbackTLSConnection.."rr2TisClientwrappedFactoryclockFc&jdSr+ buildProtocol) serverFactorysr/r0z(_loopbackTLSConnection..- ++D1r2c&jdSr+r) clientFactorysr/r0z(_loopbackTLSConnection...rr2r)rProtocolFactoryrr7rflush) serverOpts clientOptsrrplainClientFactoryplainServerFactoryrsProtocProtopumprrrrs @@@@r/_loopbackTLSConnectionrs&0**0 %(++%)*')!))+"<!))+"< GE'T2DEM(U3EUM411FFD  JJL 6-/A4 GGr2crGfdd}|}tj|}t||S)aF Create a loopback TLS connection with the given trust and keys. @param trustRoot: the C{trustRoot} argument for the client connection's context. @type trustRoot: L{sslverify.IOpenSSLTrustRoot} @param privateKeyFile: The name of the file containing the private key. @type privateKeyFile: L{str} (native string; file name) @param chainedCertFile: The name of the chained certificate file. @type chainedCertFile: L{str} (native string; file name) @return: 3-tuple of server-protocol, client-protocol, and L{IOPump} @rtype: L{tuple} ceZdZfdZy)-loopbackTLSConnection..ContextFactoryctjtj}|j|j |j |S)z Create a context for the server side of the connection. @return: an SSL context using a certificate and key. @rtype: C{OpenSSL.SSL.Context} )rContext SSLv23_METHODuse_certificate_chain_fileuse_privatekey_filecheck_privatekey)rctxchainedCertFileprivateKeyFiles r/ getContextz8loopbackTLSConnection..ContextFactory.getContextIsL++c//0C*..?  # #N 3  "Jr2N)rrrr)rrsr/ContextFactoryrHs r2r trustRootrvOpenSSLCertificateOptionsr)rrrrrrs `` r/loopbackTLSConnectionr6s4$  !J44yIJ !*j 99r2c|tj}|||}tj|||}t||S)a Create a loopback TLS connection with the given trust and keys. Like L{loopbackTLSConnection}, but using in-memory certificates and keys rather than writing them to disk. @param trustRoot: the C{trustRoot} argument for the client connection's context. @type trustRoot: L{sslverify.IOpenSSLTrustRoot} @param privateKey: The private key. @type privateKey: L{str} (native string) @param serverCertificate: The certificate used by the server. @type chainedCertFile: L{str} (native string) @param clientProtocols: The protocols the client is willing to negotiate using NPN/ALPN. @param serverProtocols: The protocols the server is willing to negotiate using NPN/ALPN. @param clientOptions: The type of C{OpenSSLCertificateOptions} class to use for the client. Defaults to C{OpenSSLCertificateOptions}. @return: 3-tuple of server-protocol, client-protocol, and L{IOPump} @rtype: L{tuple} )racceptableProtocols) privateKeyrIrr)rrrclientProtocolsserverProtocols clientOptionsclientCertOptsserverCertOptss r/loopbackTLSConnectionInMemoryr^sOF!;; "N88%+N ".. AAr2c|j}t|d5}|D]&}|j|jt( ddd|S#1swY|SxYw)a Create a temporary file to store some serializable-as-PEM objects in, and return its name. @param testCase: a test case to use for generating a temporary directory. @type testCase: L{twisted.trial.unittest.TestCase} @param dumpables: arguments are objects from pyOpenSSL with a C{dump} method, taking a pyOpenSSL file-type constant, such as L{OpenSSL.crypto.FILETYPE_PEM} or L{OpenSSL.crypto.FILETYPE_ASN1}. @type dumpables: L{tuple} of L{object} with C{dump} method taking L{int} returning L{bytes} @return: the path to a file where all of the dumpables were dumped in PEM format. @rtype: L{str} wbN)mktempopenrdumpr)testCase dumpablesfnamefdumpables r/pathContainingDumpOfrs^$ OO E eT 1a! 1H GGHMM,/ 0 11 L1 Ls ,AAceZdZdZdZy)DataCallbackProtocolc||jjdc}|j_||j|yyr+)factoryonDatacallback)rrds r/rz!DataCallbackProtocol.dataReceiveds5!%!4!4d4<<  = JJt  r2c||jjdc}|j_||j|yyr+ronLosterrback)rrrs r/rz#DataCallbackProtocol.connectionLosts5!%!4!4d4<<  = IIf  r2N)rrrrrr,r2r/rrs  r2rceZdZdZdZdZy)WritingProtocolxcN|jj|jyr+)rrbyters r/rzWritingProtocol.connectionMades TYY'r2cN|jjj|yr+rrs r/rzWritingProtocol.connectionLosts ##F+r2N)rrrrrrr,r2r/rrs D(,r2rcveZdZdZdZdZdZdZdZdZ dZ dd Z d Z d Z d ZdZdZdZdZdZdZy ) FakeContexta Introspectable fake of an C{OpenSSL.SSL.Context}. Saves call arguments for later introspection. Necessary because C{Context} offers poor introspection. cf. this U{pyOpenSSL bug}. @ivar _method: See C{method} parameter of L{__init__}. @ivar _options: L{int} of C{OR}ed values from calls of L{set_options}. @ivar _certificate: Set by L{use_certificate}. @ivar _privateKey: Set by L{use_privatekey}. @ivar _verify: Set by L{set_verify}. @ivar _verifyDepth: Set by L{set_verify_depth}. @ivar _mode: Set by L{set_mode}. @ivar _sessionID: Set by L{set_session_id}. @ivar _extraCertChain: Accumulated L{list} of all extra certificates added by L{add_extra_chain_cert}. @ivar _cipherList: Set by L{set_cipher_list}. @ivar _dhFilename: Set by L{load_tmp_dh}. @ivar _defaultVerifyPathsSet: Set by L{set_default_verify_paths} @ivar _ecCurve: Set by L{set_tmp_ecdh} rcf||_g|_d|_d|_tj |_y)NF)_method_extraCertChain_defaultVerifyPathsSet_ecCurverSESS_CACHE_SERVER_sessionCacheMode)rmethods r/__init__zFakeContext.__init__s0 !&+# "%!6!6r2c.|xj|zc_yr+)_optionsroptionss r/ set_optionszFakeContext.set_optionss  r2c||_yr+) _certificate)rrIs r/use_certificatezFakeContext.use_certificates 'r2c||_yr+) _privateKey)rrs r/use_privatekeyzFakeContext.use_privatekey %r2cyr+r,rs r/rzFakeContext.check_privatekeyr2c||_y)zo Set the mode. See L{SSL.Context.set_mode}. @param mode: See L{SSL.Context.set_mode}. N)_mode)rmodes r/set_modezFakeContext.set_modes  r2Nc||f|_yr+)_verify)rflagsrs r/ set_verifyzFakeContext.set_verifys h r2c||_yr+) _verifyDepth)rdepths r/set_verify_depthzFakeContext.set_verify_depths !r2c||_yr+)_sessionIDContext)rsessionIDContexts r/set_session_idzFakeContext.set_session_id s "2r2c||_y)zr Set the session cache mode on the context, as per L{SSL.Context.set_session_cache_mode}. Nr )r cacheModes r/set_session_cache_modez"FakeContext.set_session_cache_modes "+r2c|jS)zy Retrieve the session cache mode from the context, as per L{SSL.Context.get_session_cache_mode}. r,rs r/get_session_cache_modez"FakeContext.get_session_cache_modes %%%r2c:|jj|yr+)rappend)rcerts r/add_extra_chain_certz FakeContext.add_extra_chain_certs ##D)r2c||_yr+) _cipherList)r cipherLists r/set_cipher_listzFakeContext.set_cipher_list!rr2c||_yr+) _dhFilename)r dhfilenames r/ load_tmp_dhzFakeContext.load_tmp_dh$rr2cd|_y)z9 Set the default paths for the platform. TN)rrs r/set_default_verify_pathsz$FakeContext.set_default_verify_paths's '+#r2c||_y)z Set an ECDH curve. Should only be called by OpenSSL 1.0.1 code. @param curve: See L{OpenSSL.SSL.Context.set_tmp_ecdh} N)rrcurves r/ set_tmp_ecdhzFakeContext.set_tmp_ecdh-s  r2r+)rrr__doc__rr rrrrrr"r&r*r.r0r4r8r<r>rBr,r2r/rrs_"HH 7!(&'"2 +&*&&+ r2rc6eZdZdZereZdZdZdZdZ dZ y)ClientOptionsTestsz5 Tests for L{sslverify.optionsForClientTLS}. c|jttjdd}|j t |dy)z When passed a keyword parameter other than C{extraCertificateOptions}, L{sslverify.optionsForClientTLS} raises an exception just like a normal Python function would. alphabeta)hostnamesomeRandomThingzJoptionsForClientTLS() got an unexpected keyword argument 'someRandomThing'N) assertRaises TypeErrorrvoptionsForClientTLS assertEqualstr)rerrors r/test_extraKeywordsz%ClientOptionsTests.test_extraKeywords?sG !!   ) )" "   J  r2c|jttjd}dtj z}|j t||y)z If you pass L{bytes} as the hostname to L{sslverify.optionsForClientTLS} it immediately raises a L{TypeError}. snot-actually-a-hostname.comz6optionsForClientTLS requires text for host names, not N)rKrLrvrMbytesrrNrO)rrP expectedTexts r/test_bytesFailFastz%ClientOptionsTests.test_bytesFailFastQsL !! y446T  Eu~~ U  U\2r2cdtjd}|j|jy)zv If you pass a dNSName to L{sslverify.optionsForClientTLS} L{_hostnameIsDnsName} will be True example.comN)rvrM assertTrue_hostnameIsDnsNamers r/test_dNSNameHostnamez'ClientOptionsTests.test_dNSNameHostname^s& // > 223r2cdtjd}|j|jy)z} If you pass an IPv4 address to L{sslverify.optionsForClientTLS} L{_hostnameIsDnsName} will be False 127.0.0.1NrvrM assertFalserYrs r/test_IPv4AddressHostnamez+ClientOptionsTests.test_IPv4AddressHostnamefs( // < 334r2cdtjd}|j|jy)z} If you pass an IPv6 address to L{sslverify.optionsForClientTLS} L{_hostnameIsDnsName} will be False z::1Nr]rs r/test_IPv6AddressHostnamez+ClientOptionsTests.test_IPv6AddressHostnamens( //6 334r2N) rrrrCskipSSLskiprQrUrZr_rar,r2r/rErE7s* $ 3455r2rEceZdZdZdZdZy)$FakeChooseDiffieHellmanEllipticCurvezG A fake implementation of L{_ChooseDiffieHellmanEllipticCurve} cy)z& A no-op constructor. Nr,)r versionNumber openSSLlib openSSLcryptos r/r z-FakeChooseDiffieHellmanEllipticCurve.__init__|r1r2cy)z| A null configuration. @param ctx: An L{OpenSSL.SSL.Context} that would be configured. Nr,)rrs r/configureECDHCurvez7FakeChooseDiffieHellmanEllipticCurve.configureECDHCurver1r2N)rrrrCr rkr,r2r/rerews  r2recBeZdZdZereZdxZZdxZZ dZ dZ ddZ y)OpenSSLOptionsTestsMixinz A mixin for L{OpenSSLOptions} test cases creates client and server certificates, signs them with a CA, and provides a L{loopback} that creates TLS a connections with them. Nctdd\|_|_tdd\|_|_tddd|_td d d|_|j |j g|_|j|_y ) zK Create class variables of client and server certificates. Server Test CertificateserverOCNsClient Test CertificatesclientsCA Test Certificate 1sca1rOCA Test Certificatesca2N) rMsKeysCertcKeycCertcaCert1caCert2caCertsextraCertChainrs r/setUpzOpenSSLOptionsTestsMixin.setUps!0(Y!  4:!0(Y!  4:')AfMaP &)?FKAN  dll3 "llr2ch|j|jj|j|jjg}|j|j |j|j |j |j tj|dS)NT consumeErrors) serverPort stopListening clientConn disconnect onServerLostr2 onClientLostr DeferredList)rLs r/tearDownz!OpenSSLOptionsTestsMixin.tearDowns ?? & OO ) ) + ?? & OO & & (     ( HHT&& '    ( HHT&& '!!!488r2c|tjx|_}|tjx|_}|tj}t j }t |_||_||_t j}t|_||_tjd|||_ tjd|jjj |||_y)Nrr\)rDeferredrrr ServerFactoryrrr ClientFactoryrr listenSSLr connectSSLgetHostportr)rrrrrrrrs r/loopbackz!OpenSSLOptionsTestsMixin.loopbacks  /4~~/? ?D   /4~~/? ?D  >^^%F ..0 !5 + %  ..0 !0 + !++A}nM!,, 00277 r2NNN) rrrrCrbrcrrrrr}rrr,r2r/rmrms? ""J"&&L< + 9$  r2rmceZdZdZfdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(d'Z)d(Z*d)Z+d*Z,d+Z-d,Z.e/j`e1d-.ge._0d/Z2d0Z3d1Z4d2Z5d3Z6d4Z7d5Z8d6Z9xZ:S)7OpenSSLOptionsTestsz0 Tests for L{sslverify.OpenSSLOptions}. cXt||jtdty)z Same as L{OpenSSLOptionsTestsMixin.setUp}, but it also patches L{sslverify._ChooseDiffieHellmanEllipticCurve}. !_ChooseDiffieHellmanEllipticCurveN)superr}patchrvre)r __class__s r/r}zOpenSSLOptionsTests.setUps#    / 0 r2cd|jttj|jy)S C{privateKey} and C{certificate} make only sense if both are set. )rN)rKrqrvrrurs r/"test_constructorWithOnlyPrivateKeyz6OpenSSLOptionsTests.test_constructorWithOnlyPrivateKeys(   ;;   r2cd|jttj|jy)r)rIN)rKrqrvrrvrs r/#test_constructorWithOnlyCertificatez7OpenSSLOptionsTests.test_constructorWithOnlyCertificates(   ;;  r2c*tj|j|j}|j |j |j|j |j |j|j |jgy)zT Specifying C{privateKey} and C{certificate} initializes correctly. rrIN)rvrrurvrNrrIr|roptss r/,test_constructorWithCertificateAndPrivateKeyz@OpenSSLOptionsTests.test_constructorWithCertificateAndPrivateKeysk22yydjj  $))4 ))4::6 ,,b1r2c||jttj|j|j dy)zN C{verify} must not be C{True} without specifying C{caCerts}. T)rrIverifyN)rKrqrvrrurvrs r/0test_constructorDoesNotAllowVerifyWithoutCACertszDOpenSSLOptionsTests.test_constructorDoesNotAllowVerifyWithoutCACertss4    / /yy   r2c |jttj|j|j dd|j |jttj|j|j ddy)z C{verify}, C{requireCertificate}, and C{caCerts} must not be specified by the caller (to be I{any} value, even the default!) when specifying C{trustRoot}. TN)rrIrrr{)rrIrrequireCertificate)rKrLrvrrurvr{rs r//test_constructorDoesNotAllowLegacyWithTrustRootzCOpenSSLOptionsTests.test_constructorDoesNotAllowLegacyWithTrustRoot ss    / /yy LL      / /yy #  r2ctj|j|j|j}|j |j |j|j|jy)z2 It's currently a NOP, but valid. )rrIr{N)rvrrurvr{r^rrNrs r/*test_constructorAllowsCACertsWithoutVerifyz>OpenSSLOptionsTests.test_constructorAllowsCACertsWithoutVerify"sS22yydjj$,,  % t||4r2ctj|j|jd|j}|j |j |j|j|jy)zL Specifying C{verify} and C{caCerts} initializes correctly. T)rrIrr{N)rvrrurvr{rXrrNrs r/$test_constructorWithVerifyAndCACertsz8OpenSSLOptionsTests.test_constructorWithVerifyAndCACerts,sV22yy LL    $ t||4r2ctj|j|j|j}|j |j|jy)zt Setting C{extraCertChain} works if C{certificate} and C{privateKey} are set along with it. rrIr|N)rvrrurvr|rNrs r/test_constructorSetsExtraChainz2OpenSSLOptionsTests.test_constructorSetsExtraChain9sI 22yy ..  ,,d.A.ABr2cz|jttj|j|j y)zl A C{extraCertChain} without C{privateKey} doesn't make sense and is thus rejected. )rIr|N)rKrqrvrrvr|rs r/7test_constructorDoesNotAllowExtraChainWithoutPrivateKeyzKOpenSSLOptionsTests.test_constructorDoesNotAllowExtraChainWithoutPrivateKeyEs3    / / ..  r2cz|jttj|j|j y)zm A C{extraCertChain} without C{certificate} doesn't make sense and is thus rejected. )rr|N)rKrqrvrrur|rs r/7test_constructorDoesNotAllowExtraChainWithOutPrivateKeyzKOpenSSLOptionsTests.test_constructorDoesNotAllowExtraChainWithOutPrivateKeyQs3    / /yy..  r2ctj|j|j|j}t |_|j}|j|j|j|j|j|j|j|j|jy)z If C{extraCertChain} is set and all prerequisites are met, the specified chain certificates are added to C{Context}s that get created. rN) rvrrurvr|r_contextFactoryrrNrrrrrrs r/&test_extraChainFilesAreAddedIfSuppliedz:OpenSSLOptionsTests.test_extraChainFilesAreAddedIfSupplied]s 22yy ..  +oo COO4 S%5%56 ,,c.A.ABr2ctj|j|j|j}|j }|j |tjy)zR C{extraCertChain} doesn't break C{OpenSSL.SSL.Context} creation. rN) rvrrurvr|rassertIsInstancerrrs r/$test_extraChainDoesNotBreakPyOpenSSLz8OpenSSLOptionsTests.test_extraChainDoesNotBreakPyOpenSSLnsM22yy ..  oo c3;;/r2ctj|j|j}t|_|j }|j|jjd|jy)z If the user doesn't supply custom acceptable ciphers, a shipped secure default is used. We can't check directly for it because the effective cipher string we set varies with platforms. rrZN) rvrrurvrrrrN _cipherStringrsr6rs r/"test_acceptableCiphersAreAlwaysSetz6OpenSSLOptionsTests.test_acceptableCiphersAreAlwaysSetzs] 22yy   +oo ++227;S__Mr2c ttjGdd}tj|j |j |}t|_|j}|jd|jy)zB If acceptable ciphers are passed, they are used. ceZdZdZy)WOpenSSLOptionsTests.test_honorsAcceptableCiphersArgument..FakeAcceptableCiphersc.tjdgS)Nsentinel)rv OpenSSLCipher)r_s r/ selectCipherszeOpenSSLOptionsTests.test_honorsAcceptableCiphersArgument..FakeAcceptableCiphers.selectCipherss!// ;<.FakeDiffieHellmanParameters dh.paramsN)rrrr_dhFiler,r2r/FakeDiffieHellmanParametersr"Gs |,Gr2r%)rrI dhParametersN) rvrrurvrrrrNr$pathr:)rr%dhParamsrrs r/ test_dhParamsz!OpenSSLOptionsTests.test_dhParamsBsn  - -/022yy !  +oo 4<<AA3??Sr2c|jtjddtjdd|j tjddtjdddtjd}|j t t|d d |j|j|jd |_|j|j|jy ) zh Check that abbreviations used in certificates correctly map to complete names. ashello)rsOU) commonNameorganizationalUnitNamesxxx)rsr, emailAddresssabcdefg)rsCnrsbcdefgaN) rNrvDNDistinguishedNameassertNotEqualrKAttributeErrorrCrsr-)rdns r/#test_abbreviatingDistinguishedNamesz7OpenSSLOptionsTests.test_abbreviatingDistinguishedNamesTs  LLDX .  ' '   LLDX . LLDXF C \\Z ( .'2tTB  .  .r2c tjddddddd}|j}d D]<}|j|||d |j|j ||d >y) Ns common namesorganization namesorganizational unit name locality namesstate or province names country names email address)r-organizationNamer. localityNamestateOrProvinceName countryNamer/) common nameorganization nameorganizational unit name locality namestate or province name country name email addressz was not in inspect output.)rvr1inspectrtitlernsrKs r/testInspectDistinguishedNamez0OpenSSLOptionsTests.testInspectDistinguishedNameis} LL%1#>) 9')  IIK MA MM!Q1%'B C D MM!'')Q1%/J(K L Mr2ctjd}|j}dD]<}|j|||d|j|j ||d>|j d||j d|y)Nr8)r:)r=r>r?rArBrCz was in inspect output.r@z Locality Name)rvr1rD assertNotInrErrFs r/,testInspectDistinguishedNameWithoutAllFieldsz@OpenSSLOptionsTests.testInspectDistinguishedNameWithoutAllFieldss LL&6 7 IIK LA   QaU*A#B C   QWWYaU2I+J K L oq) oq)r2ctjjt}|j }|j }|j |jjddddddddd d d ddddddd d d d d|zgy)z Test that the C{inspect} method of L{sslverify.Certificate} returns a human-readable string containing some basic information about the certificate.  zCertificate For Subject:z5 Common Name: example.twistedmatrix.comz Country Name: USz4 Email Address: nobody@twistedmatrix.comz" Locality Name: Bostonz/ Organization Name: Twisted Matrix Labsz$ Organizational Unit Name: Securityz) State Or Province Name: MassachusettsrzIssuer:zSerial Number: 12345z7Digest: C4:96:11:00:30:C3:EC:EE:A3:55:AA:ED:8C:84:85:18zPublic Key with Hash: N) rvrwrxA_HOST_CERTIFICATE_PEM getPublicKeykeyHashrNrDsplit)rr.pkrQs r/test_inspectCertificatez+OpenSSLOptionsTests.test_inspectCertificates  ! ! ) )*@ A ^^ **,  IIK  d #*G0F4A6;G0F4A6;&I(72+  r2ctjjt}tjjt}tjjt}|j |j j|j |j|j j|j y)z L{PublicKey.matches} returns L{True} for keys from certificates with the same key, and L{False} for keys from certificates with different keys. N) rvrwrxrOA_PEER_CERTIFICATE_PEMrXrPmatchesr^)rhostAhostBpeerAs r/test_publicKeyMatchingz*OpenSSLOptionsTests.test_publicKeyMatchings %%--.DE%%--.DE%%--.DE **,44U5G5G5IJK ++-55e6H6H6JKLr2ctj}|j|jd|j }|j|j t jtjd}|j|jd|j }|j|j t jy)z The enableSessions argument sets the session cache mode; it defaults to False (at least until https://twistedmatrix.com/trac/ticket/9764 can be resolved). FT)enableSessionsN) rvrrNr]rr0rSESS_CACHE_OFFr )rrrs r/!test_enablingAndDisablingSessionsz5OpenSSLOptionsTests.test_enablingAndDisablingSessionss 557 //7  " 335s7I7IJ55TJ //6  " 335s7L7LMr2ctj|j|jtj d|jgddddddd }|j }|j||j|j||j}|jd|tj}|j||j|j|j|j|j|j|j|j tj |j#|j$|j|j&|jg|j|j(d|j+|j,|j+|j.|j+|j0|j+|j2|j#|j4|j#|j6y)zN Test that __setstate__(__getstate__()) round-trips properly. TF) rrIr rr{ verifyDepthr verifyOncerr]fixBrokenPeersenableSessionTickets_contextN)rvrrurvrrrassertIsrfassertIsNotNone __getstate__rK __setstate__rNrrIr rXrr{rbr^rrcrr]rdre)r firstOptscontextstaters r/$test_certificateOptionsSerializationz8OpenSSLOptionsTests.test_certificateOptionsSerializations77yy $$ZZL$ % !%  &&( gy112 W%&&( U+224 %  $))4 ))4::6 c&7&78  $  |4 ))1- 001 ) 112 ,,- ++, 112r2z/twisted\.internet\._sslverify\.*__[gs]etstate__)rrctjd}|j}|jd|j ddzy)zR Enabling session tickets should not set the OP_NO_TICKET option. Trer@NrvrrrNrrs r/%test_certificateOptionsSessionTicketsz9OpenSSLOptionsTests.test_certificateOptionsSessionTicketss>22Moo COOA.;22Noo S__Q%7*%DEr2ctj}jtjj j dtjd||jfdS)zw Check that anonymous connections are allowed when certificates aren't required on the server. F)rrIrrrcDj|tjSr+rNrrresultrs r/r0zKOpenSSLOptionsTests.test_allowedAnonymousClientConnection..$4++FO4H4HIr2rrrrvrrurv addCallbackrrs` r/%test_allowedAnonymousClientConnectionz9OpenSSLOptionsTests.test_allowedAnonymousClientConnectionsk !  / /99$**QV   / /5 I  !! I  r2c rtj}tj}jtjj j dj gdtjd||tj||gd}fd}|j|S)zt Check that anonymous connections are refused when certificates are required on the server. T)rrIrr{rFrwrrrc|\\}}\}}j|j|j|jtjt fj|jtjyr+)r^rvaluerErrorr r|cSuccesscResultsSuccesssResultrs r/ afterLostzLOpenSSLOptionsTests.test_refusedAnonymousClientConnection..afterLost=sj9? 6 h"58W   X &   X &  ! !'--#))^1L M  ! !'-- ;r2) rrrrvrrurvrrrrrrrs` r/%test_refusedAnonymousClientConnectionz9OpenSSLOptionsTests.test_refusedAnonymousClientConnection's ~~' ~~'   / /99 JJ #'    / /5 I%%      l;4 P <}}Y''r2cttj}tj}jtjj j ddtjddjg||tj||gd}fd}|j|S)zg Check that connecting with a certificate not accepted by the server CA fails. FrrIrrTrrr{rrc`|\\}}\}}j|j|yr+)r^rs r/rzIOpenSSLOptionsTests.test_failedCertificateVerification..afterLost`s39? 6 h"58W   X &   X &r2) rrrrvrrurvrxrrrs` r/"test_failedCertificateVerificationz6OpenSSLOptionsTests.test_failedCertificateVerificationIs ~~' ~~'   / /99 JJ#(    / / | &%      l;4 P ' }}Y''r2ctj}jtjj j ddtjddj g||jfdS)zi Test a successful connection with client certificate validation on server side. FrTrrxcDj|tjSr+rzr{s r/r0zLOpenSSLOptionsTests.test_successfulCertificateVerification..{r}r2r~rs` r/&test_successfulCertificateVerificationz:OpenSSLOptionsTests.test_successfulCertificateVerificationgs~ !  / /99 JJ#(    / /tzzl   !! I  r2c Xtj}jtjj j ddjgtjjjddj g||jfdS)zg Test a successful connection with validation on both server and client sides. T)rrIrrr{rxcDj|tjSr+rzr{s r/r0z_OpenSSLOptionsTests.test_successfulSymmetricSelfSignedCertificateVerification..r}r2) rrrrvrrurvrxrwrrs` r/9test_successfulSymmetricSelfSignedCertificateVerificationzMOpenSSLOptionsTests.test_successfulSymmetricSelfSignedCertificateVerification~s !  / /99 JJ#'    / /99 JJ#'    $!! I  r2cHtjd}tjj}|j |}tjd}tjj}|j |}|j |}|j ||dd}|j |} |j |} |j || dd} |j | } |j ||dd } |j | }|j ||d d }|j |}tj}|j| }|j| }j||| |jfd S)zT Check certificates verification building custom certificates data. client)r-servercyNTr,r5s r/r0z7OpenSSLOptionsTests.test_verification..r1r2cyrr,rs r/r0z7OpenSSLOptionsTests.test_verification..r1r2icyrr,rs r/r0z7OpenSSLOptionsTests.test_verification..r1r2cyrr,rs r/r0z7OpenSSLOptionsTests.test_verification..r1r2*rxcDj|tjSr+rzr{s r/r0z7OpenSSLOptionsTests.test_verification..r}r2) rvr2KeyPairgeneratecertificateRequestsignCertificateRequestnewCertificaterrrrr)rclientDN clientKey clientCertReqserverDN serverKey serverCertReqclientSelfCertReqclientSelfCertDataclientSelfCertserverSelfCertReqserverSelfCertDataserverSelfCertclientCertData clientCertserverCertDatarrrrs` r/test_verificationz%OpenSSLOptionsTests.test_verifications..(C%%..0 !44X> ..(C%%..0 !44X> %88B&== '# #112DE%88B&== '# #112DE"99 m_a --n= "99 m_b --n= !''7 ''7  j*V <!! I  r2);rrrrCr}rrrrrrrrrrrrrrrrrrrrrrrrrr r rrrrrrrr)r6rIrLrTr[r_rnrsuppressrrsrurrrrrr __classcell__)rs@r/rrs4     2   05 5 C    C" 0 N7&: > ::0:*8$8$8$8$ . $:2:2:2:2:2:0:.W6:.T$/*M.* ) V M N%3P  'F 5(1=F $ (D(< . 8+ r2rceZdZdZdZy)"OpenSSLOptionsECDHIntegrationTestsz? ECDH-related integration tests for L{OpenSSLOptions}. cts tdtj}j t j jjdt jjt j dt jj||jfd}|S)z@ Connections use ECDH when OpenSSL supports it. zOpenSSL does not support ECDH.F)rrIrr)rrrxcjtjjjdjjj\}|j j }jd|y)NrOECDH)rNrrr protocols getHandleget_cipher_namer)rclientProtocolcipherrs r/ assertECDHzVOpenSSLOptionsECDHIntegrationTests.test_ellipticCurveDiffieHellman..assertECDHse   S!8!8!B!BCQ G#66@@ ^#--/??AF MM&& )r2) r rrrrrvrrurvrTLSv1_3r)rrrs` r/test_ellipticCurveDiffieHellmanzBOpenSSLOptionsECDHIntegrationTests.test_ellipticCurveDiffieHellmans#$;< <!  / /99 JJ#('0';';'C'C    / /#('0';';'C'C       *  *  r2N)rrrrCrr,r2r/rrs &r2rc$eZdZdZereZdZdZy)DeprecationTestszo Tests for deprecation of L{sslverify.OpenSSLCertificateOptions}'s support of the pickle protocol. c||jtdddddftjjy)zT L{sslverify.OpenSSLCertificateOptions.__getstate__} is deprecated. Twistedra real persistence systemN)callDeprecatedrrvrrirs r/test_getstateDeprecationz)DeprecationTests.test_getstateDeprecations8  YAq )+F G  / / 1 > > r2c~|jtdddddftjjiy)zT L{sslverify.OpenSSLCertificateOptions.__setstate__} is deprecated. rrrrN)rrrvrrjrs r/test_setstateDeprecationz)DeprecationTests.test_setstateDeprecations;  YAq )+F G  / / 1 > >  r2N)rrrrCrbrcrrr,r2r/rrs   r2rc0eZdZdZereZdZdZdZdZ y)TrustRootTestsz Tests for L{sslverify.OpenSSLCertificateOptions}' C{trustRoot} argument, L{sslverify.platformTrust}, and their interactions. c:|jtdty)zG Patch L{sslverify._ChooseDiffieHellmanEllipticCurve}. rN)rrvrers r/r}zTrustRootTests.setUps  / 0 r2ctjtj}ttj fd|_|j|jjy)z Specifying a C{trustRoot} of L{sslverify.OpenSSLDefaultPaths} when initializing L{sslverify.OpenSSLCertificateOptions} loads the platform-provided trusted certificates via C{set_default_verify_paths}. rcSr+r,)r fcs r/r0z=TrustRootTests.test_caCertsPlatformDefaults..0sbr2N) rvrOpenSSLDefaultPathsrr TLSv1_METHODrrrXr)rrrs @r/test_caCertsPlatformDefaultsz+TrustRootTests.test_caCertsPlatformDefaults&sW 22335 )) *0  112r2ct\}}t|||}t||j}tt ||\}}}}} |j |j d|j |jjtj|jj} |j | jddddy)a- Specifying a C{trustRoot} of L{platformTrust} when initializing L{sslverify.OpenSSLCertificateOptions} causes certificates issued by a newly created CA to be rejected by an SSL connection using these options. Note that this test should I{always} pass, even on platforms where the CA certificates are not installed, as long as L{platformTrust} rejects completely invalid / unknown root CA certificates. This is simply a smoke test to make sure that verification is happening at all. rrrr2rratlsv1 alert unknown caN) rrrrr6rNrrtyperrrr) rrr chainedCertrrrsWrappedcWrappedrerrs r/(test_trustRootPlatformRejectsUntrustedCAz7TrustRootTests.test_trustRootPlatformRejectsUntrustedCA4s"C!D J*4ZH )$ 0E0EF 3H#o%'4 0(D , ,,11399=!!'' !Q*,DEr2c>t\}}t\}}t|t||jt||\}}}}} | j |j |j |j|j|jy)z Specifying a L{Certificate} object for L{trustRoot} will result in that certificate being the only trust root for a client. rN) rrrrr assertIsNonerrNrr) rcaCertrotherCa otherServerrrrrrs r/!test_trustRootSpecificCertificatez0TrustRootTests.test_trustRootSpecificCertificateSs ?@ @B3H/j6K6KL0zB4 0(D  (--. (9(9:r2N) rrrrCrbrcr}rrrr,r2r/rrs&   3F>;r2rceZdZdZereZddddddddfdZdZdZdZ d Z d Z d Z d Z eeed ZeeedZdZdZy)ServiceIdentityTestsz Tests for the verification of the peer's service's identity via the C{hostname} argument to L{sslverify.OpenSSLCertificateOptions}. cyr+r,rs r/r0zServiceIdentityTests.qr1r2TFc " !"#t|\!} i} d} td\}}|r| j||r|r|} ntd\}}|} tjd| jj | j d| }||j |st|\!}|r$d}|jtjd|d|i}| r|j| | s|j!| r|jtd !fd tjdi|}Gd d tj}Gd dtj}|#| tj} fd|_ tj}#fd|_ ||_ ||_t}t!|d||t!|d||"t#"fdfd|\}}}|j%|| #|fS)a Connect a server and a client. @param clientHostname: The I{client's idea} of the server's hostname; passed as the C{hostname} to the L{sslverify.OpenSSLCertificateOptions} instance. @type clientHostname: L{unicode} @param serverHostname: The I{server's own idea} of the server's hostname; present in the certificate presented by the server. @type serverHostname: L{unicode} @param serverContextSetup: a 1-argument callable invoked with the L{OpenSSL.SSL.Context} after it's produced. @type serverContextSetup: L{callable} taking L{OpenSSL.SSL.Context} returning L{None}. @param validCertificate: Is the server's certificate valid? L{True} if so, L{False} otherwise. @type validCertificate: L{bool} @param clientPresentsCertificate: Should the client present a certificate to the server? Defaults to 'no'. @type clientPresentsCertificate: L{bool} @param validClientCertificate: If the client presents a certificate, should it actually be a valid one, i.e. signed by the same CA that the server is checking? Defaults to 'yes'. @type validClientCertificate: L{bool} @param serverVerifies: Should the server verify the client's certificate? Defaults to 'no'. @type serverVerifies: L{bool} @param buggyInfoCallback: Should we patch the implementation so that the C{info_callback} passed to OpenSSL to have a bug and raise an exception (L{ZeroDivisionError})? Defaults to 'no'. @type buggyInfoCallback: L{bool} @param fakePlatformTrust: Should we fake the platformTrust to be the same as our fake server certificate authority, so that we can test it's being used? Defaults to 'no' and we just pass platform trust. @type fakePlatformTrust: L{bool} @param useDefaultTrust: Should we avoid passing the C{trustRoot} to L{ssl.optionsForClientTLS}? Defaults to 'no'. @type useDefaultTrust: L{bool} @return: the client TLS protocol, the client wrapped protocol, the server TLS protocol, the server wrapped protocol and an L{IOPump} which, when its C{pump} and C{flush} methods are called, will move data between the created client and server protocol instances @rtype: 5-L{tuple} of 4 L{IProtocol}s and L{IOPump} Nrrrcddz y)z Raise an exception. @param a: Arguments for an C{info_callback} @param k: Keyword arguments for an C{info_callback} rOrNr,)arKs r/brokenz9ServiceIdentityTests.serviceIdentitySetup..brokens Ar2_identityVerifyingInfoCallbackrI)clientCertificater6cSr+r,)serverCAsr/r0z;ServiceIdentityTests.serviceIdentitySetup..s8r2c*eZdZdZdZdZdZdZdZy)AServiceIdentityTests.serviceIdentitySetup..GreetingServerrNr2cN|jj|jyr+rrs r/rzPServiceIdentityTests.serviceIdentitySetup..GreetingServer.connectionMade$$T]]3r2c.|xj|z c_yr+rrs r/rzNServiceIdentityTests.serviceIdentitySetup..GreetingServer.dataReceived T! r2c||_yr+rrs r/rzPServiceIdentityTests.serviceIdentitySetup..GreetingServer.connectionLost "(r2) rrrrrrrrrr,r2r/rrs $HJD 4 " )r2rc*eZdZdZdZdZdZdZdZy)AServiceIdentityTests.serviceIdentitySetup..GreetingClientscheerio!r2NcN|jj|jyr+rrs r/rzPServiceIdentityTests.serviceIdentitySetup..GreetingClient.connectionMaderr2c.|xj|z c_yr+rrs r/rzNServiceIdentityTests.serviceIdentitySetup..GreetingClient.dataReceivedrr2c||_yr+rrs r/rzPServiceIdentityTests.serviceIdentitySetup..GreetingClient.connectionLostrr2) rrrrrrrrrr,r2r/GreetingClientrs "HDJ 4 " )r2rcSr+r,rsr/r0z;ServiceIdentityTests.serviceIdentitySetup..);r2cSr+r,rsr/r0z;ServiceIdentityTests.serviceIdentitySetup..rr2TrFc&jdSr+r)serverTLSFactorysr/r0z;ServiceIdentityTests.serviceIdentitySetup..$2248r2c&jdSr+r)clientTLSFactorysr/r0z;ServiceIdentityTests.serviceIdentitySetup..r r2rr,)rupdatervrroriginalrrClientTLSOptionsrMrrrrrrr7rr)$rclientHostnameserverHostnameserverContextSetupvalidCertificateclientPresentsCertificatevalidClientCertificateserverVerifiesbuggyInfoCallbackfakePlatformTrustuseDefaultTrustrotherpassClientCertclientCArbogusCAbogusrrr signaturerrrrrrrrrrrrr rs$ @@@@@r/serviceIdentitySetupz)ServiceIdentityTests.serviceIdentitySetupmsH AP*@J*  LL8L , $%!+!B8!L!&88 !,,55"++  :0023$En$U !Hk   JJ**0   0    ~  >   x  0  JJy/3C D22?Y?  )X.. ) )X.. ),-+- ((* !;  ((* !; $$. m5 / }E  8 8 8  v13EtKKr2cT|jdd\}}}}}|j|jd|j|jd|jj}|jj}|j |t |j |ty)z When a certificate containing an invalid hostname is received from the server, the connection is immediately dropped. zwrong-host.example.comcorrect-host.example.comr2N)r"rNrrrrr5r rrrrrrcErrsErrs r/test_invalidHostnamez)ServiceIdentityTests.test_invalidHostnames 483L3L $ &4 0(D , ,""((""(( d$56 d$45r2c|jdd\}}}}}|j|jd|j}|j}|j ||j |y)z} Whenever a valid certificate containing a valid hostname is received, connection proceeds normally. valid.example.comrNr"rNrrrr%s r/test_validHostnamez'ServiceIdentityTests.test_validHostname-sm 483L3L  4 0(D  6"""" $ $r2c|jddd\}}}}}|j|jd|j|jd|jj}|jj}|j |t j|j |t jy)z When an invalid certificate containing a perfectly valid hostname is received, the connection is aborted with an OpenSSL error. r*F)rr2Nr"rNrrrrrrr%s r/$test_validHostnameInvalidCertificatez9ServiceIdentityTests.test_validHostnameInvalidCertificate=s 483L3L  "4M4 0(D , ,""((""(( dCII. dCII.r2c|jdddd\}}}}}|j|jd|j|jd|jj}|jj}|j |t j|j |t jy)zu If we use the default trust from the platform, our dinky certificate should I{really} fail. r*FT)rrr2Nr.r%s r/*test_realCAsBetterNotSignOurBogusTestCertsz?ServiceIdentityTests.test_realCAsBetterNotSignOurBogusTestCertsQs 483L3L  " 4M4 0(D , ,""((""(( dCII. dCII.r2c|jdddd\}}}}}|j|jd|j}|j}|j ||j |y)z L{ssl.optionsForClientTLS} should be using L{ssl.platformTrust} by default, so if we fake that out then it should trust ourselves again. r*T)rrrNr+r%s r/test_butIfTheyDidItWouldWorkz1ServiceIdentityTests.test_butIfTheyDidItWouldWorkfsy 483L3L   " 4M4 0(D  6"""" $ $r2c|jddddd\}}}}}|j|jd|j}|j}|j ||j |y)z When the server verifies and the client presents a valid certificate for that verification by passing it to L{sslverify.optionsForClientTLS}, communication proceeds. r*T)rrrrNr+r%s r/test_clientPresentsCertificatez3ServiceIdentityTests.test_clientPresentsCertificatexs| 483L3L  !&* 4M4 0(D  6"""" $ $r2cN|jdddddd\}}}}}|j|jd|jj}|jj}|j |t j|j |t jy)z When the server verifies and the client presents an invalid certificate for that verification by passing it to L{sslverify.optionsForClientTLS}, the connection cannot be established with an SSL error. r*TF)rrrrr2Nr.r%s r/!test_clientPresentsBadCertificatez6ServiceIdentityTests.test_clientPresentsBadCertificates483L3L  !#(&* 4M4 0(D ,""((""(( dCII. dCII.r2clgfd}|jdd|\}}}}}|jdgy)z Specifying the C{hostname} argument to L{CertificateOptions} also sets the U{Server Name Extension } TLS indication field to the correct value. c2fd}|j|y)Ncbj|jjdy)NrZ)r2get_servernamert)connnamess r/servername_receivedzfServiceIdentityTests.test_hostnameIsIndicated..setupServerContext..servername_receiveds# T00299'BCr2set_tlsext_servername_callbackrr>r=s r/setupServerContextzIServiceIdentityTests.test_hostnameIsIndicated..setupServerContexts D  . ./B Cr2r*N)r"rN)rrBrrrrrr=s @r/test_hostnameIsIndicatedz-ServiceIdentityTests.test_hostnameIsIndicatedsL D 483L3L !46H4 0(D !4 56r2c g d} fd}|j|||\}}}}}|j |g|j|jd|j}|j} |j ||j | y)z0 Hostnames are encoded as IDNA. uhállo.example.comc2fd}|j|y)NcZt|j}j|yr+)r r;r2)r< serverIDNAr=s r/r>zcServiceIdentityTests.test_hostnameEncoding..setupServerContext..servername_receiveds"&t':':'<=  Z(r2r?rAs r/rBzFServiceIdentityTests.test_hostnameEncoding..setupServerContexts )  . ./B Cr2rNr+) rhellorBrrrrrr&r'r=s @r/test_hostnameEncodingz*ServiceIdentityTests.test_hostnameEncodings E D483L3L 5,4 0(D (  6"""" $ $r2cdGfdd}|}|jtj|dd|jtjtj|dy)z L{sslverify.simpleVerifyHostname} checks string equality on the commonName of a connection's certificate's subject, doing nothing if it matches and raising L{VerificationError} if it doesn't. zsomething.example.comceZdZfdZy)6ServiceIdentityTests.test_fallback..ConnectioncFt}|j_|S)z Fake of L{OpenSSL.SSL.Connection.get_peer_certificate}. @return: A certificate with a known common name. @rtype: L{OpenSSL.crypto.X509} )rrAr-)rr3names r/get_peer_certificatezKServiceIdentityTests.test_fallback..Connection.get_peer_certificates"v04  "- r2N)rrrrO)rNsr/ ConnectionrLs r2rPNnonsense)rgrvsimpleVerifyHostnamerKSimpleVerificationError)rrPr<rNs @r/ test_fallbackz"ServiceIdentityTests.test_fallbacksd '  |  * *41H I4    - -  * *    r2c|jddd\}}}}}|j|jd|j|jd|jj}|jj}|j |t |j |ttjf|jt }|j|y)a, pyOpenSSL isn't always so great about reporting errors. If one occurs in the verification info callback, it should be logged and the connection should be shut down (if possible, anyway; the app_data could be clobbered but there's no point testing for that). r$T)rr2N) r"rNrrrrZeroDivisionErrorr rrflushLoggedErrorsrX) rrrrrrr&r'errorss r/test_surpriseFromInfoCallbackz2ServiceIdentityTests.test_surpriseFromInfoCallbacks483L3L & &"4M4 0(D , ,""((""(( d$56 d%5syy$AB''(9: r2N)rrrrCrbrcr"r(r,r/r1r3r5r7rskipSNIrCrIrTrYr,r2r/rrds  ,"'#lL\6$ /(/* $ */0 GW77( GW  2 > r2rct\}}tj|jg}t ||j j|j|||\}}}} } | j |j| jfS)a Create the TLS connection and negotiate a next protocol. @param serverProtocols: The protocols the server is willing to negotiate. @param clientProtocols: The protocols the client is willing to negotiate. @param clientOptions: The type of C{OpenSSLCertificateOptions} class to use for the client. Defaults to C{OpenSSLCertificateOptions}. @return: A L{tuple} of the negotiated protocol and the reason the connection was lost. )rrrrrr) rrvOpenSSLCertificateAuthoritiesrrrrnegotiatedProtocolr) rrrrrrrrrrrs r/negotiateProtocolr^ s(I'J$M$77  " " I 0M$//88+44''# 0,FFHh JJL  % %x':': ;;r2c@eZdZdZereZnereZdZdZdZ dZ dZ y)NPNOrALPNTestsz NPN and ALPN protocol selection. These tests only run on platforms that have a PyOpenSSL version >= 0.15, and OpenSSL version 1.0.1 or later. ctj}|jtjj|vy)z When at least NPN is available on the platform, NPN is in the set of supported negotiation protocols. N)rvprotocolNegotiationMechanismsrXProtocolNegotiationSupportNPNrsupportedProtocolss r/)test_nextProtocolMechanismsNPNIsSupportedz8NPNOrALPNTests.test_nextProtocolMechanismsNPNIsSupported8 s1 'DDF  <<@@DVVWr2crddg}t||\}}|j|d|j|y)z When both ALPN and NPN are used, and both the client and server have overlapping protocol choices, a protocol is successfully negotiated. Further, the negotiated protocol is the first one in the list. h2http/1.1rrNr^rNrrrr]rs r/test_NPNAndALPNSuccessz%NPNOrALPNTests.test_NPNAndALPNSuccess@ sE K( ):%%* &J +U3 *%r2czgd}ddg}t||\}}|j|d|j|y)zm Client and server have different protocol lists: only the common element is chosen. )rirjsspdy/2spdy/3rjrkNrlrrrr]rs r/test_NPNAndALPNDifferentz'NPNOrALPNTests.test_NPNAndALPNDifferentN sJ :$k2):++* &J +[9 *%r2cpddg}t|g\}}|j||j|y)zy When one peer does not advertise any protocols, the connection is set up with no next protocol. rirjrkNr^rrms r/test_NPNAndALPNNoAdvertisez)NPNOrALPNTests.test_NPNAndALPNNoAdvertise\ sC K( ):%* &J ,- *%r2cddg}dg}t||\}}|j||j|jtj y)zh When the client and server have no overlap of protocols, the connection fails. rirjrprrN)r^rrNrrr)rrrr]rs r/test_NPNAndALPNNoOverlapz'NPNOrALPNTests.test_NPNAndALPNNoOverlapi sT !+.$+):++* &J ,- #))4r2N) rrrrCrbrcskipNPNrgrnrrrurxr,r2r/r`r`+ s3 X & & & 5r2r`c.eZdZdZereZdZyereZdZy) ALPNTestsa. ALPN protocol selection. These tests only run on platforms that have a PyOpenSSL version >= 0.15, and OpenSSL version 1.0.2 or later. This covers only the ALPN specific logic, as any platform that has ALPN will also have NPN and so will run the NPNAndALPNTest suite as well. ctj}|jtjj|vy)z When ALPN is available on a platform, protocolNegotiationMechanisms includes ALPN in the suported protocols. N)rvrbrXrcALPNres r/*test_nextProtocolMechanismsALPNIsSupportedz4ALPNTests.test_nextProtocolMechanismsALPNIsSupported s1 'DDF  <<AAEWWXr2N)rrrrCrbrcskipALPNr~r,r2r/r{r{x s'Y Yr2r{c8eZdZdZereZneresdZdZdZ dZ y)NPNAndALPNAbsentTestsz NPN/ALPN operations fail on platforms that do not support them. These tests only run on platforms that have a PyOpenSSL version < 0.15, an OpenSSL version earlier than 1.0.1, or an OpenSSL/cryptography built without NPN support. z+NPN and/or ALPN is present on this platformcNtj}|j|y)z} When neither NPN or ALPN are available on a platform, there are no supported negotiation protocols. N)rvrbr^res r/1test_nextProtocolMechanismsNoNegotiationSupportedzGNPNAndALPNAbsentTests.test_nextProtocolMechanismsNoNegotiationSupported s" 'DDF +,r2cFddg}|jtt||y)z A NotImplementedError is raised when using acceptableProtocols on a platform that does not support either NPN or ALPN. rirjrwN)rKNotImplementedErrorr^)rrs r/test_NPNAndALPNNotImplementedz3NPNAndALPNAbsentTests.test_NPNAndALPNNotImplemented s- K(    %%  r2cpd}d}t||\}}|j||j|y)z negotiatedProtocol return L{None} even when NPN/ALPN aren't supported. This works because, as neither are supported, negotiation isn't even attempted. Nrkrtrqs r/"test_NegotiatedProtocolReturnsNonez8NPNAndALPNAbsentTests.test_NegotiatedProtocolReturnsNone sC ):++* &J ,- *%r2N) rrrrCrbrcryrrrrr,r2r/rr s* H<-   &r2rceZdZdZy)_NotSSLTransportc|Sr+r,rs r/rz_NotSSLTransport.getHandle  r2N)rrrrr,r2r/rr sr2rceZdZdZdZdZy)_MaybeSSLTransportc|Sr+r,rs r/rz_MaybeSSLTransport.getHandle rr2cyr+r,rs r/rOz'_MaybeSSLTransport.get_peer_certificate rr2cyr+r,rs r/get_host_certificatez'_MaybeSSLTransport.get_host_certificate rr2N)rrrrrOrr,r2r/rr sr2rceZdZdZdZdZy)_ActualSSLTransportc|Sr+r,rs r/rz_ActualSSLTransport.getHandle rr2c\tjjtjSr+)rvrwrxrOrrs r/rz(_ActualSSLTransport.get_host_certificate $$,,-CDMMMr2c\tjjtjSr+)rvrwrxrVrrs r/rOz(_ActualSSLTransport.get_peer_certificate rr2N)rrrrrrOr,r2r/rr sNNr2rc8eZdZereZdZdZdZdZdZ dZ y)ConstructorsTestsc|jttjjt }|j t|jdy)z Verify that peerFromTransport raises an exception if the transport passed is not actually an SSL transport. non-TLSN) rKr rvrwpeerFromTransportrrXrO startswithrxs r/test_peerFromNonSSLTransportz.ConstructorsTests.test_peerFromNonSSLTransport I      ! ! 3 3    A)))45r2c|jttjjt }|j t|jdy)z Verify that peerFromTransport raises an exception if the transport passed is an SSL transport, but doesn't have a peer certificate. TLSN) rKr rvrwrrrXrOrrs r/test_peerFromBlankSSLTransportz0ConstructorsTests.test_peerFromBlankSSLTransport I      ! ! 3 3    A))%01r2c|jttjjt }|j t|jdy)z Verify that hostFromTransport raises an exception if the transport passed is not actually an SSL transport. rN) rKr rvrwhostFromTransportrrXrOrrs r/test_hostFromNonSSLTransportz.ConstructorsTests.test_hostFromNonSSLTransport rr2c|jttjjt }|j t|jdy)z Verify that hostFromTransport raises an exception if the transport passed is an SSL transport, but doesn't have a host certificate. rN) rKr rvrwrrrXrOrrs r/test_hostFromBlankSSLTransportz0ConstructorsTests.test_hostFromBlankSSLTransport rr2c|jtjjt j dy)z Verify that hostFromTransport successfully creates the correct certificate if passed a valid SSL transport. i90N)rNrvrwrr serialNumberrs r/test_hostFromSSLTransportz+ConstructorsTests.test_hostFromSSLTransport 6   ! ! 3 3#% ln   r2c|jtjjt j dy)z Verify that peerFromTransport successfully creates the correct certificate if passed a valid SSL transport. i:0N)rNrvrwrrrrs r/test_peerFromSSLTransportz+ConstructorsTests.test_peerFromSSLTransport rr2N) rrrrbrcrrrrrrr,r2r/rr s( 6 2 6 2    r2rc6eZdZdZereZdZdZdZdZ dZ y)!MultipleCertificateTrustRootTestszH Test the behavior of the trustRootFromCertificates() API call. ctjjt}tjjt }tj ||g}t||jj|j\}}}}}|j|jd|j|jy)z L{trustRootFromCertificates} accepts either a L{sslverify.Certificate} or a L{sslverify.PrivateCertificate} instance. rrrrN)rvr{rx A_KEYPAIRrwrOtrustRootFromCertificatesrrrrNrrr) r privateCertr3mtrrsWrapcWraprs r/+test_trustRootFromCertificatesPrivatePubliczMMultipleCertificateTrustRootTests.test_trustRootFromCertificatesPrivatePublic4 s  22::9E $$,,-CD  0 0+t1D E.K"--66)22. *ud ]3 %**+r2ctdd\}}tjjtj|tj |}tj |g}t||jj|j\}}}}} |j|jd|j|jy)z L{trustRootFromCertificates} called with a single self-signed certificate will cause L{optionsForClientTLS} to accept client connections to a server with that certificate. rorprqrrN)rMrvr{fromCertificateAndKeyPairrwrrrrrrNrrr) rkeyr3 selfSignedtrustrrrrrs r/)test_trustRootSelfSignedServerCertificatezKMultipleCertificateTrustRootTests.test_trustRootSelfSignedServerCertificateJ s $&@YO T11KK  ! !$ '   c " 33ZLA.K!,,55(11. *ud ]3 %**+r2ct\}}tj|g}t||jj |j \}}}}}|j |jd|j|jy)z L{trustRootFromCertificates} called with certificate A will cause L{optionsForClientTLS} to accept client connections to a server with certificate B where B is signed by A. rrN) rrvrrrrrNrrr) rrrrrrrrrs r/2test_trustRootCertificateAuthorityTrustsConnectionzTMultipleCertificateTrustRootTests.test_trustRootCertificateAuthorityTrustsConnectionb s ?@ 33VH=.K!,,55(11. *ud ]3 %**+r2ctdd\}}tjjtj|tj |}tjtddd}tj |g}t||jj|j\}}}} } |j| jd|j| jjtj| jj } |j| j"d d d d y ) z L{trustRootFromCertificates} called with certificate A will cause L{optionsForClientTLS} to disallow any connections to a server with certificate B where B is not signed by A. rorprqrts unknown CArOrr2rrarN)rMrvr{rrwrrrrrrNrrrrrrr) rrr3r untrustedCertrrrrrrrs r/'test_trustRootFromCertificatesUntrustedzIMultipleCertificateTrustRootTests.test_trustRootFromCertificatesUntrustedv s $&@YO T11KK  ! !$ '   c " "-- 4 G J 33]OD.K!,,55(11. *ud S) )).. :$$ !Q*,DEr2ctjjt}|j}|j t tj|g}|jd|jdy)z} L{trustRootFromCertificates} rejects any L{OpenSSL.crypto.X509} instances in the list passed to it. zBcertificates items must be twisted.internet.ssl.CertBase instancesrN) rvr{rxrrrKrLrrNr)rprivatecertX509rs r/,test_trustRootFromCertificatesOpenSSLObjectszNMultipleCertificateTrustRootTests.test_trustRootFromCertificatesOpenSSLObjects se ..66yA##%%   / / J  S NN1  r2N) rrrrCrbrcrrrrrr,r2r/rr, s,,,,0,(!FF r2rc4eZdZdZereZdZdZdZdZ dZ y)OpenSSLCipherTestsz> Tests for twisted.internet._sslverify.OpenSSLCipher. z CIPHER-STRINGc|j|jtj|jjy)zU The first argument passed to the constructor becomes the full name. N)rN cipherNamervrfullNamers r/test_constructorSetsFullNamez/OpenSSLCipherTests.test_constructorSetsFullName s0  OOY44T__ENN r2ctj|j}|j|t t |dtjiy)zC C{repr(cipher)} returns a valid constructor call. rN)rvrrrNevalrepr)rrs r/ test_reprzOpenSSLCipherTests.test_repr sA((9  Df9P9P'QR r2ctj|j}tj|j}|j||y)zN Equal type and C{fullName} means that the objects are equal. N)rvrrrN)rcipher1cipher2s r/test_eqSameClassz#OpenSSLCipherTests.test_eqSameClass s<))$//:))$//: '*r2cGfdd}jtjj|y)ze If ciphers have the same name but different types, they're still different. c(eZdZWjZy)HOpenSSLCipherTests.test_eqSameNameDifferentType..DifferentCipherN)rrrrrrsr/DifferentCipherr s Hr2rN)r3rvrr)rrs` r/test_eqSameNameDifferentTypez/OpenSSLCipherTests.test_eqSameNameDifferentType s5  ' '   # #DOO 4   r2N) rrrrCrbrcrrrrrr,r2r/rr s* J  +  r2rc*eZdZdZereZdZdZdZy)ExpandCipherStringTestszD Tests for twisted.internet._sslverify._expandCipherString. c~|jttjdtj dy)zU If the expanded cipher list is empty, an empty L{list} is returned. rrN)rNtuplerv_expandCipherStringrrrs r/!_test_doesNotStumbleOverEmptyListz9ExpandCipherStringTests._test_doesNotStumbleOverEmptyList s.  GY222s7H7H!L r2cd}ttj|_|j t jdfd|j tjt jdtjdy)zf Only no cipher matches get swallowed, every other SSL error gets propagated. c2tjgdg)N)rrr)rr)rs r/raiserzIExpandCipherStringTests.test_doesNotSwallowOtherSSLErrors..raiser s))\N+ +r2rcSr+r,)rrs r/r0zKExpandCipherStringTests.test_doesNotSwallowOtherSSLErrors.. ssr2ALLrN) rrrr8rrvrKrr)rrrs @r/!test_doesNotSwallowOtherSSLErrorsz9ExpandCipherStringTests.test_doesNotSwallowOtherSSLErrors s`  , #++,$ 9==)];  IIy44eS=N=NPQ r2ctjdtjd}|j |t g}|D]3}t jj|r#|j|5|jg|y)zn L{sslverify._expandCipherString} always returns a L{tuple} of L{interfaces.ICipher}. rrN) rvrrrrrrICipher providedByr2rN)rciphersr r.s r/test_returnsTupleOfICiphersz3ExpandCipherStringTests.test_returnsTupleOfICiphers ss //s7H7H!L gu- A%%003 Q  U#r2N) rrrrCrbrcrrrr,r2r/rr s   $ $r2rc*eZdZdZereZdZdZdZy)AcceptableCiphersTestszI Tests for twisted.internet._sslverify.OpenSSLAcceptableCiphers. ctjt}|jt|j ty)zG If no ciphers are available, nothing can be selected. N)rvOpenSSLAcceptableCiphersrrNrracs r/&test_selectOnEmptyListReturnsEmptyListz=AcceptableCiphersTests.test_selectOnEmptyListReturnsEmptyList s5 / / 8 ""2"257";z]AcceptableCiphersTests.test_fromOpenSSLCipherStringExpandsToTupleOfCiphers..7 s!QI--88;Qs)+N)rvrfromOpenSSLCipherStringr_ciphersrrXallrs r/3test_fromOpenSSLCipherStringExpandsToTupleOfCipherszJAcceptableCiphersTests.test_fromOpenSSLCipherStringExpandsToTupleOfCiphers0 sI  / / G G N bkk51 QR[[QQRr2N) rrrrCrbrcrrrr,r2r/rr s!= $Sr2rc.eZdZdZereZedZdZy)DiffieHellmanParametersTestszD Tests for twisted.internet._sslverify.OpenSSLDHParameters. r#ctjj|j}|j |j|j y)zl Calling C{fromFile} with a filename returns an instance with that file name saved. N)rvOpenSSLDiffieHellmanParametersfromFilefilePathrNr$)rparamss r/ test_fromFilez*DiffieHellmanParametersTests.test_fromFileC s6 99BB4==Q 7r2N) rrrrCrbrcrr r r,r2r/rr: s  %H8r2rceZdZdZdZdZy) FakeLibStatea State for L{FakeLib} @param setECDHAutoRaises: An exception L{FakeLib.SSL_CTX_set_ecdh_auto} should raise; if L{None}, nothing is raised. @ivar ecdhContexts: A list of SSL contexts with which L{FakeLib.SSL_CTX_set_ecdh_auto} was called @type ecdhContexts: L{list} of L{OpenSSL.SSL.Context}s @ivar ecdhValues: A list of boolean values with which L{FakeLib.SSL_CTX_set_ecdh_auto} was called @type ecdhValues: L{list} of L{boolean}s setECDHAutoRaises ecdhContexts ecdhValuesc.||_g|_g|_yr+r)rrs r/r zFakeLibState.__init___ s!2r2NrrrrC __slots__r r,r2r/r r L s DIr2r ceZdZdZdZdZy)FakeLibz An introspectable fake of cryptography's lib object. @param state: A L{FakeLibState} instance that contains this fake's state. c||_yr+_staterrms r/r zFakeLib.__init__m  r2c|jjj||jjj||jj|jjy)a Record the context and value under in the C{_state} instance variable. @see: L{FakeLibState} @param ctx: An SSL context. @type ctx: L{OpenSSL.SSL.Context} @param value: A boolean value @type value: L{bool} N)rrr2rr)rrrs r/SSL_CTX_set_ecdh_autozFakeLib.SSL_CTX_set_ecdh_autop sY   '', %%e, ;; ( ( 4++// / 5r2N)rrrrCr rr,r2r/rre s0r2rceZdZdZdZdZy) FakeLibTestsz Tests for L{FakeLib}. c@td}t|}|j|j|j|jd\}}|j |||j |j|g|j |jdgy)zh L{FakeLib.SSL_CTX_set_ecdh_auto} records context and value it was called with. NrCONTEXTTT)r r assertNotrrrrNrrmlibrlrs r/test_SSL_CTX_set_ecdh_autoz'FakeLibTests.test_SSL_CTX_set_ecdh_auto s t4en u))* u''(( !!'51 ++gY7 ))D62r2chtt}t|}|j|j|j|j d\}}|j t|j|||j|j|g|j|j dgy)z L{FakeLib.SSL_CTX_set_ecdh_auto} raises the exception provided by its state, while still recording its arguments. r!r"TN) r rqrr$rrrKrrNr%s r/ test_SSL_CTX_set_ecdh_autoRaisesz-FakeLibTests.test_SSL_CTX_set_ecdh_autoRaises s z:en u))* u''(( *c&?&?%P ++gY7 ))D62r2N)rrrrCr'r)r,r2r/rr s 3 3r2rceZdZdZdZdZy)FakeCryptoStatea State for L{FakeCrypto} @param getEllipticCurveRaises: What L{FakeCrypto.get_elliptic_curve} should raise; L{None} and it won't raise anything @param getEllipticCurveReturns: What L{FakeCrypto.get_elliptic_curve} should return. @ivar getEllipticCurveCalls: The arguments with which L{FakeCrypto.get_elliptic_curve} has been called. @type getEllipticCurveCalls: L{list} getEllipticCurveRaisesgetEllipticCurveReturnsgetEllipticCurveCallsc.||_||_g|_yr+r,)rr-r.s r/r zFakeCryptoState.__init__ s '=#'>$%'"r2Nrr,r2r/r+r+ s I (r2r+ceZdZdZdZdZy) FakeCryptozy An introspectable fake of pyOpenSSL's L{OpenSSL.crypto} module. @ivar state: A L{FakeCryptoState} instance c||_yr+rrs r/r zFakeCrypto.__init__ rr2c|jjj||jj|jj|jjS)a A fake that records the curve with which it was called. @param curve: see L{crypto.get_elliptic_curve} @return: see L{FakeCryptoState.getEllipticCurveReturns} @raises: see L{FakeCryptoState.getEllipticCurveRaises} )rr/r2r-r.r@s r/get_elliptic_curvezFakeCrypto.get_elliptic_curve sL ))007 ;; - - 9++44 4{{222r2N)rrrrCr r5r,r2r/r2r2 s  3r2r2c"eZdZdZdZdZdZy)FakeCryptoTestsz" Tests for L{FakeCrypto}. ctdd}t|}|jd|j|jdgy)zk L{FakeCrypto.test_get_elliptic_curve} records the curve with which it was called. Nr-r.z a curve name)r+r2r5rNr/rrmcryptos r/&test_get_elliptic_curveRecordsArgumentz6FakeCryptoTests.test_get_elliptic_curveRecordsArgument sG  #'$( E"!!.1 44~6FGr2cd}td|}t|}|j|jd||j |j dgy)z L{FakeCrypto.test_get_elliptic_curve} returns the value specified by its state object and records what it was called with. objectNr9zanother curve name)r+r2rgr5rNr/)r returnValuermr;s r/test_get_elliptic_curveReturnsz.FakeCryptoTests.test_get_elliptic_curveReturns s_  #'$/ E"  % %&: ;   447K6LMr2cttd}t|}|jt|jd|j |j dgy)zs L{FakeCrypto.test_get_elliptic_curve} raises the exception specified by its state object. Nr9zyet another curve name)r+rqr2rKr5rNr/r:s r/test_get_elliptic_curveRaisesz-FakeCryptoTests.test_get_elliptic_curveRaises s[  #-t E"    % % $   ' ' % & r2N)rrrrCr<r@rBr,r2r/r7r7 s HN$ r2r7cNeZdZdZereZdZdZdZdZ dZ dZ dZ d Z d Zd Zy ) %ChooseDiffieHellmanEllipticCurveTestsaN Tests for L{sslverify._ChooseDiffieHellmanEllipticCurve}. @cvar OPENSSL_110: A version number for OpenSSL 1.1.0 @cvar OPENSSL_102: A version number for OpenSSL 1.0.2 @cvar OPENSSL_101: A version number for OpenSSL 1.0.1 @see: U{https://wiki.openssl.org/index.php/Manual:OPENSSL_VERSION_NUMBER(3)} ii iOctd|_t|j|_t dd|_t |j |_ttj|_ y)NFr!)r.r-) r libStaterr&r+ cryptoStater2r;rrrrlrs r/r}z+ChooseDiffieHellmanEllipticCurveTests.setUp- sV$u= 4==)*$( !!1!12 "3#4#45 r2ctj|j|j|j}|j |j |j|jj|j|jj|j|jj|j|j jy)z No configuration of contexts occurs under OpenSSL 1.1.0 and later, because they create contexts with secure ECDH curves. @see: U{http://twistedmatrix.com/trac/ticket/9210} rhriN)rvr OPENSSL_110r&r;rkrlr^rFrrrGr/rrrchoosers r/test_openSSL110z5ChooseDiffieHellmanEllipticCurveTests.test_openSSL1107 s==   xx++  ""4<<0 334 112 ))??@ $,,//0r2ctjtj}tj|j |j |j}|j||j|jj|jg|j|jjdg|j|jj |j#|j$j&y)z OpenSSL 1.0.2 does not set ECDH curves by default, but C{SSL_CTX_set_ecdh_auto} requests that a context choose a secure set curves automatically. rITN)rrrrvr OPENSSL_102r&r;rkrNrFrrfrr^rGr/rrlrrrlrLs r/test_openSSL102z5ChooseDiffieHellmanEllipticCurveTests.test_openSSL102J s ++c//0==   xx++  ""7+ 33g6F6F5GH 11D6: ))??@ $,,//0r2ct|j_tjtj }t j|j|j|j}|j||j|jj|jg|j|jjdg|j!|j"j$y)z An exception raised by C{SSL_CTX_set_ecdh_auto} under OpenSSL 1.0.2 is suppressed because ECDH is best-effort. rITN) BaseExceptionrFrrrrrvrrOr&r;rkrNrrfrr^rGr/rPs r/ test_openSSL102SetECDHAutoRaiseszFChooseDiffieHellmanEllipticCurveTests.test_openSSL102SetECDHAutoRaises] s +8 '++c//0==   xx++  ""7+ 33g6F6F5GH 11D6: ))??@r2cdx|j_}tj|j|j |j }|j|j|j|jj|j|jj|j|jjtjg|j!|jj"|y)z OpenSSL 1.0.1 does not set ECDH curves by default, nor does it expose L{SSL_CTX_set_ecdh_auto}. Instead, a single ECDH curve can be set with L{OpenSSL.SSL.Context.set_tmp_ecdh}. z curve objectrIN)rGr.rvr OPENSSL_101r&r;rkrlr^rFrrrNr/_defaultCurveNamergr)rrArLs r/test_openSSL101z5ChooseDiffieHellmanEllipticCurveTests.test_openSSL101o s .set_tmp_ecdh s r2rIN)rlrBrvrrVr&r;rkr^rFrrrNrGr/rW)rrBrLs r/test_openSSL101SetECDHRaiseszBChooseDiffieHellmanEllipticCurveTests.test_openSSL101SetECDHRaises s  %1 !==   xx++  ""4<<0 334 112     2 2  ( ( ) r2ct|j_tj|j |j |j}|j|j|j|jj|j|jj|j|jjy)zy Contexts created under an OpenSSL 1.0.1 that doesn't support ECC have no configuration applied. rIN)rqrGr-rvrrVr&r;rkrlr^rFrrrrrKs r/test_openSSL101NoECCz:ChooseDiffieHellmanEllipticCurveTests.test_openSSL101NoECC s 3=/==   xx++  ""4<<0 334 112 $,,//0r2N)rrrrCrbrcrJrOrVr}rMrQrTrXr[r]r,r2r/rDrD sD KKK61&1&A$4, 21r2rDc0eZdZdZereZdZdZdZdZ y) KeyPairTestsz) Tests for L{sslverify.KeyPair}. c.tddd|_y)z* Create test certificate. rorprqrN)rMrurs r/r}zKeyPairTests.setUp s$&@YOPQR r2c|jtdddddftj|jj y)zB L{sslverify.KeyPair.__getstate__} is deprecated. rrrrN)rrrvrrurirs r/rz%KeyPairTests.test_getstateDeprecation s>  YAq )+F G   dii ( 5 5 r2ctj|jj}|j t dddddftj|jj |y)zA {sslverify.KeyPair.__setstate__} is deprecated. rrrrN)rvrrurrrrjrs r/rz%KeyPairTests.test_setstateDeprecation s^!!$)),113  YAq )+F G   dii ( 5 5  r2ctdjjd}|j}tj j |y)Nz twisted.testzcert.pem.no_trailing_newline)rr sibling getContentr)rwrx)rnoTrailingNewlineKeyPemPathcertPEMs r/test_noTrailingNewlinePemCertz*KeyPairTests.test_noTrailingNewlinePemCert sC&/&?&H&H&P&P *' #.88: (r2N) rrrrCrbrcr}rrrhr,r2r/r_r_ s&S    )r2r_cVeZdZdZereZdZejdge_dZ y)SelectVerifyImplementationTestsz3 Tests for L{_selectVerifyImplementation}. ctd5dtjd<tj}tj tj tjf}|j||dddy#1swYyxYw)z If I{service_identity} cannot be imported then L{_selectVerifyImplementation} returns L{simpleVerifyHostname} and L{SimpleVerificationError}. service_identityN) rsysmodulesrv_selectVerifyImplementationrRsimpleVerifyIPAddressrSrN)rr|expecteds r/test_dependencyMissingz6SelectVerifyImplementationTests.test_dependencyMissing ss . / /.2CKK* +::>BzEYou do not have a working installation of the service_identity module)rcXtd5dtjd<tjdddt d|j D\}d}|j|d||j|dd|j|dd y#1swYmxYw) z If I{service_identity} cannot be imported then L{_selectVerifyImplementation} emits a L{UserWarning} advising the user of the exact error. rlNc38K|]}|dtk(r|yw)rN) UserWarning)rwarnings r/rzPSelectVerifyImplementationTests.test_dependencyMissingWarning.. s% z"k1  saYou do not have a working installation of the service_identity module: 'import of service_identity halted; None in sys.modules'. Please install it from and make sure all of its dependencies are satisfied. Without the service_identity module, Twisted can perform only rudimentary TLS client hostname verification. Many valid certificate/hostname mappings may be rejected.rfilenamerlinenor)rrmrnrvrolistrrN)rrvexpectedMessages r/test_dependencyMissingWarningz=SelectVerifyImplementationTests.test_dependencyMissingWarning s . / 4.2CKK* +  1 1 3 4  --/   =  +_= ,b1 *A.= 4 4s (B  B)N) rrrrCrbrcrrrrr{r,r2r/rjrj s;/$  * '#$/r2rj)rWr+r)rCr_ itertoolsrmunittestrzope.interfacer incrementalrtwisted.internetrrrr twisted.internet._idnar twisted.internet.errorr r r twisted.internet.taskrtwisted.python.compatrtwisted.python.filepathrtwisted.python.modulesrtwisted.python.reflectrtwisted.test.iosimrtwisted.test.test_twistedr twisted.trialrtwisted.trial.unittestrrrrbrZryrrnrrOpenSSL.cryptorrrrr cryptographyr!cryptography.hazmat.backendsr"cryptography.hazmat.primitivesr#)cryptography.hazmat.primitives.asymmetricr$,cryptography.hazmat.primitives.serializationr%r&r'cryptography.x509.oidr(r)rrrset_npn_advertise_callbackrr4set_alpn_select_callbackr4rvtwisted.internet.sslr5r6twisted.protocols.tlsr7rOrVrr rdrercountr:rMrrrrrrrrrrErermrrrrrr^r`r{rrrrrrrrrrr rrr+r2r7rDr_rjr,r2r/rsn   &AA,UU'.,,074JJ    VV!<5= .$ ckk#++, &&~6Hckk#++, $$^43GGGH8E9** h  ( ( 0 0 > I I K $IOO% $]"@:Hz%:X /Bd2 8,, ,h'',uup=5,=5@  &E E Ps 2Hs l+)A8+\ * :N;XN;be .e P <>J5XJ5ZYY20&H0&f NNJ J Z} } @/ / d.$h.$b(SX(SV888$200