
    Bwg                        d dl mZmZmZm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 ddlmZmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZmZ ddl m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z=mZ ddl>m?Z? ddl@mAZA ej                  dk  reCZDej                  dk  rej                  ZFnej                  ZFddgZG e       j                  d      ZI ej                  d      ZKej                  ej                  ej                  ej                  ej                  dZQd ZR G d deS      ZT G d deS      ZUy)    )unicode_literalsdivisionabsolute_importprint_functionN   )libsslLibsslConst)	libcryptolibcrypto_version_infohandle_openssl_errorpeek_openssl_error   )_backend_config)Certificate)pretty_message)nullbytes_from_bufferbuffer_from_bytesis_nullbuffer_pointer)	type_namestr_clsbyte_cls	int_types)TLSErrorTLSDisconnectErrorTLSGracefulDisconnectError)detect_client_auth_requestextract_chainget_dh_params_lengthparse_session_inforaise_client_authraise_dh_paramsraise_disconnectionraise_expired_not_yet_validraise_handshakeraise_hostnameraise_no_issuerraise_protocol_errorraise_protocol_versionraise_self_signedraise_verificationraise_weak_signatureparse_tls_recordsparse_handshake_messages)load_certificater   )parse_certificate)get_path   )r4      
TLSSession	TLSSockettrust_list_paths   (
||
))SSLv2SSLv3TLSv1TLSv1.1TLSv1.2c                 .    t         dk  r| S | d   d| d   fS )a^  
    Takes a 3-element tuple from peek_openssl_error() and modifies it
    to handle the changes in OpenSSL 3.0. That release removed the
    concept of an error function, meaning the second item in the tuple
    will always be 0.

    :param error_tuple:
        A 3-element tuple of integers

    :return:
        A 3-element tuple of integers
    r3   r   r   )r   )error_tuples    L/var/www/horilla/myenv/lib/python3.12/site-packages/oscrypto/_openssl/tls.py_homogenize_openssl3_errorrA   D   s'     $NA{1~..    c                   6    e Zd ZdZdZdZdZdZdZdZ	ddZ
d Zy)r6   zj
    A TLS session object that multiple TLSSocket objects can share for the
    sake of session reuse
    Nc           	         t        |t              st        t        dt	        |                  || _        |t        g d      }t        |t              rt        |g      }n.t        |t              st        t        dt	        |                  t        g d      }||z
  }|rt        t        dt        |                  || _
        g | _        |r|D ]  }t        |t              r|j                  }nt        |t              rt        |      }nmt        |t              r/t!        |d      5 }t        |j#                               }ddd       n.t        |t$              st        t        dt	        |                  | j                  j'                  |        d}	 t(        d	k  rt+        j,                         }	nt+        j.                         }	t+        j0                  |	      }t3        |      rt5        d
       || _        t+        j8                  |d       t+        j:                  |t<        j>                  t<        j@                  tC                      tD        jF                  t        ddg      v rYtH        }
|

tK               }
tD        jF                  dk(  rd}nd}t+        jL                  ||
jO                  |      tC                     }nt+        jP                  |      }t5        |       |rt<        jR                  nt<        jT                  }t+        jV                  ||tC                      t+        jX                  |d      }t5        |       t        dg      }||| j                  z
  z  }|D ]7  }t+        j:                  |t<        jZ                  t\        |   tC                      9 | j                  r]t+        j^                  |      }| j                  D ]8  }ta        |      }t+        jb                  ||jd                        }t5        |       : yy# 1 sw Y   xY w# tf        $ r  |rt+        jh                  |       d| _         w xY w)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
                N)r;   r<   r=   zu
                protocol must be a unicode string or set of unicode strings,
                not %s
                )r:   r;   r<   r=   z
                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
                        r   r   r   iX  win32darwinmbcsutf-8s  ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHAr9   )5
