o ?Og @sdZddlZddlZddlmZddlmZmZ m Z ddl Z ddl m Z mZmZddl mZmZmZddl mZmZmZmZmZmZmZddl mZmZdd l mZmZm Z m!Z!zdd l m"Z"Wn e#yiYnwdd l m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-dd l m.Z.m/Z/e j0d e1dde de j0de1dde de j0de1dde de j0de1dde de j0de1dde de j0de1dde de2j3Z4e2_4dde2j56DZ7e8e2ddZ9Gddde Z:Gd d!d!e Z;Gd"d#d#e Zd&krdd'l m?Z?m@Z@dd(lAmAZAmBZBmCZCdd)lAmDZDmEZEmFZFddlAZGddlHZHddlIZIddlJZJeKZLd*gZMeNe d+ZOe.ZPeZQd,d-ZRd.d/ZSd0d1ZTd2d3ZUed4d5ZVd6d7ZWGd8d9d9ed9d:ZXGd;d<dd>eZZeYj[fdddd?d@dAZ\d[e]dBeYj[ddddddCdDdEZ^e\Z_e^Z`GdFdGdGZadHdIZbGdJdKdKeAZceceZ_deaeZ_edddBe]e3ddLdLdf dMdNZfdOdPZgdQZhdRZidSdTZjdUdVZkeldeFfdWdXZmdYdZZndS)\a This module provides some more Pythonic support for SSL. Object types: SSLSocket -- subtype of socket.socket which does SSL over the socket Exceptions: SSLError -- exception raised for I/O errors Functions: cert_time_to_seconds -- convert time string used for certificate notBefore and notAfter functions to integer seconds past the Epoch (the time values returned from time.time()) get_server_certificate (addr, ssl_version, ca_certs, timeout) -- Retrieve the certificate from the server at the specified address and return it as a PEM-encoded string Integer constants: SSL_ERROR_ZERO_RETURN SSL_ERROR_WANT_READ SSL_ERROR_WANT_WRITE SSL_ERROR_WANT_X509_LOOKUP SSL_ERROR_SYSCALL SSL_ERROR_SSL SSL_ERROR_WANT_CONNECT SSL_ERROR_EOF SSL_ERROR_INVALID_ERROR_CODE The following group define certificate requirements that one side is allowing/requiring from the other side: CERT_NONE - no certificates from the other side are required (or will be looked at if provided) CERT_OPTIONAL - certificates are not required, but if provided will be validated, and if validation fails, the connection will also fail CERT_REQUIRED - certificates are required, and will be validated, and if validation fails, the connection will also fail The following constants identify various SSL protocol variants: PROTOCOL_SSLv2 PROTOCOL_SSLv3 PROTOCOL_SSLv23 PROTOCOL_TLS PROTOCOL_TLS_CLIENT PROTOCOL_TLS_SERVER PROTOCOL_TLSv1 PROTOCOL_TLSv1_1 PROTOCOL_TLSv1_2 The following constants identify various SSL alert message descriptions as per http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 ALERT_DESCRIPTION_CLOSE_NOTIFY ALERT_DESCRIPTION_UNEXPECTED_MESSAGE ALERT_DESCRIPTION_BAD_RECORD_MAC ALERT_DESCRIPTION_RECORD_OVERFLOW ALERT_DESCRIPTION_DECOMPRESSION_FAILURE ALERT_DESCRIPTION_HANDSHAKE_FAILURE ALERT_DESCRIPTION_BAD_CERTIFICATE ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE ALERT_DESCRIPTION_CERTIFICATE_REVOKED ALERT_DESCRIPTION_CERTIFICATE_EXPIRED ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN ALERT_DESCRIPTION_ILLEGAL_PARAMETER ALERT_DESCRIPTION_UNKNOWN_CA ALERT_DESCRIPTION_ACCESS_DENIED ALERT_DESCRIPTION_DECODE_ERROR ALERT_DESCRIPTION_DECRYPT_ERROR ALERT_DESCRIPTION_PROTOCOL_VERSION ALERT_DESCRIPTION_INSUFFICIENT_SECURITY ALERT_DESCRIPTION_INTERNAL_ERROR ALERT_DESCRIPTION_USER_CANCELLED ALERT_DESCRIPTION_NO_RENEGOTIATION ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE ALERT_DESCRIPTION_UNRECOGNIZED_NAME ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY N) namedtuple)EnumIntEnumIntFlag)OPENSSL_VERSION_NUMBEROPENSSL_VERSION_INFOOPENSSL_VERSION) _SSLContext MemoryBIO SSLSession)SSLErrorSSLZeroReturnErrorSSLWantReadErrorSSLWantWriteErrorSSLSyscallError SSLEOFErrorSSLCertVerificationError)txt2objnid2obj) RAND_statusRAND_add RAND_bytesRAND_pseudo_bytes)RAND_egd) HAS_SNIHAS_ECDHHAS_NPNHAS_ALPN HAS_SSLv2 HAS_SSLv3 HAS_TLSv1 HAS_TLSv1_1 HAS_TLSv1_2 HAS_TLSv1_3)_DEFAULT_CIPHERS_OPENSSL_API_VERSION _SSLMethodcCs|do|dkS)NZ PROTOCOL_PROTOCOL_SSLv23 startswithnamer,*/opt/alt/python310/lib64/python3.10/ssl.py}sr.)sourceOptionscC |dS)NZOP_r(r*r,r,r-r. ZAlertDescriptioncCr1)NZALERT_DESCRIPTION_r(r*r,r,r-r.r2ZSSLErrorNumbercCr1)NZ SSL_ERROR_r(r*r,r,r-r.r2 VerifyFlagscCr1)NZVERIFY_r(r*r,r,r-r.r2 VerifyModecCr1)NZCERT_r(r*r,r,r-r.r2cCsi|]\}}||qSr,r,).0r+valuer,r,r- sr7ZPROTOCOL_SSLv2c@s6eZdZejZejZejZ ej Z ej Z ejZejZdS) TLSVersionN)__name__ __module__ __qualname___sslZPROTO_MINIMUM_SUPPORTEDZMINIMUM_SUPPORTEDZ PROTO_SSLv3SSLv3Z PROTO_TLSv1ZTLSv1Z PROTO_TLSv1_1ZTLSv1_1Z PROTO_TLSv1_2ZTLSv1_2Z PROTO_TLSv1_3ZTLSv1_3ZPROTO_MAXIMUM_SUPPORTEDZMAXIMUM_SUPPORTEDr,r,r,r-r8s r8c@s(eZdZdZdZdZdZdZdZdZ dS) _TLSContentTypez@Content types (record layer) See RFC 8446, section B.1 N) r9r:r;__doc__CHANGE_CIPHER_SPECALERTZ HANDSHAKEZAPPLICATION_DATAHEADERZINNER_CONTENT_TYPEr,r,r,r-r>sr>c@seZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$S)% _TLSAlertTypezQAlert types for TLSContentType.ALERT messages See RFC 8466, section B.2 r r?r@rA()*+,-./0123<FGPVZdmnopqrstxN)&r9r:r;rEZ CLOSE_NOTIFYZUNEXPECTED_MESSAGEZBAD_RECORD_MACZDECRYPTION_FAILEDZRECORD_OVERFLOWZDECOMPRESSION_FAILUREZHANDSHAKE_FAILUREZNO_CERTIFICATEZBAD_CERTIFICATEZUNSUPPORTED_CERTIFICATEZCERTIFICATE_REVOKEDZCERTIFICATE_EXPIREDZCERTIFICATE_UNKNOWNZILLEGAL_PARAMETERZ UNKNOWN_CAZ ACCESS_DENIEDZ DECODE_ERRORZ DECRYPT_ERRORZEXPORT_RESTRICTIONZPROTOCOL_VERSIONZINSUFFICIENT_SECURITYZINTERNAL_ERRORZINAPPROPRIATE_FALLBACKZ USER_CANCELEDZNO_RENEGOTIATIONZMISSING_EXTENSIONZUNSUPPORTED_EXTENSIONZCERTIFICATE_UNOBTAINABLEZUNRECOGNIZED_NAMEZBAD_CERTIFICATE_STATUS_RESPONSEZBAD_CERTIFICATE_HASH_VALUEZUNKNOWN_PSK_IDENTITYZCERTIFICATE_REQUIREDZNO_APPLICATION_PROTOCOLr,r,r,r-rIsHrIc@sheZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdS)_TLSMessageTypezFMessage types (handshake protocol) See RFC 8446, section B.3 r r?r@rArBCrDN)r9r:r;rEZ HELLO_REQUESTZ CLIENT_HELLOZ SERVER_HELLOZHELLO_VERIFY_REQUESTZNEWSESSION_TICKETZEND_OF_EARLY_DATAZHELLO_RETRY_REQUESTZENCRYPTED_EXTENSIONSZ CERTIFICATEZSERVER_KEY_EXCHANGEZCERTIFICATE_REQUESTZ SERVER_DONEZCERTIFICATE_VERIFYZCLIENT_KEY_EXCHANGEZFINISHEDZCERTIFICATE_URLZCERTIFICATE_STATUSZSUPPLEMENTAL_DATAZ KEY_UPDATEZ NEXT_PROTOZ MESSAGE_HASHrFr,r,r,r-rhs0rhwin32)enum_certificates enum_crls)socket SOCK_STREAMcreate_connection) SOL_SOCKETSO_TYPE_GLOBAL_DEFAULT_TIMEOUT tls-uniqueHOSTFLAG_NEVER_CHECK_SUBJECTcCs|sdS|d}|s||kS|dkrtd||d\}}}d|vr1td||s:td||dkrEtd||d\}}}|rQ|sSdS||kS) aMatching according to RFC 6125, section 6.4.3 - Hostnames are compared lower case. - For IDNA, both dn and hostname must be encoded as IDN A-label (ACE). - Partial wildcards like 'www*.example.org', multiple wildcards, sole wildcard or wildcards in labels other then the left-most label are not supported and a CertificateError is raised. - A wildcard must match at least one character. F*riz1too many wildcards in certificate DNS name: {!r}..z9wildcard can only be present in the leftmost label: {!r}.z>sole wildcard without additional labels are not support: {!r}.zt||r>dS||q*|d krY|durTt||rTdS||q*|s~|d dD]}|D]\}}|d kr|t||rwdS||qfqbt |d krt d |d t t |ft |d krt d||dft d)aVerify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed. The function matches IP addresses rather than dNSNames if hostname is a valid ipaddress string. IPv4 addresses are supported on all platforms. IPv6 addresses are supported on platforms with IPv6 support (AF_INET6 and inet_pton). CertificateError is raised on failure. On success, the function returns nothing. z"ssl.match_hostname() is deprecatedrjcategory stacklevelztempty or no certificate, match_hostname needs a SSL socket or SSL context with either CERT_OPTIONAL or CERT_REQUIREDNZsubjectAltNamer,ZDNSz IP AddresssubjectZ commonNameriz&hostname %r doesn't match either of %sz, zhostname %r doesn't match %rrz=no appropriate commonName or subjectAltName fields were found)warningswarnDeprecationWarningrrgetrappendrlenrjoinmaprepr)certrrZdnsnamesZsankeyr6subr,r,r-match_hostnametsT             rDefaultVerifyPathszQcafile capath openssl_cafile_env openssl_cafile openssl_capath_env openssl_capathcCsft}tj|d|d}tj|d|d}ttj|r#|ndtj|r,|ndg|RS)z/Return paths to default cafile and capath. rrirjrkN) r<get_default_verify_pathsosenvironrrpathisfileisdir)partscafilecapathr,r,r-rsrcsDeZdZdZdZfddZefddZefddZZ S) _ASN1Objectz#ASN.1 object identifier lookup r,ctj|gt|ddRS)NFr*super__new___txt2obj)clsoid __class__r,r-rsz_ASN1Object.__new__cstj|gt|RS)z3Create _ASN1Object from OpenSSL numeric ID )rr_nid2obj)rZnidrr,r-fromnidsz_ASN1Object.fromnidcr)z=Create _ASN1Object from short name, long name or OID Tr*r)rr+rr,r-fromnamesz_ASN1Object.fromname) r9r:r;rE __slots__r classmethodrr __classcell__r,r,rr-rs rznid shortname longname oidc@seZdZdZdZdZdS)PurposezDSSLContext purpose flags with X509v3 Extended Key Usage objects z1.3.6.1.5.5.7.3.1z1.3.6.1.5.5.7.3.2N)r9r:r;rE SERVER_AUTH CLIENT_AUTHr,r,r,r-rsrcseZdZdZdZdZdZd2ddZddZ  d3d d Z  d4d d Z ddZ ddZ ddZ ddZejfddZeedrcefddZejfddZefddZejfddZefdd Zejfd!d Zeed"red#d$Zejd%d$Zned&d$Zefd'd(Zejfd)d(Zefd*d+Zefd,d-Zejfd.d-Zefd/d0Zejfd1d0ZZS)5 SSLContextz|An SSLContext holds various SSL-related configuration options and data, such as certificates and possibly a private key.)ZCAZROOTNcOs,|durtjdtddt}t||}|S)Nz9ssl.SSLContext() without protocol argument is deprecated.rjr)rrr PROTOCOL_TLSr r)rprotocolargskwargsselfr,r,r-rs zSSLContext.__new__cCs0|durdSt|tr|ddS|dS)NZidnaascii) isinstancestrencodedecode)rrr,r,r-_encode_hostnames   zSSLContext._encode_hostnameFTc Cs|jj|||||||dS)N)sock server_sidedo_handshake_on_connectsuppress_ragged_eofsserver_hostnamecontextsession)sslsocket_class_create)rrrrrrrr,r,r- wrap_socketszSSLContext.wrap_socketcCs|jj|||||||dS)N)rrrr)sslobject_classrr)rincomingoutgoingrrrr,r,r-wrap_bio s zSSLContext.wrap_biocCsptjdtddt}|D]#}t|d}t|dks t|dkr$td|t|||q | |dS)N'ssl NPN is deprecated, use ALPN insteadrjrrrz(NPN protocols must be 1 to 255 in length) rrr bytearraybytesrr rextendZ_set_npn_protocols)rZ npn_protocolsprotosrbr,r,r-set_npn_protocolss  zSSLContext.set_npn_protocolscs:dur d_dStstdfdd}|_dS)Nznot a callable objectcs|}|||SN)r)sslobjZ servernameZsslctxrserver_name_callbackr,r-shim_cb,s  z3SSLContext.set_servername_callback..shim_cb)Z sni_callbackcallable TypeError)rrrr,rr-set_servername_callback%s   z"SSLContext.set_servername_callbackcCs`t}|D]#}t|d}t|dkst|dkrtd|t|||q||dS)Nrrrz)ALPN protocols must be 1 to 255 in length)rrrr rrZ_set_alpn_protocols)rZalpn_protocolsrrrr,r,r-set_alpn_protocols2s  zSSLContext.set_alpn_protocolscCstt}zt|D]\}}}|dkr|dus|j|vr||qWnty/tdYnw|r8|j|d|S)NZx509_asnTz-unable to enumerate Windows certificate store)cadata)rrzrrPermissionErrorrrload_verify_locations)r storenamepurposeZcertsrencodingZtrustr,r,r-_load_windows_store_certs=s   z$SSLContext._load_windows_store_certscCs@t|ts t|tjdkr|jD]}|||q|dS)Nry)rrrsysplatform_windows_cert_storesrZset_default_verify_paths)rrrr,r,r-load_default_certsKs    zSSLContext.load_default_certsminimum_versionc ttjSr)r8rrrrr,r-rT zSSLContext.minimum_versioncs4|tjkr|jtjM_tttj||dSr) r8r=optionsr0Z OP_NO_SSLv3rrr__set__rr6rr,r-rXs crr)r8rmaximum_versionrrr,r-r^rzSSLContext.maximum_versionctttj||dSr)rrrrrrr,r-rbcrr)r0rrrrr,r-rfrzSSLContext.optionscrr)rrrrrrr,r-rjrrcCs|jtj@}|tjkSrZ _host_flagsr<r)rZncsr,r,r-hostname_checks_common_nameos  z&SSLContext.hostname_checks_common_namecCs.|r |jtjM_dS|jtjO_dSrrrr,r,r-rtscCsdS)NTr,rr,r,r-r{cstj}|dur |jSdS)a9TLS message callback The message callback provides a debugging hook to analyze TLS connections. The callback is called for any TLS protocol message (header, handshake, alert, and more), but not for application data. Due to technical limitations, the callback can't be used to filter traffic or to abort a connection. Any exception raised in the callback is delayed until the handshake, read, or write operation has been performed. def msg_cb(conn, direction, version, content_type, msg_type, data): pass conn :class:`SSLSocket` or :class:`SSLObject` instance direction ``read`` or ``write`` version :class:`TLSVersion` enum member or int for unknown version. For a frame header, it's the header version. content_type :class:`_TLSContentType` enum member or int for unsupported content type. msg_type Either a :class:`_TLSContentType` enum number for a header message, a :class:`_TLSAlertType` enum member for an alert message, a :class:`_TLSMessageType` enum member for other messages, or int for unsupported message types. data Raw, decrypted message content as bytes N)r _msg_callback user_function)rinnerrr,r-r s!zSSLContext._msg_callbackcsbdurtttj|ddStdstdfdd}|_tttj||dS)N__call__z is not callable.cszt|}Wn tyYnwzt|}Wn tyYnw|tjkr(t}n |tjkr0t}nt}z||}Wn tyAYnw||||||Sr)r8rr>rHrGrIrh)ZconnZ directionversionZ content_typeZmsg_typedataZmsg_enumcallbackr,r-r s.        z'SSLContext._msg_callback..inner)rrr rhasattrrr )rrr rrr-r s  crr)r&rrrrr,r-rrzSSLContext.protocolcrr)r3r verify_flagsrrr,r-rrzSSLContext.verify_flagscrr)rrrrrrr,r-rrcs*tj}zt|WSty|YSwr)r verify_moder4rrrr,r-rs   zSSLContext.verify_modecrr)rrrrrrr,r-rrr)FTTNN)FNN) r9r:r;rErrrrrrrrrrrrrrrr propertyrsetterrrr<rr rrrrr,r,rr-rsl            &%r)rrrcCst|ts t||tjkrtt}t|_d|_ n|tj kr#tt }nt ||s-|s-|r5| |||n |jtkr?||t|drStjd}|rStjjsS||_|S)zCreate a SSLContext object with default settings. NOTE: The protocol and settings may change anytime without prior deprecation. The values represent a fair balance between maximum compatibility and security. Tkeylog_filename SSLKEYLOGFILE)rrrrrrPROTOCOL_TLS_CLIENT CERT_REQUIREDrcheck_hostnamerPROTOCOL_TLS_SERVERrr CERT_NONErrrrrrflagsignore_environmentr)rrrrr keylogfiler,r,r-create_default_contexts$          r F) cert_reqsrrcertfilekeyfilerrrc Cst|ts t||tjkr|durt}n|tjkr!|dur t}nt|t |} || _ |dur3|| _ |r8d| _ |r@|s@td|sD|rJ| |||sP|sP|rX| |||n | j tkrb| |t| drvtjd} | rvtjjsv| | _| S)a/Create a SSLContext object for Python stdlib modules All Python stdlib modules shall use this function to create SSLContext objects in order to keep common settings in one place. The configuration is less restrict than create_default_context()'s to increase backward compatibility. NTcertfile must be specifiedrr)rrrrrrrrrrrrload_cert_chainrrrrrrrrrrr) rr!rrr"r#rrrrrr,r,r-_create_unverified_context s<          r&c@seZdZdZddZe  d2ddZedd Zej d d Zed d Z e j d d Z eddZ eddZ eddZ d3ddZddZd4ddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd5d,d-Zd.d/Zd0d1ZdS)6 SSLObjectaThis class implements an interface on top of a low-level SSL object as implemented by OpenSSL. This object captures the state of an SSL connection but does not provide any network IO itself. IO needs to be performed through separate "BIO" objects which are OpenSSL's IO abstraction layer. This class does not have a public constructor. Instances are returned by ``SSLContext.wrap_bio``. This class is typically used by framework authors that want to implement asynchronous IO for SSL through memory buffers. When compared to ``SSLSocket``, this object lacks the following features: * Any form of network IO, including methods such as ``recv`` and ``send``. * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery. cOt|jjd)NzU does not have a public constructor. Instances are returned by SSLContext.wrap_bio().rrr9rrrr,r,r-__init__X zSSLObject.__init__FNc Cs*||}|j||||||d}||_|S)N)rrownerr)rZ _wrap_bio_sslobj) rrrrrrrrrr,r,r-r^s zSSLObject._createcC|jjS)z(The SSLContext that is currently in use.r.rrr,r,r-rjzSSLObject.contextcC ||j_dSrr0rctxr,r,r-rorcCr/)z!The SSLSession for client socket.r.rrr,r,r-rsr1zSSLObject.sessioncCr2rr5rrr,r,r-rxrcCr/)z.Was the client session reused during handshaker.session_reusedrr,r,r-r8|r1zSSLObject.session_reusedcCr/)z%Whether this is a server-side socket.)r.rrr,r,r-rr1zSSLObject.server_sidecCr/)z^The currently set server hostname (for SNI), or ``None`` if no server hostname is set.)r.rrr,r,r-rszSSLObject.server_hostnamecCs*|dur |j||}|S|j|}|S)zRead up to 'len' bytes from the SSL object and return them. If 'buffer' is provided, read into this buffer and return the number of bytes read. N)r.read)rrbuffervr,r,r-r:s  zSSLObject.readcC |j|S)zWrite 'data' to the SSL object and return the number of bytes written. The 'data' argument must support the buffer interface. )r.writerrr,r,r-r>s zSSLObject.writecCr=)zReturns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated. )r. getpeercertrZ binary_formr,r,r-r@s zSSLObject.getpeercertcCstjdtdddS)zReturn the currently selected NPN protocol as a string, or ``None`` if a next protocol was not negotiated or if NPN is not supported by one of the peers.rrjrN)rrrrr,r,r-selected_npn_protocols  zSSLObject.selected_npn_protocolcC |jS)zReturn the currently selected ALPN protocol as a string, or ``None`` if a next protocol was not negotiated or if ALPN is not supported by one of the peers.)r.selected_alpn_protocolrr,r,r-rD z SSLObject.selected_alpn_protocolcCrC)z_Return the currently selected cipher as a 3-tuple ``(name, ssl_version, secret_bits)``.)r.cipherrr,r,r-rF zSSLObject.ciphercCrC)zReturn a list of ciphers shared by the client during the handshake or None if this is not a valid server connection. )r.shared_ciphersrr,r,r-rHrEzSSLObject.shared_cipherscCrC)zReturn the current compression algorithm in use, or ``None`` if compression was not negotiated or not supported by one of the peers.)r. compressionrr,r,r-rIrGzSSLObject.compressioncCrC)z8Return the number of bytes that can be read immediately.)r.pendingrr,r,r-rJ zSSLObject.pendingcCs|jdS)zStart the SSL/TLS handshake.N)r. do_handshakerr,r,r-rLszSSLObject.do_handshakecCrC)z!Start the SSL shutdown handshake.)r.shutdownrr,r,r-unwraprKzSSLObject.unwraprcCr=)zGet channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake).)r.get_channel_bindingrZcb_typer,r,r-rOs zSSLObject.get_channel_bindingcCrC)zZReturn a string identifying the protocol version used by the current SSL channel. r.r rr,r,r-r rGzSSLObject.versioncCrCr)r.verify_client_post_handshakerr,r,r-rRs z&SSLObject.verify_client_post_handshake)FNNNr9NFr)r9r:r;rEr+rrrrrrr8rrr:r>r@rBrDrFrHrIrJrLrNrOr rRr,r,r,r-r'IsF              r'cCstt|jj|_|S)z*Copy docstring from SSLObject to SSLSocket)getattrr'r9rE)funcr,r,r- _sslcopydocsrXcs eZdZdZddZe   dXfdd Zeed d Z e j d d Z eed d Z e j dd Z eeddZ ddZ dYddZddZdZddZddZed[ddZeddZed d!Zed"d#Zed$d%Zed&d'Zd\fd)d* ZdYfd+d, Zd-d.Zd\fd/d0 Zd]fd1d2 Zd^fd3d4 Zd_fd5d6 Zd^fd7d8 Zd_fd9d: Z d;d<Z!d=d>Z"ed?d@Z#fdAdBZ$edCdDZ%edEdFZ&fdGdHZ'ed[dIdJZ(fdKdLZ)dMdNZ*dOdPZ+fdQdRZ,ed`dTdUZ-edVdWZ.Z/S)a SSLSocketzThis class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and provides read and write methods over that channel. cOr()NzX does not have a public constructor. Instances are returned by SSLContext.wrap_socket().r)r*r,r,r-r+r,zSSLSocket.__init__FTNc sX|tttkr td|r|rtd|durtd|jr%|s%tdt|j|j |j | d}|j |fi|} t t| jdi||} ||| _|| _d| _d| _|| _||| _|| _|| _z| Wnuty} zi| jtjkr~d} | } | dz| !d}Wnty} z| jtjtj"fvrd}WYd} ~ nd} ~ ww| | |rd }t#| j|}||_$d|_%z| &Wn tyYnwz|d}wWYd} ~ nd} ~ wwd } | '| | | _(| r*z(| jj)| || j| | jd | _|r| }|d krtd | *W| SW| Sttfy)| &w| S)Nz!only stream sockets are supportedz4server_hostname can only be specified in client modez,session can only be specified in client modez'check_hostname requires server_hostname)familytypeprotofilenoFriz5Closed before TLS handshake with data in recv buffer.Tr-rzHdo_handshake_on_connect should not be specified for non-blocking socketsr,)+Z getsockoptrrr}NotImplementedErrorrrdictrZr[r\r]rrrYr+ gettimeoutdetach_context_sessionZ_closedr.rrrrr getpeernamererrnoZENOTCONNZ getblockingZ setblockingrecvZEINVALr reasonZlibraryclose settimeout _connected _wrap_socketrL)rrrrrrrrrrZ sock_timeouteZ connectedZblockingZnotconn_pre_handshake_datarjZ notconn_pre_handshake_data_errortimeoutrr,r-rs           %    zSSLSocket._createcCs|jSr)rerr,r,r-rVszSSLSocket.contextcCs||_||j_dSr)rer.rr3r,r,r-r[s cC|jdur |jjSdSrr5rr,r,r-r` zSSLSocket.sessioncCs ||_|jdur||j_dSdSr)rfr.rr6r,r,r-rfs  cCrqrr7rr,r,r-r8lrrzSSLSocket.session_reusedcCstd|jj)NzCan't dup() %s instances)rarr9rr,r,r-duprsz SSLSocket.dupcCsdSrr,)rmsgr,r,r- _checkClosedvrzSSLSocket._checkClosedcCs|js |dSdSr)rmrgrr,r,r-_check_connectedzs zSSLSocket._check_connectedr9c Cs||jdur tdz|dur|j||WS|j|WStyI}z|jdtkrD|jrD|dur=WYd}~dSWYd}~dSd}~ww)zORead up to LEN bytes and return them. Return zero-length string on EOF.Nz'Read on closed or unwrapped SSL socket.rr^)rur.rr:r rZ SSL_ERROR_EOFr)rrr;xr,r,r-r:s zSSLSocket.readcCs&||jdur td|j|S)zhWrite DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted.Nz(Write on closed or unwrapped SSL socket.)rur.rr>r?r,r,r-r>s  zSSLSocket.writecCs|||j|Sr)rurvr.r@rAr,r,r-r@s zSSLSocket.getpeercertcCs|tjdtdddS)Nrrjr)rurrrrr,r,r-rBszSSLSocket.selected_npn_protocolcCs&||jdus tjsdS|jSr)rur.r<rrDrr,r,r-rDs z SSLSocket.selected_alpn_protocolcC ||jdur dS|jSr)rur.rFrr,r,r-rF  zSSLSocket.ciphercCrxr)rur.rHrr,r,r-rHryzSSLSocket.shared_cipherscCrxr)rur.rIrr,r,r-rIryzSSLSocket.compressionrcsB||jdur|dkrtd|j|j|St||S)Nrz3non-zero flags not allowed in calls to send() on %s)rur.rrr>rsend)rrrrr,r-rzs  zSSLSocket.sendcsF||jdurtd|j|durt||St|||S)Nz%sendto not allowed on instances of %s)rur.rrrsendto)rrZ flags_or_addrrrr,r-r{s zSSLSocket.sendtocOtd|j)Nz&sendmsg not allowed on instances of %srarr*r,r,r-sendmsgszSSLSocket.sendmsgc s||jdurc|dkrtd|jd}t|?}|d!}t|}||kr:|||d}||7}||ks)Wdn1sDwYWddSWddS1s\wYdSt ||S)Nrz6non-zero flags not allowed in calls to sendall() on %sB) rur.rr memoryviewcastrrzrsendall)rrrrZviewZ byte_viewZamountr<rr,r-rs$ PzSSLSocket.sendallcs(|jdur ||||St|||S)zSend a file, possibly by using os.sendfile() if this is a clear-text socket. Return the total number of bytes sent. N)r.Z_sendfile_use_sendrsendfile)rfileoffsetrrr,r-rs zSSLSocket.sendfilecs@||jdur|dkrtd|j||St||S)Nrz3non-zero flags not allowed in calls to recv() on %s)rur.rrr:rrirZbuflenrrr,r-ris  zSSLSocket.recvcsf||r|durt|}n|durd}|jdur+|dkr%td|j|||St|||S)Nr9rz8non-zero flags not allowed in calls to recv_into() on %s)rurr.rrr:r recv_intorr;nbytesrrr,r-rs    zSSLSocket.recv_intocs.||jdurtd|jt||S)Nz'recvfrom not allowed on instances of %s)rur.rrrrecvfromrrr,r-rs  zSSLSocket.recvfromcs0||jdurtd|jt|||S)Nz,recvfrom_into not allowed on instances of %s)rur.rrr recvfrom_intorrr,r-r's  zSSLSocket.recvfrom_intocOr|)Nz&recvmsg not allowed on instances of %sr}r*r,r,r-recvmsg/zSSLSocket.recvmsgcOr|)Nz+recvmsg_into not allowed on instances of %sr}r*r,r,r- recvmsg_into3rzSSLSocket.recvmsg_intocCs ||jdur|jSdSNr)rur.rJrr,r,r-rJ7s  zSSLSocket.pendingcs|d|_t|dSr)rur.rrM)rZhowrr,r-rM?szSSLSocket.shutdowncCs*|jr |j}d|_|Stdt|NzNo SSL wrapper around )r.rMrr)rsr,r,r-rNDs  zSSLSocket.unwrapcCs |jr|jStdt|r)r.rRrrrr,r,r-rRMs z&SSLSocket.verify_client_post_handshakecsd|_tdSr)r.r _real_closerrr,r-rTszSSLSocket._real_closec CsN||}z|dkr|r|d|jW||dS||w)Nr`)rvrcrlr.rL)rblockrpr,r,r-rLXs   zSSLSocket.do_handshakec s|jrtd|js|jdurtd|jj|d|j||jd|_z |r+t |}nd}t ||s?d|_|j r?| |WSt tfyNd|_w)Nz!can't connect in server-side modez/attempt to connect already-connected SSLSocket!Fr_T)rrrmr.rrnrrfr connect_exconnectrrLr)rrrZrcrr,r- _real_connectcs, zSSLSocket._real_connectcCs||ddS)QConnects to remote ADDR, and then wraps the connection in an SSL channel.FNrrrr,r,r-r}szSSLSocket.connectcCs ||dS)rTrrr,r,r-rs zSSLSocket.connect_excs.t\}}|jj||j|jdd}||fS)zAccepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.T)rrr)racceptrrrr)rZnewsockrrr,r-rszSSLSocket.acceptrcCs0|jdur |j|S|tvrtd|dS)Nz({0} channel binding type not implemented)r.rOCHANNEL_BINDING_TYPESrrrPr,r,r-rOs  zSSLSocket.get_channel_bindingcCs|jdur |jSdSrrQrr,r,r-r s  zSSLSocket.version)FTTNNNrrSrT)r)rN)r9rrrU)0r9r:r;rEr+rrrrXrrrr8rsrurvr:r>r@rBrDrFrHrIrzr{r~rrrirrrrrrJrMrNrRrrLrrrrrOr rr,r,rr-rYs_                           rYTc Cs|tjdtdd|r|std|r|stdt|} || _|r&| ||r.| ||| r5| | | j ||||dS)Nz=ssl.wrap_socket() is deprecated, use SSLContext.wrap_socket()rjrz5certfile must be specified for server-side operationsr$)rrrr) rrrrrrrr%Z set_ciphersr) rr#r"rr! ssl_versionca_certsrrZciphersrr,r,r-rs,   rcCsddlm}ddlm}d}d}z||ddd}Wnty.td ||fw||dd|}||d|f|d d S) aReturn the time in seconds since the Epoch, given the timestring representing the "notBefore" or "notAfter" date from a certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). "notBefore" or "notAfter" dates must use UTC (RFC 5280). Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec UTC should be specified as GMT (see ASN1_TIME_print()) r)strptime)timegm) ZJanZFebZMarZAprZMayZJunZJulZAugZSepZOctZNovZDecz %d %H:%M:%S %Y GMTNrkriz*time data %r does not match format "%%b%s"rjrn)timerZcalendarrindextitler)Z cert_timerrZmonthsZ time_formatZ month_numberZttr,r,r-cert_time_to_secondss  rz-----BEGIN CERTIFICATE-----z-----END CERTIFICATE-----csRtt|ddtg}|fddtdtdD7}|tdd|S)z[Takes a certificate in binary DER format and returns the PEM version of it as a string.ASCIIstrictcsg|] }||dqS)@r,)r5ifr,r- sz(DER_cert_to_PEM_cert..rr ) rbase64Zstandard_b64encode PEM_HEADERrangerr PEM_FOOTERr)Zder_cert_bytesZssr,rr-DER_cert_to_PEM_certs " rcCs\|ts tdt|tstdt|tttt }t| ddS)zhTakes a certificate in ASCII PEM format and returns the DER-encoded version of it as a byte sequencez(Invalid PEM encoding; must start with %sz&Invalid PEM encoding; must end with %srr) r)rrstripendswithrrrZ decodebytesr)Zpem_cert_stringdr,r,r-PEM_cert_to_DER_certs rc Cs|\}}|dur t}nt}t|||d}t||d1}|j||d } | d} Wdn1s2wYWdt| SWdt| S1sNwYt| S)a=Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt. If 'timeout' is specified, use it in the connection attempt. N)r!r)rp)rT)rr_create_stdlib_contextr~rr@r) rrrrpZhostZportr!rrZsslsockZdercertr,r,r-get_server_certificates&    rcCs t|dS)Nz )_PROTOCOL_NAMESr)Z protocol_coder,r,r-get_protocol_names rr)orErr collectionsrenumrZ_EnumrZ_IntEnumrZ_IntFlagr<rrrr r r r r rrrrrrrrrrrrrr ImportErrorrrrrrrr r!r"r#r$r% _convert_r9r&rr' __members__itemsrrVZ_SSLv2_IF_EXISTSr8r>rIrhrrzr{r|r}r~rrrrrrhrrZ socket_errorrrZHAS_NEVER_CHECK_COMMON_NAMEZ_RESTRICTED_SERVER_CIPHERSrrrrrrrrrrrr rr&Z_create_default_https_contextrr'rXrYrrrrrrrrrrrr,r,r,r-sZ $ 0   )  1# > & 7@