
    DfV                        d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
ZddlZddlZddlZddlZddlmZmZmZ ddlmZmZmZ ddlmZmZmZ ddlmZmZ ddlmZm Z m!Z!m"Z"m#Z# dd	l$m%Z%  e& ej'        d
                    Z(eod ej)        d          v Z*ej+        ,                    d          Z-ej.        /                    ej.        j0                  ,                    d          Z1ej2        dd         dk    Z3ej4        ej.        j5        ej6        ej.        j7        ej8        ej.        j7        ej.        j9        z   iZ:ej;        <                     e#d           d          Z= G d de%          Z>d Z?ej@        d             ZAej@        d             ZBej@        d             ZCej@        d             ZDej@        d             ZEej@        d             ZFd ZGej@        d             ZHej;        I                    dd          d              ZJej;        I                    dd          ej;        I                    d!d"          ej;        I                    d#ej4        ej6        ej8        f          ej;        K                    eoed$d%&          d'                                                 ZLej;        I                    d ejM        d(ej;        K                    eoe3d)d%&          *          d+f          ej;        I                    d,ej4        d%fej4        d-fej6        d%fej6        d-fej8        d-ff          d.                         ZNej;        I                    d/ee f          d0             ZOej;        I                    dd          ej;        I                    d/e ejM        e e=*          f          ej;        P                    d1d2          d3                                     ZQdS )4zTests for TLS support.    N   )btonntobntou)IS_ABOVE_OPENSSL10IS_CIIS_PYPY)IS_LINUXIS_MACOS
IS_WINDOWS)
HTTPServerget_ssl_adapter_class)ANY_INTERFACE_IPV4ANY_INTERFACE_IPV6EPHEMERAL_PORT_get_conn_data_probe_ipv6_sock)
Gateway_10GITHUB_WORKFLOWs(   Microsoft Windows Server 2016 Datacenter)
systeminfoLibreSSLs   OpenSSL 1.0.)   
   z::1zYIPv6 is disabled (for example, under Travis CI which runs under GCE supporting only IPv4))reasonc                   "     e Zd ZdZ fdZ xZS )HelloWorldGatewayz0Gateway responding with Hello World to root URI.c                 L   | j         }t          |j                  }|dk    r2d|_        |                                 |                    d           dS |dk    rd|_        |                                 |                                 }|                    d           |                    d           t          |           |                    t          j
        |                              d                     dS t          t          |                                           S )	z$Respond with dummy content via HTTP./s   200 OKs   Hello world!N/envzwsgi.errorsz
wsgi.inpututf-8)reqr   uristatusensure_headers_sentwriteget_environpopprintjsondumpsencodesuperr   respond)selfr!   req_urienv	__class__s       D/var/www/media/lib/python3.11/site-packages/cheroot/test/test_ssl.pyr-   zHelloWorldGateway.respondF   s    hsw--c>>"CJ##%%%IIo&&&Ff"CJ##%%%""$$CGGM"""GGL!!!#JJJIIdjoo,,W55666F&--55777    )__name__
__module____qualname____doc__r-   __classcell__)r1   s   @r2   r   r   C   s>        ::8 8 8 8 8 8 8 8 8r3   r   c                    t          | t                    }||_        t          j        |j                                                   |j        st          j	        d           |j        |
                    |j                   |S )z7Create and start an HTTP server bound to ``bind_addr``.)	bind_addrgateway)targetg?)r   r   ssl_adapter	threadingThread
safe_startstartreadytimesleepaddfinalizerstop)r:   r=   request
httpservers       r2   make_tls_http_serverrI   \   s    !  J
 )JJ122288::: 
3   )))r3   c                 8    t          j        t          |           S )z(Provision a server creator as a fixture.rG   )	functoolspartialrI   rK   s    r2   tls_http_serverrN   o   s     17CCCCr3   c                  (    t          j                    S )z,Provide a certificate authority via fixture.)trustmeCA r3   r2   carS   u   s     :<<r3   c              #   v   K   | j                                         5 }|V  ddd           dS # 1 swxY w Y   dS )z=Provide a certificate authority certificate file via fixture.N)cert_pemtempfile)rS   ca_cert_pems     r2   tls_ca_certificate_pem_pathrX   {   s       
				 ;                    .22c                 v    t          t                    \  }}}|                     t          |                    S )z'Provide a leaf certificate via fixture.)r   r   