isinstancebool	TypeErrorr   r   _manual_validationsetr   
ValueErrorrepr
_protocols_extra_trust_rootsr   asn1r   r1   openreadAsn1Certificateappendr   r   SSLv23_method
TLS_methodSSL_CTX_newr   r   _ssl_ctxSSL_CTX_set_timeoutSSL_CTX_ctrlr	   SSL_CTRL_SET_SESS_CACHE_MODESSL_SESS_CACHE_CLIENTr   sysplatform_trust_list_pathr2   SSL_CTX_load_verify_locationsencode SSL_CTX_set_default_verify_pathsSSL_VERIFY_NONESSL_VERIFY_PEERSSL_CTX_set_verifySSL_CTX_set_cipher_listSSL_CTRL_OPTIONS_PROTOCOL_MAPSSL_CTX_get_cert_storer0   X509_STORE_add_certx509	ExceptionSSL_CTX_free)selfprotocolmanual_validationextra_trust_rootsvalid_protocolsunsupported_protocolsextra_trust_rootfssl_ctxmethodr8   path_encodingresultverify_modedisabled_protocolsdisabled_protocol
x509_storecertoscrypto_certs                      r@   __init__zTLSSession.__init__d   s   > +T2N +,	   #4:;Hh(H:HHc*N (#   FG (? : ^ *+   #"$$5 A .<'7'<'<$ 0(;'89I'J$ 0':.5 G+<QVVX+F(G G#$4oF#N
 ""23%   ''../?@#A& V	%.--/**,((0Gw$Q'#DM&&w4 8811	 ||sGX#677"2"*&.jO<<7*$*M$+M==#**=9F  @@I (9J+55P[PkPkK%%g{DFC 33@F" !(!$gY?T__#DE%7 !##00!"34F	 &&#::7C
 33 1D$4T$:M#77"%**F )01 'mG G@  	##G, DM		s   ,PI0P P	)Qc                     | j                   r&t        j                  | j                          d | _         | j                  r't        j                  | j                         d | _        y y N)r\   r   rq   _ssl_sessionSSL_SESSION_freerr   s    r@   __del__zTLSSession.__del__  sL    ==. DM##D$5$56 $D rB   )NFN)__name__
__module____qualname____doc__rR   _ciphersrN   rS   r\   r   r   r    rB   r@   r6   r6   W   s5    
 JHHLpd%rB   c                      e 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dZdZdZdZdZdZdZdZdZdZed"d       Zd#dZd Zd Zd	 Zd
 Zd"dZd Z d Z!d Z"d Z#d"dZ$d Z%d Z&d Z'd Z(d Z)e*d        Z+e*d        Z,e*d        Z-e*d        Z.e*d        Z/e*d        Z0e*d        Z1e*d        Z2e*d        Z3e*d        Z4e*d         Z5d! Z6y)$r7   z8
    A wrapper around a socket.socket that adds TLS
    N    Fc                    t        |t        j                        st        t	        dt        |                  t        |t              st        t	        dt        |                  |.t        |t              st        t	        dt        |                   | dd|      }||_        ||_	        |j                          |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)rK   socket_socketrM   r   r   r   r6   _socket	_hostname
_handshake)clsr   hostnamer   
new_sockets        r@   wrapzTLSSocket.wrapS  s    * &'..1N &!	   (G,N (#	   z':'FN '"	   tW5
#
'
rB   c                    d| _         d| _        |
|d| _        nt        |t              st        t        dt        |                  t        |t              st        t        dt        |                  |8t        |t        j                        st        t        dt        |                  t        j                  ||f|      | _        | j                  j                  |       |t               }n.t        |t              st        t        dt        |                  || _        | j                  r|| _        | j#                          yy)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
        rB   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
                    r   )
