o w[e @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)N PROTOCOL_PROTOCOL_SSLv23 startswithnamer-/usr/lib/python3.10/ssl.py}sr/)sourceOptionscC |dS)NOP_r)r+r-r-r.r/ AlertDescriptioncCr2)NALERT_DESCRIPTION_r)r+r-r-r.r/r4SSLErrorNumbercCr2)N SSL_ERROR_r)r+r-r-r.r/r4 VerifyFlagscCr2)NVERIFY_r)r+r-r-r.r/r4 VerifyModecCr2)NCERT_r)r+r-r-r.r/r4cCsi|]\}}||qSr-r-).0r,valuer-r-r. sr?PROTOCOL_SSLv2c@s6eZdZejZejZejZ ej Z ej Z ejZejZdS) TLSVersionN)__name__ __module__ __qualname___sslPROTO_MINIMUM_SUPPORTEDMINIMUM_SUPPORTED PROTO_SSLv3SSLv3 PROTO_TLSv1TLSv1 PROTO_TLSv1_1TLSv1_1 PROTO_TLSv1_2TLSv1_2 PROTO_TLSv1_3TLSv1_3PROTO_MAXIMUM_SUPPORTEDMAXIMUM_SUPPORTEDr-r-r-r.rAs rAc@s(eZdZdZdZdZdZdZdZdZ dS) _TLSContentTypez@Content types (record layer) See RFC 8446, section B.1 N) rBrCrD__doc__CHANGE_CIPHER_SPECALERT HANDSHAKEAPPLICATION_DATAHEADERINNER_CONTENT_TYPEr-r-r-r.rTsrTc@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 rUrVrW()*+,-./0123<FGPVZdmnopqrstxN)&rBrCrDr[ CLOSE_NOTIFYUNEXPECTED_MESSAGEBAD_RECORD_MACDECRYPTION_FAILEDRECORD_OVERFLOWDECOMPRESSION_FAILUREHANDSHAKE_FAILURENO_CERTIFICATEBAD_CERTIFICATEUNSUPPORTED_CERTIFICATECERTIFICATE_REVOKEDCERTIFICATE_EXPIREDCERTIFICATE_UNKNOWNILLEGAL_PARAMETER UNKNOWN_CA ACCESS_DENIED DECODE_ERROR DECRYPT_ERROREXPORT_RESTRICTIONPROTOCOL_VERSIONINSUFFICIENT_SECURITYINTERNAL_ERRORINAPPROPRIATE_FALLBACK USER_CANCELEDNO_RENEGOTIATIONMISSING_EXTENSIONUNSUPPORTED_EXTENSIONCERTIFICATE_UNOBTAINABLEUNRECOGNIZED_NAMEBAD_CERTIFICATE_STATUS_RESPONSEBAD_CERTIFICATE_HASH_VALUEUNKNOWN_PSK_IDENTITYCERTIFICATE_REQUIREDNO_APPLICATION_PROTOCOLr-r-r-r.rbsHrbc@sheZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdS)_TLSMessageTypezFMessage types (handshake protocol) See RFC 8446, section B.3 r rUrVrWrXCrZN)rBrCrDr[ HELLO_REQUEST CLIENT_HELLO SERVER_HELLOHELLO_VERIFY_REQUESTNEWSESSION_TICKETEND_OF_EARLY_DATAHELLO_RETRY_REQUESTENCRYPTED_EXTENSIONS CERTIFICATESERVER_KEY_EXCHANGECERTIFICATE_REQUEST SERVER_DONECERTIFICATE_VERIFYCLIENT_KEY_EXCHANGEFINISHEDCERTIFICATE_URLCERTIFICATE_STATUSSUPPLEMENTAL_DATA KEY_UPDATE NEXT_PROTO MESSAGE_HASHr\r-r-r-r.rs0rwin32)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*rz1too 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 deprecatedrcategory stacklevelztempty or no certificate, match_hostname needs a SSL socket or SSL context with either CERT_OPTIONAL or CERT_REQUIREDNsubjectAltNamer-DNSz IP Addresssubject commonNamerz&hostname %r doesn't match either of %sz, zhostname %r doesn't match %rrz=no appropriate commonName or subjectAltName fields were found)warningswarnDeprecationWarningrrgetrappendrlenrjoinmaprepr)certrrdnsnamessankeyr>subr-r-r.match_hostnametsT             r DefaultVerifyPathszQcafile 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. rrrrN) rEget_default_verify_pathsosenvironrr pathisfileisdir)partscafilecapathr-r-r.r sr csDeZdZdZdZfddZefddZefddZZ 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)rnidrr-r.fromnidsz_ASN1Object.fromnidcr)z=Create _ASN1Object from short name, long name or OID Tr+r)rr,rr-r.fromnamesz_ASN1Object.fromname) rBrCrDr[ __slots__r classmethodr r! __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)rBrCrDr[ SERVER_AUTH CLIENT_AUTHr-r-r-r.r%sr%cseZdZdZdZdZdZd2ddZddZ  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.)CAROOTNcOs,|durtjdtddt}t||}|S)Nz9ssl.SSLContext() without protocol argument is deprecated.rr)rrr PROTOCOL_TLSr r)rprotocolargskwargsselfr-r-r.rs zSSLContext.__new__cCs0|durdSt|tr|ddS|dS)Nidnaascii) isinstancestrencodedecode)r/rr-r-r._encode_hostnames   zSSLContext._encode_hostnameFTc Cs|jj|||||||dS)N)sock server_sidedo_handshake_on_connectsuppress_ragged_eofsserver_hostnamecontextsession)sslsocket_class_create)r/r7r8r9r:r;r=r-r-r. wrap_socketszSSLContext.wrap_socketcCs|jj|||||||dS)N)r8r;r=r<)sslobject_classr?r6)r/incomingoutgoingr8r;r=r-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 insteadrrr1rz(NPN protocols must be 1 to 255 in length) rrr bytearraybytesrr rextend_set_npn_protocols)r/ npn_protocolsprotosr,br-r-r.set_npn_protocolss  zSSLContext.set_npn_protocolscs:dur d_dStstdfdd}|_dS)Nznot a callable objectcs|}|||SN)r6)sslobj servernamesslctxr/server_name_callbackr-r.shim_cb,s  z3SSLContext.set_servername_callback..shim_cb) sni_callbackcallable TypeError)r/rUrVr-rTr.set_servername_callback%s   z"SSLContext.set_servername_callbackcCs`t}|D]#}t|d}t|dkst|dkrtd|t|||q||dS)Nr1rrGz)ALPN protocols must be 1 to 255 in length)rHrIrr rrJ_set_alpn_protocols)r/alpn_protocolsrMr,rNr-r-r.set_alpn_protocols2s  zSSLContext.set_alpn_protocolscCstt}zt|D]\}}}|dkr|dus|j|vr||qWnty/tdYnw|r8|j|d|S)Nx509_asnTz-unable to enumerate Windows certificate store)cadata)rHrrrJPermissionErrorrrload_verify_locations)r/ storenamepurposecertsrencodingtrustr-r-r._load_windows_store_certs=s   z$SSLContext._load_windows_store_certscCs@t|ts t|tjdkr|jD]}|||q|dS)Nr)r2rrYsysplatform_windows_cert_storesrgset_default_verify_paths)r/rcrbr-r-r.load_default_certsKs    zSSLContext.load_default_certsminimum_versionc ttjSrP)rArrmr/rr-r.rmT zSSLContext.minimum_versioncs4|tjkr|jtjM_tttj||dSrP) rArIoptionsr1 OP_NO_SSLv3rr(rm__set__r/r>rr-r.rmXs crnrP)rArmaximum_versionrorr-r.ru^rpzSSLContext.maximum_versionctttj||dSrP)rr(rursrtrr-r.rubcrnrP)r1rrqrorr-r.rqfrpzSSLContext.optionscrvrP)rr(rqrsrtrr-r.rqjrwrcCs|jtj@}|tjkSrP _host_flagsrEr)r/ncsr-r-r.hostname_checks_common_nameos  z&SSLContext.hostname_checks_common_namecCs.|r |jtjM_dS|jtjO_dSrPrxrtr-r-r.r{tscCsdS)NTr-ror-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)r/innerrr-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||||||SrP)rArrTr`r]rbr)conn directionversion content_typemsg_typedatamsg_enumcallbackr-r.rs.        z'SSLContext._msg_callback..inner)rr(r}rshasattrrYr~)r/rrrrr.r}s  crnrP)r&rr,rorr-r.r,rpzSSLContext.protocolcrnrP)r9r verify_flagsrorr-r.rrpzSSLContext.verify_flagscrvrP)rr(rrsrtrr-r.rrwcs*tj}zt|WSty|YSwrP)r verify_moder;rrtrr-r.rs   zSSLContext.verify_modecrvrP)rr(rrsrtrr-r.rrwrP)FTTNN)FNN) rBrCrDr[rjr>rArr6r@rDrOrZr]rgr%r&rlrr propertyrmsetterrurqrEr{r}r,rrr$r-r-rr.r(sl            &%r()rrr_cCst|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)r2rrYr%r&r(PROTOCOL_TLS_CLIENT CERT_REQUIREDrcheck_hostnamer'PROTOCOL_TLS_SERVERrra CERT_NONErlrr r rrhflagsignore_environmentr)rcrrr_r< keylogfiler-r-r.create_default_contexts$          rF) cert_reqsrrccertfilekeyfilerrr_c 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)r2rrYr%r&rr'rrr(rrload_cert_chainrarrlrr r rrhrrr) r,rrrcrrrrr_r<rr-r-r._create_unverified_context s<          rc@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().rYrrBr/r-r.r-r-r.__init__X zSSLObject.__init__FNc Cs*||}|j||||||d}||_|S)N)r8r;ownerr=)r _wrap_bio_sslobj) rrBrCr8r;r=r<r/rQr-r-r.r?^s zSSLObject._createcC|jjS)z(The SSLContext that is currently in use.rr<ror-r-r.r<jzSSLObject.contextcC ||j_dSrPrr/ctxr-r-r.r<orpcCr)z!The SSLSession for client socket.rr=ror-r-r.r=srzSSLObject.sessioncCrrPrr/r=r-r-r.r=xrpcCr)z.Was the client session reused during handshakersession_reusedror-r-r.r|rzSSLObject.session_reusedcCr)z%Whether this is a server-side socket.)rr8ror-r-r.r8rzSSLObject.server_sidecCr)z^The currently set server hostname (for SNI), or ``None`` if no server hostname is set.)rr;ror-r-r.r;szSSLObject.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)rread)r/rbuffervr-r-r.rs  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. )rwriter/rr-r-r.rs 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 getpeercertr/ binary_formr-r-r.rs 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.rErrFN)rrrror-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.)rselected_alpn_protocolror-r-r.r z SSLObject.selected_alpn_protocolcCr)z_Return the currently selected cipher as a 3-tuple ``(name, ssl_version, secret_bits)``.)rcipherror-r-r.r zSSLObject.ciphercCr)zReturn a list of ciphers shared by the client during the handshake or None if this is not a valid server connection. )rshared_ciphersror-r-r.rrzSSLObject.shared_cipherscCr)zReturn the current compression algorithm in use, or ``None`` if compression was not negotiated or not supported by one of the peers.)r compressionror-r-r.rrzSSLObject.compressioncCr)z8Return the number of bytes that can be read immediately.)rpendingror-r-r.r zSSLObject.pendingcCs|jdS)zStart the SSL/TLS handshake.N)r do_handshakeror-r-r.rszSSLObject.do_handshakecCr)z!Start the SSL shutdown handshake.)rshutdownror-r-r.unwraprzSSLObject.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).)rget_channel_bindingr/cb_typer-r-r.rs zSSLObject.get_channel_bindingcCr)zZReturn a string identifying the protocol version used by the current SSL channel. rrror-r-r.rrzSSLObject.versioncCrrP)rverify_client_post_handshakeror-r-r.rs z&SSLObject.verify_client_post_handshake)FNNNrNFr)rBrCrDr[rr#r?rr<rr=rr8r;rrrrrrrrrrrrrrr-r-r-r.rIsF              rcCstt|jj|_|S)z*Copy docstring from SSLObject to SSLSocket)getattrrrBr[)funcr-r-r. _sslcopydocsrcs 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().rrr-r-r.rrzSSLSocket.__init__FTNc sP|tttkr td|r|rtd|durtd|jr%|s%tdt|j|j |j | d}|j |fi|} t t| jdi||} ||| _|| _d| _d| _|| _||| _|| _|| _z| Wnqty} ze| jtjkr~d} | } | dz| !d}Wnty} z| jtjtj"fvrd}WYd} ~ nd} ~ ww| | |rd }t#| j|}||_$d|_%z| &W|tyY|wWYd} ~ nd} ~ wwd } | '| | | _(| r&z(| jj)| || j| | jd | _|r| }|d kr td | *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)familytypeprotofilenoFrz5Closed before TLS handshake with data in recv buffer.Trr=zHdo_handshake_on_connect should not be specified for non-blocking socketsr-)+ getsockoptrrrNotImplementedErrorrrdictrrrrrrrr gettimeoutdetach_context_session_closedrr8r6r;r9r: getpeernamererrnoENOTCONN getblocking setblockingrecvEINVALr reasonlibraryclose settimeout _connected _wrap_socketr)rr7r8r9r:r;r<r=r.r/ sock_timeoute connectedblockingnotconn_pre_handshake_datar notconn_pre_handshake_data_errortimeoutrr-r.r?s           !    zSSLSocket._createcCs|jSrP)rror-r-r.r<RszSSLSocket.contextcCs||_||j_dSrP)rrr<rr-r-r.r<Ws cC|jdur |jjSdSrPrror-r-r.r=\ zSSLSocket.sessioncCs ||_|jdur||j_dSdSrP)rrr=rr-r-r.r=bs  cCrrPrror-r-r.rhrzSSLSocket.session_reusedcCstd|jj)NzCan't dup() %s instances)rrrBror-r-r.dupnsz SSLSocket.dupcCsdSrPr-)r/msgr-r-r. _checkClosedrr|zSSLSocket._checkClosedcCs|js |dSdSrP)rrror-r-r._check_connectedvs zSSLSocket._check_connectedrc 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)rrrrr r- SSL_ERROR_EOFr:)r/rrxr-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.)rrrrrr-r-r.rs  zSSLSocket.writecCs|||j|SrP)rrrrrr-r-r.rs zSSLSocket.getpeercertcCs|tjdtdddS)NrErrF)rrrrror-r-r.rszSSLSocket.selected_npn_protocolcCs&||jdus tjsdS|jSrP)rrrErrror-r-r.rs z SSLSocket.selected_alpn_protocolcC ||jdur dS|jSrP)rrrror-r-r.r  zSSLSocket.ciphercCrrP)rrrror-r-r.rrzSSLSocket.shared_cipherscCrrP)rrrror-r-r.rrzSSLSocket.compressionrcsB||jdur|dkrtd|j|j|St||S)Nrz3non-zero flags not allowed in calls to send() on %s)rrrrrrsend)r/rrrr-r.rs  zSSLSocket.sendcsF||jdurtd|j|durt||St|||S)Nz%sendto not allowed on instances of %s)rrrrrsendto)r/r flags_or_addrrrr-r.rs zSSLSocket.sendtocOtd|j)Nz&sendmsg not allowed on instances of %srrrr-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) rrrr memoryviewcastrrrsendall)r/rrrview byte_viewamountrrr-r.r s$ 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_sendfile_use_sendrsendfile)r/fileoffsetrrr-r.rs zSSLSocket.sendfilecs@||jdur|dkrtd|j||St||S)Nrz3non-zero flags not allowed in calls to recv() on %s)rrrrrrrr/buflenrrr-r.rs  zSSLSocket.recvcsf||r|durt|}n|durd}|jdur+|dkr%td|j|||St|||S)Nrrz8non-zero flags not allowed in calls to recv_into() on %s)rrrrrrr recv_intor/rnbytesrrr-r.r s    zSSLSocket.recv_intocs.||jdurtd|jt||S)Nz'recvfrom not allowed on instances of %s)rrrrrrecvfromrrr-r.rs  zSSLSocket.recvfromcs0||jdurtd|jt|||S)Nz,recvfrom_into not allowed on instances of %s)rrrrr recvfrom_intorrr-r.r#s  zSSLSocket.recvfrom_intocOr)Nz&recvmsg not allowed on instances of %srrr-r-r.recvmsg+zSSLSocket.recvmsgcOr)Nz+recvmsg_into not allowed on instances of %srrr-r-r. recvmsg_into/rzSSLSocket.recvmsg_intocCs ||jdur|jSdSNr)rrrror-r-r.r3s  zSSLSocket.pendingcs|d|_t|dSrP)rrrr)r/howrr-r.r;szSSLSocket.shutdowncCs*|jr |j}d|_|Stdt|NzNo SSL wrapper around )rrrr3)r/sr-r-r.r@s  zSSLSocket.unwrapcCs |jr|jStdt|r )rrrr3ror-r-r.rIs z&SSLSocket.verify_client_post_handshakecsd|_tdSrP)rr _real_closerorr-r.r"PszSSLSocket._real_closec CsN||}z|dkr|r|d|jW||dS||w)Nr)rrrrr)r/blockrr-r-r.rTs   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!FrT)r8rrrr<rr;rr connect_exconnectr9rr)r/rr$rcrr-r. _real_connect_s, zSSLSocket._real_connectcCs||ddS)QConnects to remote ADDR, and then wraps the connection in an SSL channel.FNr'r/rr-r-r.r%yszSSLSocket.connectcCs ||dS)r(Tr)r*r-r-r.r$~s 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)r9r:r8)racceptr<r@r9r:)r/newsockrrr-r.r+szSSLSocket.acceptrcCs0|jdur |j|S|tvrtd|dS)Nz({0} channel binding type not implemented)rrCHANNEL_BINDING_TYPESrrrr-r-r.rs  zSSLSocket.get_channel_bindingcCs|jdur |jSdSrPrror-r-r.rs  zSSLSocket.version)FTTNNNrPrr)r)rN)rrrr)0rBrCrDr[rr#r?rrr<rr=rrrrrrrrrrrrrrrr rrrrrrrrrrrr"rr'r%r$r+rrr$r-r-rr.rs[                           rTc Cs|tjdtdd|r|std|r|stdt|} || _|r&| ||r.| ||| r5| | | j ||||dS)Nz=ssl.wrap_socket() is deprecated, use SSLContext.wrap_socket()rrz5certfile must be specified for server-side operationsr)r7r8r9r:) rrrrr(rrar set_ciphersr@) r7rrr8r ssl_versionca_certsr9r:ciphersr<r-r-r.r@s,   r@cCsddlm}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) JanFebMarAprMayJunJulAugSepOctNovDecz %d %H:%M:%S %Y GMTNrrz*time data %r does not match format "%%b%s"rr)timer2calendarr3indextitler) cert_timer2r3months time_format month_numberttr-r-r.cert_time_to_secondss  rIz-----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-)r=ifr-r. sz(DER_cert_to_PEM_cert..rrL ) r3base64standard_b64encode PEM_HEADERrangerr PEM_FOOTERr)der_cert_bytesssr-rNr.DER_cert_to_PEM_certs " rYcCs\|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 %srJrK) r*rTrstripendswithrVrrR decodebytesr4)pem_cert_stringdr-r-r.PEM_cert_to_DER_certs r_c 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)rr)r)r;T)rr_create_stdlib_contextrr@rrY) rr/r0rhostportrr<r7sslsockdercertr-r-r.get_server_certificates&    recCs t|dS)Nz )_PROTOCOL_NAMESr) protocol_coder-r-r.get_protocol_names rhrP)or[rhr  collectionsrenumr_Enumr_IntEnumr_IntFlagrErrrr r r r r rrrrrrrrrrrrrr ImportErrorrrrrrrr r!r"r#r$r% _convert_rBr&r+r( __members__itemsrfr_SSLv2_IF_EXISTSrArTrbrrirrrrrrrrrrRrrr socket_errorr-rHAS_NEVER_CHECK_COMMON_NAME_RESTRICTED_SERVER_CIPHERSrrrrr r r rr%r(r&rrr_create_default_https_contextr`rrrr>rAr@rIrTrVrYr_rrerhr-r-r-r.sZ $ 0   )  1# > & 7<