issue_certr   )rS   	interface_host_ports       r2   tls_certificater_      s1     --?@@Iue==i)))r3   c              #   v   K   | j                                         5 }|V  ddd           dS # 1 swxY w Y   dS )z6Provide a certificate chain PEM file path via fixture.N)private_key_and_cert_chain_pemrV   )r_   rU   s     r2   tls_certificate_chain_pem_pathrb      s       
	7	@	@	B	B h                 rY   c              #   v   K   | j                                         5 }|V  ddd           dS # 1 swxY w Y   dS )z<Provide a certificate private key PEM file path via fixture.N)private_key_pemrV   )r_   cert_key_pems     r2   $tls_certificate_private_key_pem_pathrf      s       
	(	1	1	3	3 |                 rY   c                    t          |j        t                    rdS |                     |j        t	          |j                  d                    t          j        |j        |j        |j	                            f           dS )z@Append uncaught exception ``args`` in threads to ``exceptions``.N )

issubclassexc_type
SystemExitappendstr	exc_valuejoin	tracebackformat_exceptionexc_traceback)
exceptionsargss     r2   _thread_except_hookru      s    $-,, DN
&t~t/A 	
 	
     r3   c               #      K   g } t          t          dd          }|$t          j        t          |           t          _        	 | V  ||t          _        dS dS # ||t          _        w xY w)zProvide a list of uncaught exceptions from threads via a fixture.

    Only catches exceptions on Python 3.8+.
    The list contains: ``(type, str(value), str(traceback))``
    