_raw_bytes_decrypted_bytesr   rK   r   rM   r   r   r   numbersNumberr   create_connection
settimeoutr6   _sessionr   r   )rr   addressporttimeoutr   s        r@   r   zTLSSocket.__init__  sC      #?t|DL gw/ g&	!   dI. dO	!   ":gw~~+N g&	!   #44gt_gNDLLL##G,? lGGZ0N '"	    <<$DNOO rB   c                    d| _         d| _        d| _        	 t        j                  | j
                  j                        | _         t        | j                         rd| _         t        d       t        j                         }t        j                  |      | _        t        | j                        rt        d       t        j                  |      | _        t        | j                        rt        d       t        j                  | j                   | j                  | j                         | j                  j                  d      }t        j                  | j                   t        j                   t        j"                  |       t        j$                  | j                          | j
                  j&                  r4t        j(                  | j                   | j
                  j&                         t+        | j,                        | _        t+        | j,                        | _        d}d}	 t        j2                  | j                         }|| j5                         z  }|dk(  rnt        j6                  | j                   |      }|t        j8                  k(  rK| j;                         }|dk(  r/|dk(  r
t=                t?        |      r
tA                tC        |       ||z  }n	|t        jD                  k(  r|| j5                         z  }n|t        jF                  k(  r*d| _$        | jK                  d       | jM                          ntO               }t        jP                  t        jR                  t        jT                  f}	tW        |	      }	t        jP                  t        jX                  t        jT                  f}
tW        |
      }
