U af@sddlmZmZmZmZddlZddlZddlZddl Z ddl Z ddl m Z ddlmZddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZddlm Z m!Z!m"Z"dd l#m$Z$m%Z%m"Z&dd l'm(Z(dd l)m*Z*m+Z+m,Z,m-Z-dd l.m/Z/m0Z0m1Z1m2Z2dd l3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFddlGmHZHm Z ddlImJZJejKdkreLZMejNZOnePZOejKdkrejQZRnejRZRddgZSeTdZUeVZWeWdeWdfZXGddde0ZYGddde/ZZGddde[Z\Gddde[Z]dS))unicode_literalsdivisionabsolute_importprint_functionN) Certificate)pretty_message)buffer_from_bytesbuffer_from_unicodebytes_from_buffercastderefis_nullnativenewnullrefsizeofstructunwrapwrite_to_buffer)secur32 Secur32Const handle_error)crypt32 Crypt32Constr)kernel32) type_namestr_clsbyte_cls int_types)TLSErrorTLSVerificationErrorTLSDisconnectErrorTLSGracefulDisconnectError)detect_client_auth_requestdetect_other_protocol extract_chainget_dh_params_length parse_alertparse_session_inforaise_client_authraise_dh_paramsraise_disconnectionraise_expired_not_yet_validraise_handshakeraise_hostnameraise_no_issuerraise_protocol_errorraise_protocol_version raise_revokedraise_self_signedraise_verificationraise_weak_signature)load_certificater)parse_certificate))r; TLSSession TLSSockets( | | )c@s eZdZdS)_TLSDowngradeErrorN)__name__ __module__ __qualname__rCrCB/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/tls.pyr?Qsr?c@seZdZdZdS)_TLSRetryErrorz TLSv1.2 on Windows 7 and 8 seems to have isuses with some DHE_RSA ServerKeyExchange messages due to variable length integer encoding. This exception is used to trigger a reconnection to attempt the handshake again. N)r@rArB__doc__rCrCrCrDrEVsrEc@s>eZdZdZdZdZdZdZdZd ddZ ddZ dd Z dS) r=zj A TLS session object that multiple TLSSocket objects can share for the sake of session reuse NFc Cs<t|tsttdt|||_|dkr8tdddg}t|trNt|g}nt|tsjttdt||tddddg}|rttdt |||_ g|_ |r0|D]}t|t r|j }nbt|trt|}nNt|trt|d }t|}W5QRXnt|ts"ttd t||j |q|dS) a] :param protocol: A unicode string or set of unicode strings representing allowable protocols to negotiate with the server: - "TLSv1.2" - "TLSv1.1" - "TLSv1" - "SSLv3" Default is: {"TLSv1", "TLSv1.1", "TLSv1.2"} :param manual_validation: If certificate and certificate path validation should be skipped and left to the developer to implement :param extra_trust_roots: A list containing one or more certificates to be treated as trust roots, in one of the following formats: - A byte string of the DER encoded certificate - A unicode string of the certificate filename - An asn1crypto.x509.Certificate object - An oscrypto.asymmetric.Certificate object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library zM manual_validation must be a boolean, not %s NTLSv1TLSv1.1TLSv1.2zu protocol must be a unicode string or set of unicode strings, not %s SSLv3z protocol must contain only the unicode strings "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2", not %s rbz extra_trust_roots must be a list of byte strings, unicode strings, asn1crypto.x509.Certificate objects or oscrypto.asymmetric.Certificate objects, not %s ) isinstancebool TypeErrorrr_manual_validationsetr ValueErrorrepr _protocols_extra_trust_rootsrZasn1r r:openreadAsn1Certificateappend_obtain_credentials)selfprotocolZmanual_validationZextra_trust_rootsZunsupported_protocolsZextra_trust_rootfrCrCrD__init__msN          zTLSSession.__init__c Cstjtjtjtjd}d}|D]\}}||jkr"||O}q"tjtjtj tj tj tj tj tjtjtjg }d|jkr|tjtjtjgttdt|}t|D]\}}|||<qtjtjB} |js|js| tjO} n | tjO} ttd} t | } tj!| _"d| _#t$| _%t$| _&d| _'t$| _(t|| _)|| _*|| _+d| _,d| _-d| _.| | _/d| _0ttd} t1t$tj2tj3t$| t$t$| t$ } t4| | |_5dS)zU Obtains a credentials handle from secur32.dll for use with SChannel )rJrGrHrIrrIz ALG_ID[%s]Z SCHANNEL_CREDz CredHandle *N)6rSP_PROT_SSL3_CLIENTSP_PROT_TLS1_CLIENTSP_PROT_TLS1_1_CLIENTSP_PROT_TLS1_2_CLIENTitemsrSZ CALG_AES_128Z CALG_AES_256Z CALG_3DESZ CALG_SHA1Z CALG_ECDHEZ CALG_DH_EPHEMZ CALG_RSA_KEYXZ CALG_RSA_SIGNZ CALG_ECDSAZ CALG_DSS_SIGNextendZ CALG_SHA512Z CALG_SHA384Z CALG_SHA256rrlen enumerateZSCH_USE_STRONG_CRYPTOZSCH_CRED_NO_DEFAULT_CREDSrOrTZSCH_CRED_AUTO_CRED_VALIDATIONZSCH_CRED_MANUAL_CRED_VALIDATIONrrZSCHANNEL_CRED_VERSIONZ dwVersionZcCredsrZpaCredZ hRootStoreZcMappersZ aphMappersZcSupportedAlgsZpalgSupportedAlgsZgrbitEnabledProtocolsZdwMinimumCipherStrengthZdwMaximumCipherStrengthZdwSessionLifespandwFlagsZ dwCredFormatZAcquireCredentialsHandleWZ UNISP_NAMEZSECPKG_CRED_OUTBOUNDr_credentials_handle)rZZprotocol_valuesZprotocol_bit_maskkeyvalueZalgsZ alg_arrayindexalgflagsZschannel_cred_pointerZ schannel_credZcred_handle_pointerresultrCrCrDrYs~            zTLSSession._obtain_credentialscCs$|jr t|j}t|d|_dSN)rgrZFreeCredentialsHandler)rZrmrCrCrD__del__s zTLSSession.__del__)NFN) r@rArBrFrSZ_ciphersrOrTrgr]rYrorCrCrCrDr=as ZQc@seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZdZdZdZdZdZdZed=ddZd>ddZd d Zd d Z d?d dZ!ddZ"d@ddZ#ddZ$ddZ%ddZ&ddZ'dAddZ(ddZ)dd Z*d!d"Z+d#d$Z,e-d%d&Z.e-d'd(Z/e-d)d*Z0e-d+d,Z1e-d-d.Z2e-d/d0Z3e-d1d2Z4e-d3d4Z5e-d5d6Z6e-d7d8Z7e-d9d:Z8d;d<Z9dS)Br>z8 A wrapper around a socket.socket that adds TLS NFc Cst|tjsttdt|t|ts:ttdt||dk r^t|ts^ttdt||dd|d}||_||_ z | Wnbt k r}zt |j |j}|W5d}~XYn0tk r}zt|j }|W5d}~XYnX|S)az Takes an existing socket and adds TLS :param socket: A socket.socket object to wrap with TLS :param hostname: A unicode string of the hostname or IP the socket is connected to :param session: An existing TLSSession object to allow for session reuse, specific protocol or manual certificate validation :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library zU socket must be an instance of socket.socket, not %s zK hostname must be a unicode string, not %s N` session must be an instance of oscrypto.tls.TLSSession, not %s )session)rLsocket_socketrNrrrr=_socket _hostname _handshaker?r#message certificaterEr")clsrshostnamerqZ new_socketeZnew_erCrCrDwrapEs6    zTLSSocket.wrap cCsd|_d|_|dkr$|dkr$d|_n|t|ts@ttdt|t|ts\ttdt||dk rt|t j sttdt|t ||f||_|j ||dkrt}nt|tsttdt|||_|jr||_z |Wntk r`|t|jtdg|j|j}|d|_||_t ||f||_|j ||YnBtk rd|_t ||f||_|j ||YnXdS)a :param address: A unicode string of the domain name or IP address to connect to :param port: An integer of the port number to connect to :param timeout: An integer timeout to use for the socket :param session: An oscrypto.tls.TLSSession object to allow for session reuse and controlling the protocols and validation performed NzR address must be a unicode string, not %s zI port must be an integer, not %s zJ timeout must be a number, not %s rprI)_received_bytes_decrypted_bytesrtrLrrNrrr!numbersNumberrrcreate_connection settimeoutr=_sessionrurvr?closerSrPrOrTrorE)rZaddressporttimeoutrqZ new_sessionrCrCrDr]sf        zTLSSocket.__init__cCsnttd|}td|D]&}d||_tj||_t||_qt td}t |}tj |_ ||_ ||_||fS)z Creates a SecBufferDesc struct and contained SecBuffer structs :param number: The number of contains SecBuffer objects to create :return: A tuple of (SecBufferDesc pointer, SecBuffer array) z SecBuffer[%d]r SecBufferDesc)rrrangecbBufferrSECBUFFER_EMPTY BufferTyperpvBufferrrSECBUFFER_VERSION ulVersioncBufferspBuffers)rZnumberbuffersrjsec_buffer_desc_pointersec_buffer_descrCrCrD_create_bufferss    zTLSSocket._create_buffersc( Csd}d}zttjtjtdt}t|r6t dt }|j j D]B}| }t|tj|t|tjt}|szt d||jqDttd}t|jtj|}t|t|}ttd|}ttd} t| ttd| } ttd} ttdtj| d<ttdtj| d<ttdtj | d <t!td } t| } d | _"ttd | | _#t!td }t|}tj$|_%| |_&t!td}t|}||_'t(t|}||_)ttd}t*t|| ||tj+tj,Bt|}t |tj-}t|}t|}t.t/|j0}|dkrbt|j1}t|}t.t/|j2}|j3|d}t|}t|j4}t5|j6t.t/|j7}t89|}|j|krb|tj:O}t!td}t|} t(t| | _)tj;| _|j?| _@t!td}!t|!}"t(t|"|"_)||"_Attd||"_Bt!td}#t|#}$t(t|$|$_)tCtjD||!|#}t |t|}%t5|%j6t.t/|%j7}t89|}|$jE}&|&r|&tjFkrRtG||&tjHkrtI|}'|'jJrxtK|ntL||&tjMkrtN||j?|&tjOkrtP||&tjQkrtR|tS||jTt ddgkrtP|W5|rt|d|r t|XdS)z Manually invoked windows certificate chain builder and verification step when there are extra trust roots to include in the search process NrzPCERT_CONTEXT *Z PCERT_CONTEXTz FILETIME *z char *[3]zchar *rrZCERT_ENHKEY_USAGEr;zchar **ZCERT_USAGE_MATCHZCERT_CHAIN_PARAzPCERT_CHAIN_CONTEXT *Z SSL_EXTRA_CERT_CHAIN_POLICY_PARAz wchar_t *ZCERT_CHAIN_POLICY_PARAzvoid *ZCERT_CHAIN_POLICY_STATUSmd5Zmd2)UrCertCloseStoreZCertFreeCertificateChainZ CertOpenStorerZCERT_STORE_PROV_MEMORYZX509_ASN_ENCODINGrrhandle_crypt32_errorrPrrTdumpZ CertAddEncodedCertificateToStorerdZCERT_STORE_ADD_USE_EXISTINGaddsha256rrQueryContextAttributesW_context_handle_pointerrSECPKG_ATTR_REMOTE_CERT_CONTEXTrrr rZGetSystemTimeAsFileTimeZPKIX_KP_SERVER_AUTHZSERVER_GATED_CRYPTOZ SGC_NETSCAPErZcUsageIdentifierZrgpszUsageIdentifierZUSAGE_MATCH_TYPE_ORZdwTypeUsageZRequestedUsagerZcbSizeZCertGetCertificateChainZCERT_CHAIN_CACHE_END_CERTZ&CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLYZ.CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGSrintZcChainZrgpChainZcElementZ rgpElementZ pCertContextr pbCertEncoded cbCertEncodedrWloadZ'CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAGZAUTHTYPE_SERVERZ dwAuthTypeZ fdwChecksr ruZpwszServerNamerfZpvExtraPolicyParaZ CertVerifyCertificateChainPolicyZCERT_CHAIN_POLICY_SSLZdwErrorZCERT_E_EXPIREDr/ZCERT_E_UNTRUSTEDROOTr9 self_signedr6r2ZCERT_E_CN_NO_MATCHr1TRUST_E_CERT_SIGNATUREr8ZCRYPT_E_REVOKEDr5r7Z hash_algo)(rZstoreZcert_chain_context_pointerZ cert_hashescert cert_datarmcert_context_pointer_pointercert_context_pointerZorig_now_pointerZ now_pointerZusage_identifiersZcert_enhkey_usage_pointerZcert_enhkey_usageZcert_usage_match_pointerZcert_usage_matchZcert_chain_para_pointerZcert_chain_paraZcert_chain_para_sizeZ"cert_chain_context_pointer_pointerZcert_chain_policy_para_flagsZcert_chain_contextZ num_chainsZfirst_simple_chain_pointerZfirst_simple_chainZ num_elementsZlast_element_pointerZ last_elementZlast_element_certZlast_element_cert_dataZ last_certZ(ssl_extra_cert_chain_policy_para_pointerZ ssl_extra_cert_chain_policy_paraZcert_chain_policy_para_pointerZcert_chain_policy_paraZ cert_chain_policy_status_pointerZcert_chain_policy_status cert_contexterror oscrypto_certrCrCrD_extra_trust_root_validations                                       z&TLSSocket._extra_trust_root_validationc!Csd}d}d}zzd|r |j}nttd}|}tjdtj dtj dtj dtj d tj d tjd i}d|_|D]}|j|O_qf|d \}}tj|d_|d \} }tj|d_tj|d_ttd } |r|} t} n t} |} t|jj| |j|jddtd| | | t } | ttjtjgkr*t| t|s6| }n| }d}d}|djdkrt|dj|dj}||7}|j !|d|d_t|djt|d_t"d}t#td||d_d}| tjkrz$d}|j $d}|dkrt%Wnt&k r d}YnX||7}|j'|7_'t(|j'|d_t)||j't|jj||j|jdd|dt| | t } | tj*krtj|d_|djtj+krtj+|d_d|d_t|djst|djt|d_|rt%q| tj,kr&t-|rt.t/|}|r |dkr t0t1| tj2krJt3|}t4|d|j| tj5krjt3|}t6|d| tj7krt3|}|d}t8|}|j9st:|t;|| tj| tj?krt.| t@jAkrtB|| tjCkr|djdkr|t|dj|dj}||7}|dd}|dksF|dkr|d|jjDkr|t(|jjDdkr|t3|}tEd|dt-|rt.tF|rtG|t1| tjHks| tjIkrd|jjDkrtJd|rt%| tjKkrt=|dkrt>| ttjtjgkrt| t|djdkr~t|dj|dj}||7}|j !|d|d_t|djt|d_|djtjLkr|dj}|j'| d|_'tj+|d_d|d_t|djt|d_| tjkr|| d}nd|_'qtMtd}tN|tjO|} t| ttP|}tjQdtjRdtjSd tjTd!tjUdiVtWtX|jYtZ|jY|_[|j[tdd d!dgkrt\||}|d"|_]|d#|_^|d$|__|d%|_`ta| }|D]&}||Bdkrtbtcd&||q|sb||_d}tMtd'}tN|jtjd|} t| tP|} tWtX| je|_ftWtX| jg|_htWtX| ji|_j|jf|jh|jj|_k|jjlrt|mWn&tbtnjofk r|pYnXW5|rt|djst|djt|djst|dj|rt|XdS)(z Perform an initial TLS handshake, or a renegotiation :param renegotiate: If the handshake is for a renegotiation Nrrz CtxtHandle *zreplay detectionzsequence detectionZconfidentialityzmemory allocationZ integrityzstream orientationzdisable automatic client authrULONG *r~iBYTE *F T)rFir<(+rIzMServer certificate verification failed - weak certificate signature algorithmzTLS handshake failedZSecPkgContext_ConnectionInfoZSSLv2rJrGrH cipher_suite compression session_idsession_ticketzl Unable to obtain a credential context with the property %s ZSecPkgContext_StreamSizes)qrrrFreeContextBufferDeleteSecurityContextrrrZISC_REQ_REPLAY_DETECTZISC_REQ_SEQUENCE_DETECTZISC_REQ_CONFIDENTIALITYZISC_REQ_ALLOCATE_MEMORYZISC_REQ_INTEGRITYZISC_REQ_STREAMZISC_REQ_USE_SUPPLIED_CREDS_context_flagsrSECBUFFER_TOKENrSECBUFFER_ALERTrInitializeSecurityContextWrrgrurPSEC_E_OKSEC_I_CONTINUE_NEEDEDrr"rr rtsendr r recvr.socket_error_clsrrdrSEC_E_INCOMPLETE_MESSAGErZSEC_E_ILLEGAL_MESSAGEr&r,r*r4r0ZSEC_E_WRONG_PRINCIPALr(r1ZSEC_E_CERT_EXPIREDr/ZSEC_E_UNTRUSTED_ROOTr9rr2r6ZSEC_E_INTERNAL_ERRORr)r-ZSEC_I_INCOMPLETE_CREDENTIALSrrr8ZSEC_E_INVALID_TOKENrSr?r'r3ZSEC_E_BUFFER_TOO_SMALLZSEC_E_MESSAGE_ALTEREDrEZSEC_E_INVALID_PARAMETERSECBUFFER_EXTRArrZSECPKG_ATTR_CONNECTION_INFOrZSP_PROT_SSL2_CLIENTr^r_r`ragetrrZ dwProtocolr _protocolr+ _cipher_suite _compression _session_id_session_ticketr OSErrorrZSECPKG_ATTR_STREAM_SIZESZcbHeader _header_sizeZcbMaximumMessage _message_sizeZ cbTrailer _trailer_size _buffer_sizerTrrrrr)!rZ renegotiateZ in_buffers out_buffersZnew_context_handle_pointerZtemp_context_handle_pointerZrequested_flagsflagZin_sec_buffer_desc_pointerout_sec_buffer_desc_pointeroutput_context_flags_pointerZ first_handleZ second_handlermZhandshake_server_bytesZhandshake_client_bytestokenZin_data_buffer bytes_readZ fail_lateZ alert_infochainrrZ alert_bytesZ alert_number extra_amountZconnection_info_pointerZconnection_infoZ session_infoZoutput_context_flagsZstream_sizes_pointerZ stream_sizesrCrCrDrvs                                                           zTLSSocket._handshakec sXt|tsttdt|jdkrZjdkrRjd|}j|d_|Sjst j _ d\_ _ tjj d_ttdjj d_t|j }tj dj dj dj d fd d }j}t|}d_|dkr&ds&d_|Stjdk}||kr,|rpjj|7_tjdkrptttjj }|dkrq,|j d_tjjd|tjj dt}d }|tj kr|d }q4nX|tj!krd _"#q,n8|tj$kr*j%d d&|S|tj'kr@t(|t)t*tj+tj,tj-g} d} fD]f} | j} | tjkr|t.| j| j7}t|}n2| tj/krt0t1| j} n| | krdt2td| qd| rj|| d_nj|d_|drd }|s4tjdkr4q,q4t||krT||d_|d|}|S)a0 Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the data read zG max_length must be an integer, not %s Nr~rrrrr;cs^tj_ttdj_d_tj__d_tj__d_tj__d_dS)Nrr) rSECBUFFER_DATArr r_decrypt_data_bufferrrrrCZbuf0Zbuf1buf2Zbuf3Z null_valuerZrCrD_reset_bufferssz&TLSSocket.read.._reset_buffersFT)rz] Unexpected decrypt output buffer of type %s )3rLr!rNrrrr _raise_closedrr rr _decrypt_desc_decrypt_buffersrrrr rrmaxrrd select_readrrtrr.minrrZDecryptMessagerZSEC_I_CONTEXT_EXPIRED_remote_closedshutdownZSEC_I_RENEGOTIATErvrVrrr"rPrSECBUFFER_STREAM_HEADERSECBUFFER_STREAM_TRAILERr rrrr) rZ max_lengthoutputZto_recvrZ output_lenZdo_readdata_lenrmZvalid_buffer_typesrbufZ buffer_typerCrrDrVs                          zTLSSocket.readcCs8t|jdkrdSt|jggg|\}}}t|dkS)aZ Blocks until the socket is ready to be read from, or the timeout is hit :param timeout: A float - the period of time to wait for data to be read. None for no time limit. :return: A boolean - if data is ready to be read. Will only be False if timeout is not None. rT)rdrselectrt)rZrZ read_ready_rCrCrDrszTLSSocket.select_readc Cst|ts&t|ts&ttdt|d}t|t}t|jdkrP|j}d|_n |d}t|}||7}|r| |}|dk r| }qq4t d|t|d}| ||}|dkr4|t|}qq4||d|j|_|d|S)a Reads data from the socket until a marker is found. Data read may include data beyond the marker. :param marker: A byte string or regex object from re.compile(). Used to determine when to stop reading. Regex objects are more inefficient since they must scan the entire byte string of read data each time data is read off the socket. :return: A byte string of the data read z_ marker must be a byte string or compiled regex object, not %s r~rrNr) rLr PatternrNrrrdrrVsearchendrfind) rZmarkerris_regexchunkoffsetmatchrstartrCrCrD read_untils2     zTLSSocket.read_untilcCs |tS)z Reads a line from the socket, including the line ending of "\r\n", "\r", or "\n" :return: A byte string of the next line from the socket )r _line_regexrZrCrCrD read_lines zTLSSocket.read_linecCs0d}|}|dkr,|||7}|t|}q|S)z Reads exactly the specified number of bytes from the socket :param num_bytes: An integer - the exact number of bytes to read :return: A byte string of the data that was read r~r)rVrd)rZ num_bytesr remainingrCrCrD read_exactlys zTLSSocket.read_exactlyc Cs|jdkr||jst|j|j|j|_|d\|_|_ t j |j d_ |j|j d_ ttd|j|j d_t j|j d_ t|j|j|j d_t j|j d_ |j|j d_ t|j|j|j|j d_t|dkrtt||j}t|j|d||j||j d_ t|j|j||j d_t|jd|jd}|t jkrVt|ttt|j dj }|tt|j dj 7}|tt|j dj 7}z|jt|j|Wn:t j!k r}z|j"dkrt#W5d}~XYnX||d}qdS)a Writes data to the TLS-wrapped socket :param data: A byte string to write to the socket :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library NrrrrriE')$rr_encrypt_data_bufferr rrrr _encrypt_desc_encrypt_buffersrrrrr rrrrrrdrrZEncryptMessagerrr"rrrtrr rrrerrnor.)rZdataZto_writermto_sendr{rCrCrDwritesH     zTLSSocket.writecCs&tg|jgg|\}}}t|dkS)aw Blocks until the socket is ready to be written to, or the timeout is hit :param timeout: A float - the period of time to wait for the socket to be ready to written to. None for no time limit. :return: A boolean - if the socket is ready for writing. Will only be False if timeout is not None. r)rrtrd)rZrrZ write_readyrCrCrD select_write's zTLSSocket.select_writec Cs|jdkrdSd}zHt dkrt td}d|d_ tj|d_ttdtd|d_ttd }t|}tj|_d|_||_t|j|}t|t|d \}}tj|d_tj|d_t td }t|jj |j|j!|j"ddt#dt#||t# }t$tj%tj&tj'g}||krt|tt(|dj|dj } z|j)| Wntj k rXYnXW5|rt|djst|djt|djst|djt|jd|_z|jtj Wntj k rYnXXdS) z Shuts down the TLS session and then shuts down the underlying socket :raises: OSError - when an error is returned by the OS crypto library Nrr)rrz SecBuffer[1]rrsrrr)*rrrrrrrtrrr SHUT_RDWRr_win_version_inforrrrrr r rrrrrrZApplyControlTokenrr"rrrrrgrurrrPrZSEC_E_CONTEXT_EXPIREDrr r) rZrrrrrmrrZacceptable_resultsrrCrCrDr7sr             zTLSSocket.shutdowncCsFz |W5|jr@z|jWntjk r8YnXd|_XdS)zN Shuts down the TLS session and socket and forcibly closes it N)rtrrrrrrrCrCrDrs zTLSSocket.closec Csttd}t|jtj|}t|tt |}t td|}t |}t |j t t|j}t||_g|_d}zd|j}t|t}t|st |}t |j t t|j} | |kr|jt| t||}qW5|rt|dXdS)zh Reads end-entity and intermediate certificate information from the TLS session zCERT_CONTEXT **zCERT_CONTEXT *Nr)rrrrrrrrr"rr r rrrrrWr _certificate_intermediatesrZ hCertStoreZCertEnumCertificatesInStorerrrX) rZrrmrrrZ store_handleZcontext_pointercontextr rCrCrD_read_certificatess2    zTLSSocket._read_certificatescCs|jrtdntddS)zi Raises an exception describing if the local or remote end closed the connection z$The remote end closed the connectionz!The connection was already closedN)rr%r$rrCrCrDrs zTLSSocket._raise_closedcCs*|jdkr||jdkr$||jS)zu An asn1crypto.x509.Certificate object of the end-entity certificate presented by the server N)rrrrrrCrCrDrxs   zTLSSocket.certificatecCs*|jdkr||jdkr$||jS)zz A list of asn1crypto.x509.Certificate objects that were presented as intermediates by the server N)rrrrrrrCrCrD intermediatess   zTLSSocket.intermediatescCs|jS)zg A unicode string of the IANA cipher suite name of the negotiated cipher suite )rrrCrCrDrszTLSSocket.cipher_suitecCs|jS)zM A unicode string of: "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3" )rrrCrCrDr[szTLSSocket.protocolcCs|jS)z5 A boolean if compression is enabled )rrrCrCrDrszTLSSocket.compressioncCs|jSzM A unicode string of "new" or "reused" or None for no ticket )rrrCrCrDrszTLSSocket.session_idcCs|jSr)rrrCrCrDr szTLSSocket.session_ticketcCs|jS)zM The oscrypto.tls.TLSSession object used for this connection )rrrCrCrDrqszTLSSocket.sessioncCs|jS)zN A unicode string of the TLS server domain name or IP address )rurrCrCrDrzszTLSSocket.hostnamecCs|jdS)zJ An integer of the port number the socket is connected to r)rs getpeernamerrCrCrDr%szTLSSocket.portcCs|jdkr||jS)z9 The underlying socket.socket connection N)rrrtrrCrCrDrs-s zTLSSocket.socketcCs |dSrn)rrrCrCrDro8szTLSSocket.__del__)N)r}N)F)N)N):r@rArBrFrtrrrrurrrrrrrrrrrrrrrrrrr classmethodr|r]rrrvrVrrrrr r rrrrpropertyrxrrr[rrrrqrzrrsrorCrCrCrDr>s > W3 0+ 7 > T(            )^ __future__rrrrsysrersrrrrZ_asn1rrW_errorsrZ_ffir r r r r rrrrrrrrrZ_secur32rrrZ_crypt32rrrZ _kernel32r_typesrrr r!errorsr"r#r$r%_tlsr&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8Z asymmetricr9keysr: version_infoxrangerrrZ WindowsErrorZ _pattern_typer__all__compilergetwindowsversionZ_gwvrr?rEobjectr=r>rCrCrCrDsD  @ T     ?