excepthookN)getattrr>   rL   rM   ru   rw   )rs   	orig_hooks     r2   thread_exceptionsrz      s       J	<66I(0 
  
	- #,I    ! 9 #,I ,,,,s   A A(adapter_type)builtin	pyopensslc                    t          t                    \  }}}	t          |          }
 |
||          }|dk    r|                                |_        |                    |j                    |||	f|          }t          |j                  \  }}}	t          j        d	                    ||	          | |          }|j
        dk    sJ |j        dk    sJ dS )	z;Test ability to connect to server via HTTPS using adapters.namer}   https://{host!s}:{port!s}/hostport)timeoutverify   Hello world!N)r   r   r   get_contextcontextconfigure_certr:   requestsgetformatstatus_codetext)http_request_timeoutrN   r{   r_   rb   rf   rX   r\   r]   r   tls_adapter_clstls_adaptertlshttpserverresps                 r2   test_ssl_adaptersr      s     ,,>??Iud+>>>O!/&(L K {"")5577"";#6777#OY$5{CCM
 , Iud <$+++FF$*  D s""""9&&&&&&r3   )is_trusted_certtls_client_identity))T	localhost)T	127.0.0.1)Tz*.localhost)Tnot_localhost)Fr   tls_verify_modez)Fails under PyPy in CI for unknown reasonF)r   strictc                    |t           j        k    o|	 }t          t                    \  }}}|	r|nt	          j                    }|j                            dt          |
                    5  |	                    t          |
                    }~ddd           n# 1 swxY w Y   |j                                        5 }t          |          } |||          }|dk    rA|                                |_        |j                            t"          |         d            n||j        _        |                    |j                   |                    |j                    |||f|          }t          |j                  \  }}}t-          j        t0          j        d                    ||          | ||	          }|s |            }|j        d
k    }|s9t8          r2|dk    r,|t           j        k    r|
dk    r|	rt=          j        d           |sJ |j         dk    sJ |!                                 	 ddd           dS tD          o|dk    o|t           j        k    }|rt=          j        d           t0          j#        j$        f}tJ          stL          r|t0          j#        j'        fz  }t=          j(        |          5 } |            !                                 ddd           n# 1 swxY w Y   	 |j)        j*        d         j+        j*        d         j*        d         n4# tX          $ r' tJ          stL          rt[          |j)                  n Y nw xY wt]          t^                    rt[          |j)                  t`          rdndf}tD          rtb          r|dk    rd}|t           j        t           j2        fv r&|	s$|
dk    r|tJ          rdntL          r	tf          rdndz  }th          r|dz  }tL          rtJ          rth          r|dz  }tk          fd|D                       sJ 	 ddd           dS # 1 swxY w Y   dS )z8Verify that client TLS certificate auth works correctly.idna.core.ulabelreturn_valueNr   r}   c                     |S NrR   conncerterrnodepthpreverify_oks        r2   <lambda>z&test_tls_client_auth.<locals>.<lambda>-      | r3   r   r   r   r   r   r   r|   r   z4OpenSSL 1.0 has problems with verifying client certsr   zTest sometimes failsr   zsslv3 alert bad certificatetlsv1 alert unknown ca)r   )z3bad handshake: SysCallError(10054, 'WSAECONNRESET')z<('Connection aborted.', OSError("(10054, 'WSAECONNRESET')"))z=('Connection aborted.', OSError("(10054, 'WSAECONNRESET')",))z;('Connection aborted.', error("(10054, 'WSAECONNRESET')",))z('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))zf('Connection aborted.', error(10054, 'An existing connection was forcibly closed by the remote host')))z7('Connection aborted.', OSError("(104, 'ECONNRESET')"))z8('Connection aborted.', OSError("(104, 'ECONNRESET')",))z6('Connection aborted.', error("(104, 'ECONNRESET')",))zN('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))z?('Connection aborted.', error(104, 'Connection reset by peer')))z;('Connection aborted.', BrokenPipeError(32, 'Broken pipe')))zGSSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:)z\('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))c              3       K   | ]}|v V  	d S r   rR   ).0eerr_texts     r2   	<genexpr>z'test_tls_client_auth.<locals>.<genexpr>  s'      >>Q1=>>>>>>r3   )6ssl	CERT_NONEr   r   rP   rQ   mock_modulepatchr   r[   r   ra   rV   r   r   r   
set_verify_stdlib_to_openssl_verifyverify_modeconfigure_trustr   r:   rL   rM   r   r   r   r   IS_PYOPENSSL_SSL_VERSION_1_0CERT_REQUIREDpytestxfailr   closer   rs   SSLErrorr   IS_GITHUB_ACTIONS_WORKFLOWConnectionErrorraisesvaluert   r   AttributeErrorrm   
isinstanceintIS_LIBRESSL_BACKENDr	   CERT_OPTIONALr
   
PY310_PLUSany)r   mockerrN   r{   rS   r_   rb   rf   rX   r   r   r   test_cert_rejectionr\   r]   r   client_cert_root_caclient_certcl_pemr   r   r   make_https_requestr   is_req_successful	issue_237expected_ssl_errorsssl_errexpected_substringsr   s                                @r2   test_tls_client_authr      s.   V 	3=( 	   ,,>??Iud /A""WZ\\			!	!-.. 
" 
 
     *44$%%
 
                                
	3	<	<	>	> Q?&/\BBB%o*0
 
 ;&&"-"9"9";";K**)/:KK   
 />K+
;.///&&{':;;;'D(9;GG!/0G!H!H	5$&.L(//YT/JJ ) / 
 
 
 # 	%%''D $ 0C 7)
4
 %	11'3+<<<+{::' ; J   %$$$9....JJLLLkQ? Q? Q? Q? Q? Q? Q? Q?t  1	)13=0 	
  	1L/000&1:; 	H3 	H8#6#F#GG].// 	)7  &&(((	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)	})!,38;@CHH 	 	 	 7 w}-- 	 h$$ 	*7=))H .A *)))
  	> 	>LK$?$?"=%%$   (	
 (;66" #"$ $ $: +" " " "?"H  	 $  & 	* 	 	 $  >>>>*=>>>>>>>>>cQ? Q? Q? Q? Q? Q? Q? Q? Q? Q? Q? Q? Q? Q? Q? Q? Q? Q?su   -$BB!$B!E:P7A<P7K-!P7-K1	1P74K1	5P79-L'&P7'.MP7MCP77P;>P;r|   zGUnclosed TLS resource warnings happen on macOS under Python 3.10 (#508))marksr}   )r   use_client_certTc                     t          t                    \  }}}|j                            dt	          d                    5  |                    t          d                    }ddd           n# 1 swxY w Y   |j                                        5 }t          |          } ||	|
          }|dk    rA|
                                |_        |j                            t          |         d            n||j        _        |                    |j                   |                    |j                    |||f|          }t          |j                  \  }}}t%          j        d|z   d	z   t)          |          z   d
z   |||r|nd          }t+          j        |j                            d                    }|d         dk    sJ |d         dk    sJ dD ]}||v sJ 	|dk    r	 ddd           dS dD ]}||v sJ 	|t2          j        k    s|s|d         dk    sJ n`|d         dk    sJ t7          |d          5 }|d         |                                v sJ 	 ddd           n# 1 swxY w Y   dD ]}||v sJ 	ddd           n# 1 swxY w Y   t:          rdS |D ]r}t=          |j        t@                    st)          |j!                  }d|v r)tE          j#        d$                    d|f                     tE          j%        |           s| D ]!\  }}}tM          |tN          j(                   "| r<J d$                    | d         d         j)        | d         d         f                      dS ) z7Test the SSL environment generated by the SSL adapters.r   r   r   Nr   r}   c                     |S r   rR   r   s        r2   r   ztest_ssl_env.<locals>.<lambda>  r   r3   zhttps://:r   r   r    zwsgi.url_schemehttpsHTTPSon>   SSL_VERSION_LIBRARYSSL_VERSION_INTERFACE>   
SSL_CIPHERSSL_PROTOCOLSSL_CLIENT_VERIFYNONESUCCESSrtSSL_CLIENT_CERT>   SSL_CLIENT_I_DNSSL_CLIENT_S_DNSSL_CLIENT_M_SERIALSSL_CLIENT_M_VERSIONzsocket.socket
zASometimes this test fails due to a socket.socket ResourceWarning:)filez: r      )*r   r   r   r   r   r[   r   ra   rV   r   r   r   r   r   r   r   r   r:   r   r   rm   r)   loadscontentdecoder   r   openreadr	   ri   categoryResourceWarningmessager   r   ro   failr(   sysstderrr4   )rz   recwarnr   r   rN   r{   rS   r   r_   rb   rf   rX   r   r\   r]   r   r   r   r   r   tlswsgiserverr   r0   keyfwarnmsg_traces                                r2   test_ssl_envr    s   L ,,>??Iud			!	!+&& 
" 
 
 7 7 mmD$5$566	7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 
	3	<	<	>	> ;"&/\BBB%o*0
 
 ;&&"-"9"9";";K**)/:KK   
 />K+
;.///&&{':;;;'D(9;GG!/0G!H!H	5$|"S(3t994v=(.*4	
 
 
 j,,W5566 $%00007|t#### D 	 	C#::::: ;&&S;" ;" ;" ;" ;" ;" ;" ;"V 2 	 	C#::::: cm++?+*+v55555*+y8888fd## :q,-99999: : : : : : : : : : : : : : : " " czzzzzw;" ;" ;" ;" ;" ;" ;" ;" ;" ;" ;" ;" ;" ;" ;"~   	  $-99 	 $,c!!L		7     	C ) & &1ee#*%%%%%   $))!Q(!Q- # #     sP   #A11A58A5EJ;A
JI1%J1I5	5J8I5	9JJJip_addrc                    |                      |t          f          }t          |j                  \  }}}t	          j        t          j                  5 }t          j	        
                    d                    ||                                        dd           ddd           n# 1 swxY w Y   t          rdnd}||j        j        d         v sJ dS )	z:Ensure that connecting over HTTPS to HTTP port is handled.z{interface}:{port})r\   r   GETr   Nzwrong version numberzunknown protocol)sendr   r   r:   r   r   r   r   httpclientHTTPSConnectionr   rG   r   r   rt   )http_serverr  rH   r\   r]   r   r   expected_substrings           r2   test_https_over_http_errorr  E  s    !!7N";<<J+J,@AAIud	s|	$	$ ## ''# (  	
 	

 '%


               #5 	   !3B!7777777s   A	B((B,/B,r   )rerunsreruns_delayc                    t           o|dk    }|rt          j        d           t          |          }	 |	||          }
|dk    r|
                                |
_        |                    |
j                   t          |          \  }}} |||f|
          }t          |j                  \  }}}|}|t          u r dj
        di t                      }|dk    }|rGt          j        d
                    ||          |           }|j        d	k    sJ |j        d
k    sJ dS t          j        t          j        j                  5 }t          j        d
                    ||          |            ddd           n# 1 swxY w Y   t&          rd\  }}t           rd\  }}t(          rd\  }}|j        j        d         j        d         }t/          |          }|j        |k    s!J  dj
        di t                                  ||v sJ dS )z:Ensure that connecting over HTTP to HTTPS port is handled.r|   zTest fails in Travis-CIr   r}   z[{fqdn}]zhttp://{host!s}:{port!s}/r   )r   i  zUThe client sent a plain HTTP request, but this server only speaks HTTPS on this port.N)h   Connection reset by peer)6   r  )iF'  z=An existing connection was forcibly closed by the remote hostr   r  z,The underlying error is {underlying_error!r}rR   )r   r   r   r   r   r   r   r   r:   r   r   localsr   r   r   r   r   rs   r   r
   r   r   rt   rm   r   )r   rN   r{   rS   r  r_   rb   rf   	issue_225r   r   r\   r]   r   r   fqdn(expect_fallback_response_over_plain_httpr   r   expected_error_codeexpected_error_textunderlying_errorr   s                          r2   test_http_over_https_errorr  ^  s   6 	 	&I%   0.///+>>>O!/&(L K {"")5577"";#6777+G44Iud#OY$5{CCM+ Iud D$$$ z ,,688,, K' -
 0 
|'..Dt.DD(
 
 
 3&&&&y>
 
 
 
 		x*:	;	; 
w'..Dt.DD(	
 	
 	
 	

 
 
 
 
 
 
 
 
 
 
 
 
 
 
  
4
00  
4
00  
4
00
 })!,1"5#$$H!%8888	6	 		 	 988 (******s   ,F  FF)Rr7   rL   r)   osr   
subprocessr   r>   rC   rp   http.clientr	  OpenSSL.SSLOpenSSLr   r   rP   _compatr   r   r   r   r   r	   r
   r   r   serverr   r   testingr   r   r   r   r   wsgir   boolgetenvr   check_output
IS_WIN2016OPENSSL_VERSION
startswithr   SSLSSLeay_versionSSLEAY_VERSIONr   version_infor   r   VERIFY_NONEr   VERIFY_PEERr   VERIFY_FAIL_IF_NO_PEER_CERTr   markskipifmissing_ipv6r   rI   fixturerN   rS   rX   r_   rb   rf   ru   rz   parametrizer   r   r   paramr  r  flakyr  rR   r3   r2   <module>r:     sf          				 



     



                     & & & & & & & & & & 8 8 8 8 8 8 8 8 8 8 4 4 4 4 4 4 4 4 4 4 6 6 6 6 6 6 6 6                    "T)"),=">">??  37Nz7N8 8 	  )44Z@@ Kw{9::J  bqb!W,
 M7;*w{.'+"II	  {!!1 "  8 8 8 8 8
 8 8 82  & D D D
   
    * * *          - - -(  #' #' #'L   .    6   
o? o?    8o?d +##'Z+	 $  	
 	
 	
 	  *				E"		D!		D!	 	r r	 	 2rj  8 8 8$   '|<<<  !!,,Q+ Q+ -,  Q+ Q+ Q+r3   