t        jP                  t        jZ                  t        j\                  f}tW        |      }||	k(  s
||
k(  s||k(  r
t_                t`        dk  r0t        jP                  t        jb                  t        jd                  f}n:t        jP                  t        jf                  t        jh                  f}tW        |      }||k(  rtC        |       t        jP                  t        jb                  t        jj                  f}tW        |      }||k(  r
tm                t        jP                  t        jb                  t        jn                  f}t`        d	k  r||k(  r
tq                t        jP                  t        jr                  t        jn                  f}tW        |      }||k(  rNd}tu        |      D ](  \  }}}|d
k7  rtw        |      D ]  \  }}|dk(  sd} ( * |r
tA                tq                t`        dk  r0t        jP                  t        jx                  t        jz                  f}n:t        jP                  t        j|                  t        jz                  f}tW        |      }t        j~                  t        j                  t        j                  f}tW        |      }||k(  rKt        |      }|r>|d   }t        |      }|j                  j                  t        ddg      v rt        |       ||k(  r t        j                  | j                         }t        |      }d}d}d}d}d}|r|d   }t        |      }|j                  }t        t        j                  t        j                  t        j                  g      }||v r| }t        t        j                  t        j                  g      } || v }|rt        |       |rt        |       |rt        |       |r.|j                  j                  t        ddg      v rt        |       t        |       t        dt               t        ||      }!|!d   | _U        |!d   | _V        |!d   | _W        |!d   | _X        |!d   | _Y        | j                  j                  d      dk7  r*t        |      }"|"dk  r| j                          t_                | j                  dk(  s| j                  dk(  rm| j
                  j&                  r)t        j                  | j
                  j&                         t        j                  | j                         | j
                  _        | j
                  j                  s| j                  j                  t        ddg      v rt        | j                         | j                  j                  | j                        s!t        | j                  | j                         yyy# t        t        j                  f$ r | j                   r5t        j                  | j                          d| _         d| _        d| _        nd| j                  r&t        j                  | j                         d| _        | j                  r&t        j                  | j                         d| _        | j                           w xY w)z2
        Perform an initial TLS handshake
        Nr   rJ   rB   Tr   FrF   r3         md5md2rs   cipher_suitecompression
session_idsession_ticket_DHE_i   new)h_ssl_rbio_wbior   SSL_newr   r\   r   r   	BIO_s_memBIO_newSSL_set_bior   re   SSL_ctrlr	   SSL_CTRL_SET_TLSEXT_HOSTNAMETLSEXT_NAMETYPE_host_nameSSL_set_connect_stater   SSL_set_sessionr   _buffer_size_bio_write_buffer_read_bufferSSL_do_handshake
_raw_writeSSL_get_errorSSL_ERROR_WANT_READ	_raw_readr$   r   r"   r)   SSL_ERROR_WANT_WRITESSL_ERROR_ZERO_RETURN_gracefully_closed	_shutdown_raise_closedr   ERR_LIB_SSL#SSL_F_SSL3_CHECK_CERT_AND_ALGORITHMSSL_R_DH_KEY_TOO_SMALLrA   SSL_F_TLS_PROCESS_SKE_DHESSL_F_SSL3_GET_KEY_EXCHANGESSL_R_BAD_DH_P_LENGTHr#   r   SSL_F_SSL23_GET_SERVER_HELLOSSL_R_UNKNOWN_PROTOCOLSSL_F_SSL3_GET_RECORDSSL_R_WRONG_VERSION_NUMBER"SSL_R_TLSV1_ALERT_PROTOCOL_VERSIONr*   #SSL_R_SSLV3_ALERT_HANDSHAKE_FAILUREr&   SSL_F_SSL3_READ_BYTESr.   r/   !SSL_F_SSL3_GET_SERVER_CERTIFICATESSL_R_CERTIFICATE_VERIFY_FAILED$SSL_F_TLS_PROCESS_SERVER_CERTIFICATEERR_LIB_ASN1ASN1_F_ASN1_ITEM_VERIFY'ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHMr   r0   rT   	hash_algorO   r-   SSL_get_verify_resultself_signed&X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT$X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN,X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLYX509_V_ERR_CERT_HAS_EXPIREDX509_V_ERR_CERT_NOT_YET_VALIDr%   r(   r+   r,   r   r!   	_protocol_cipher_suite_compression_session_id_session_ticketfindr    closer   SSL_get1_sessionrN   certificateis_valid_domain_ipr'   OSErrorr   errorSSL_freeBIO_free)#rr   mem_bioutf8_domainhandshake_server_byteshandshake_client_bytesr}   r   chunkinfodh_key_info_1dh_key_info_2dh_key_info_3unknown_protocol_infotls_version_info_errorhandshake_error_infohandshake_failure_infosaw_client_authrecord_type_record_datamessage_typemessage_datacert_verify_failed_infounknown_hash_algo_infochainr   r   verify_resultr   time_invalid	no_issuerissuer_error_codestime_error_codessession_infodh_params_lengths#                                      r@   r   zTLSSocket._handshake  s   
 	

N	t}}'='=>DItyy! 	$Q'&&(G0DJtzz"$Q'0DJtzz"$Q'tyy$**djjA..//8KOO		8855	 ((3}}))&&tyy$--2L2LM%6t7H7H%ID" 1$2C2C DD%("%("00;&$//*;;&Q;,,TYY?K;;; NN,E|1S8/156LM-/,-CD*e3*k>>>*doo.??*k???.2D+NN5)&&( ./D $//#GG#::%M
 %?}$MM $//#==#::%M
 %?}$MM $//#??#99%M
 %?}$MM},0EQ^I^')-6'33'DD'>>1- (33'=='BB1-
 1KK`0a-44,-CD $//#@@#FF.*
 .HH^-_*55.0 $//#@@#GG,( .5$BV:V') $//#99#GG.*
 .HH^-_*55*/;LMc;d *7KK*g5 (>VWb>c * :l#/7#:6:O$)** +-/')-6'33'II'GG3/ (33'LL'GG3/
 3MMd2e/ $00#;;#KK.*
 .HH^-_*55 -.D E #(8D,<T,BM,11;;sE5>?RR 4] C66(.(D(DTYY(O -.D E&+',$)	#(, #(8D,<T,BM*7*C*CK14 + R R + P P + X X6 2.
  -0BB0;O	/2 + G G + I I4 0, ,9<L+LL'7=$+D1&-d3(]-?-?-I-ISRWY^Q_M`-`0?*40(H5g j .&&L **5DN!-n!=D ,] ;D+L9D#/0@#AD !!&&w/25#78N#O #d*JJL#% 5(D,@,@E,I==--++DMM,F,FG-3-D-DTYY-O*==33##--eU^1DD()9)9: ''::4>>J"4#3#3T^^D K 4 ' 	yy		* 	!
!
 ::OODJJ/!%DJ::OODJJ/!%DJJJL#	s   U<f O6f Cic                     | j                   }	 || j                  j                  d      z  }|}t        j                  | j                  |t        |            }||d | _         |S # t        j                  $ r Y Mw xY w)aD  
        Reads data from the socket and writes it to the memory bio
        used by libssl to decrypt the data. Returns the unencrypted
        data for the purpose of debugging handshakes.

        :return:
            A byte string of ciphertext from the socket. Used for
            debugging the handshake only.
        r   N)	r   r   recvr   r   r   	BIO_writer   len)rr   dataoutputwrittens       r@   r   zTLSSocket._raw_read  sx     	DLL%%d++D ""4::tSY?wx.  		s   A$ $A:9A:c                    t        j                  | j                        }|dk(  ryt        | j                  |      }t        j
                  | j                  | j                  |      }t        | j                  |      }|}t        |      rVd}	 | j                  j                  |      }|r
t!                |d	 }t        |      r| j#                          t        |      rV|S # t        j                  $ rQ}|j                  dk(  s|j                  dk(  rd}n&t        j                  dk(  r|j                  dk(  rd}n Y d	}~d	}~ww xY w)
z
        Takes ciphertext from the memory bio and writes it to the
        socket.

        :return:
            A byte string of ciphertext going to the socket. Used
            for debugging the handshake only.
        r   rB   Fh       TrH   )   N)r   BIO_ctrl_pendingr   minr   BIO_readr   r   r  r   sendr   r   errnora   rb   r$   select_write)	rr   data_availableto_readrV   to_writer  raise_disconnectsentes	            r@   r   zTLSSocket._raw_write  s     00<Qd''8tzz4+A+A7K$T%;%;TB(m$||((2  #%H8}!!#' (m( ! MM 	77c>QWW]'+$ \\X-!''R-'+$	s   C" "E5AEEc                 Z   t        |t              st        t        dt	        |                  t        | j                        }||k\  r%| j                  d| }| j                  |d | _        |S | j                  | j                          |dkD  r&| j                  d      s| j                  }d| _        |S t        | j                  ||z
        }| j                  }d}|rd}t        j                  | j                  | j                  |      }| j                          |dk  rt        j                   | j                  |      }|t"        j$                  k(  r!| j'                         dk7  rd}t)                nb|t"        j*                  k(  r| j                          d}|t"        j,                  k(  rd| _        | j1                  d       n-t3        dt4               |t7        | j                  |      z  }|r| j.                  rt        |      dk(  r| j                          ||d | _        |d| S )aO  
        Reads data from the TLS-wrapped socket

        :param max_length:
            The number of bytes to read - output may be less than this

        :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
                r   NrB   TF)rK   r   rM   r   r   r  r   r   r   select_readr!  r   r   SSL_readr   r   r   r	   r   r   r$   r   r   r   r   r   r   r   )rr   
max_lengthbuffered_lengthr  r'  againr}   r   s           r@   rV   zTLSSocket.read  s   $ *i0N *%	   d334 j(**1Z8F$($9$9*+$FD!M99  Qt'7'7':**F$'D!M d''o)EF&& E__TYY0A0A7KFOO{,,TYY?K;;;~~'3. $ ')k>>>OO% Ek???.2D+NN5) )H5'(9(96BBF5 8 ""s6{a'7  &z{ 3a
##rB   c                     t        | j                        dkD  ryt        j                  | j                  gg g |      \  }}}t        |      dkD  S )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.
        r   T)r  r   selectr   )rr   r   
read_readyr  s       r@   r-  zTLSSocket.select_readv  sJ     t$$%)!==$,,RI
Aq:""rB   c                    t        |t              s.t        |t              st        t	        dt        |                  d}t        |t              }	 t        | j                        dkD  r| j                  }d| _        nP| j                  | j                          t        j                  | j                        xs d}| j                  |      }t        |      }||z  }|r$|j                  |      }|R|j                         }nBt        d|t        |      z
  dz
        }	|j!                  ||	      }|dk7  r|t        |      z   }n||d | j                  z   | _        |d| S )a  
        Reads data from the socket until a marker is found. Data read includes
        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, including the marker
        z_
                marker must be a byte string or compiled regex object, not %s
                rB   r   Nr   r   r   )rK   r   PatternrM   r   r   r  r   r   r   r   SSL_pendingrV   searchendmaxr   )
rr   markerr  is_regexr   r'  offsetmatchr9  starts
             r@   
read_untilzTLSSocket.read_until  sZ    &(+Jvw4ON &!	   fg.4(()A---(+%99$&&( ,,TYY7?4		'*[FeOFf-$))+C
 AvF3a78FE2B;#f+-C5 8 !'stt/D/D Da}rB   c                 ,    | j                  t              S )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_regexr   s    r@   	read_linezTLSSocket.read_line  s     {++rB   c                 h    d}|}|dkD  r(|| j                  |      z  }|t        |      z
  }|dkD  r(|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
        rB   r   )rV   r  )rr   	num_bytesr  	remainings       r@   read_exactlyzTLSSocket.read_exactly  sF     	!mdii	**F!CK/I !m rB   c                 r   t        |      }|r)| j                  | j                          t        j                  | j                  ||      }| j                          |dk  rt        j                  | j                  |      }|t        j                  k(  r| j                         dk7  rt                np|t        j                  k(  r| j                          |t        j                  k(  r)d| _        | j                  d       | j                          nt        dt                ||d }t        |      }|r(yy)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
        Nr   rB   TF)r  r   r   r   	SSL_writer   r   r	   r   r   r$   r   r   r   r   r   r   )rr   r  data_lenr}   r   s        r@   writezTLSSocket.write  s     t9yy ""$%%diix@FOO{,,TYY?K;;;~~'3. ')k>>>OO%k???.2D+NN5)&&( )H5=D4yH5 rB   c                 l    t        j                   g | j                  gg |      \  }}}t        |      dkD  S )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   )r3  r   r  )rr   r   r  write_readys       r@   r%  zTLSSocket.select_write  s5     #MM"t||nb'J;;!##rB   c                    | j                   y	 t        j                  | j                         }	 | j                          |dk\  rn|dk  r|t        j
                  | j                   |      }|t        j                  k(  r| j                         dk7  rn5|t        j                  k(  r| j                          t        dt               |rd| _        t        j                  | j                          d| _         d| _        d| _        	 | j                   j#                  t$        j&                         y# t        $ r Y w xY w# t$        j(                  $ r Y yw xY w)z
        Shuts down the TLS session and then shuts down the underlying socket

        :param manual:
            A boolean if the connection was manually shutdown
        NTr   rB   )r   r   SSL_shutdownr   r   r   r	   r   r   r   r   r   _local_closedr   r   r   r   shutdownr   	SHUT_RDWRr   )rr   manualr}   r   s       r@   r   zTLSSocket._shutdown  s)    99((3F! {z,,TYY?K;;;~~'3. k>>>OO% )H51 4 !%D		"	

	LL!!'"3"34= ' >  		s#   D/ )D> /	D;:D;>EEc                 &    | j                  d       y)zV
        Shuts down the TLS session and then shuts down the underlying socket
        TN)r   r   s    r@   rQ  zTLSSocket.shutdownQ  s    
 	trB   c                 R   	 | j                          | j                  r#	 | j                  j                          d| _        yy# t        j                  $ r Y w xY w# | j                  r=	 | j                  j                          n# t        j                  $ r Y nw xY wd| _        w w xY w)zN
        Shuts down the TLS session and socket and forcibly closes it
        N)rQ  r   r   r   r   r   s    r@   r   zTLSSocket.closeX  s    
		$MMO ||LL&&(  $     ||LL&&( # s@   A A AAB&)BB&BB&BB&c                    t        j                  | j                        }t        |      rt	        dt
               t        dk  rt        j                  |      }nt        j                  |      }g | _	        t        d|      D ]  }t        dk  rt        j                  ||      }nt        j                  ||      }t        j                  |t                     }t!        |      }t#        |      }t        j                  ||      }t	        |       t%        ||      }	t'        j(                  |	      }
|dk(  r|
| _        | j                  j-                  |
        y)zh
        Reads end-entity and intermediate certificate information from the
        TLS session
        r   rF   N)r   SSL_get_peer_cert_chainr   r   r   r   r   sk_numOPENSSL_sk_num_intermediatesrangesk_valueOPENSSL_sk_valuer
   i2d_X509r   r   r   r   rW   load_certificaterX   )rr   stack_pointernumber_certsindexx509_buffer_sizecert_buffercert_pointercert_length	cert_datar   s              r@   _read_certificateszTLSSocket._read_certificatesh  s    66tyyA=! H-!F*!==7L!00?L 1l+ 	1E%.u=//uE#,,UDF;K+K8K)+6L#,,ULAK -)+{CI"''	2Dz$(!##**40#	1rB   c                 t    | j                   rt        d      | j                  rt        d      t        d      )zi
        Raises an exception describing if the local or remote end closed the
        connection
        z!The connection was already closedz$The remote end closed the connectionzThe connection was closed)rP  r   r   r   r   s    r@   r   zTLSSocket._raise_closed  s:     $%HII$$,-STT$%@AArB   c                     | j                   | j                          | j                  | j                          | j                  S )zu
        An asn1crypto.x509.Certificate object of the end-entity certificate
        presented by the server
        )r   r   r`  rj  r   s    r@   r   zTLSSocket.certificate  s>     99 $##%   rB   c                     | j                   | j                          | j                  | j                          | j                  S )zz
        A list of asn1crypto.x509.Certificate objects that were presented as
        intermediates by the server
        )r   r   r`  rj  rZ  r   s    r@   intermediateszTLSSocket.intermediates  s>     99 $##%"""rB   c                     | j                   S )zg
        A unicode string of the IANA cipher suite name of the negotiated
        cipher suite
        )r   r   s    r@   r   zTLSSocket.cipher_suite  s     !!!rB   c                     | j                   S )zM
        A unicode string of: "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"
        )r   r   s    r@   rs   zTLSSocket.protocol       ~~rB   c                     | j                   S )z5
        A boolean if compression is enabled
        )r   r   s    r@   r   zTLSSocket.compression  s        rB   c                     | j                   S zM
        A unicode string of "new" or "reused" or None for no ticket
        )r   r   s    r@   r   zTLSSocket.session_id  s     rB   c                     | j                   S rt  )r   r   s    r@   r   zTLSSocket.session_ticket  s     ###rB   c                     | j                   S )zM
        The oscrypto.tls.TLSSession object used for this connection
        )r   r   s    r@   r   zTLSSocket.session  s     }}rB   c                     | j                   S )zN
        A unicode string of the TLS server domain name or IP address
        )r   r   s    r@   r   zTLSSocket.hostname  rq  rB   c                 <    | j                   j                         d   S )zJ
        An integer of the port number the socket is connected to
        r   )r   getpeernamer   s    r@   r   zTLSSocket.port  s     {{&&(++rB   c                 R    | j                   | j                          | j                  S )z9
        The underlying socket.socket connection
        )r   r   r   r   s    r@   r   zTLSSocket.socket  s$     99 ||rB   c                 $    | j                          y r   )r   r   s    r@   r   zTLSSocket.__del__  s    

rB   r   )
   N)7r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r`  rZ  r   r   r   r   r   rP  r   classmethodr   r   r   r   r   rV   r-  r@  rC  rG  rK  r%  r   rQ  r   rj  r   propertyr   rn  r   rs   r   r   r   r   r   r   r   r   r   rB   r@   r7   r7      s    G H D EE L  L J ILNIMLKO M1 1fAFWr*%NU$n#(8t	,&*!X$ 1f$ "1HB ! ! # # " "   ! !     $ $     , ,  rB   )V
__future__r   r   r   r   ra   rer   r   r3  r   _libsslr   r	   
_libcryptor
   r   r   r    r   _asn1r   rW   _errorsr   _ffir   r   r   r   r   _typesr   r   r   r   errorsr   r   r   _tlsr   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   
asymmetricr0   keysr1   
trust_listr2   version_infoxranger[  _pattern_typer6  __all__getrc   compilerB  SSL_OP_NO_SSLv2SSL_OP_NO_SSLv3SSL_OP_NO_TLSv1SSL_OP_NO_TLSv1_1SSL_OP_NO_TLSv1_2rl   rA   objectr6   r7   r   rB   r@   <module>r     s#   R R 
 	    ( c c  2 $ V V < < M M    ( 6 $ !dEfGjjG  #$(():; bjj)((((((,,,,/&F% F%Rd drB   