B \] @sdZddlZddlZddlmZddlmZmZ m Z ddl Z ddl m Z mZmZddl mZmZmZddl mZmZmZmZmZmZmZddl mZmZdd l mZmZm Z m!Z!ydd l m"Z"Wne#k rYnXdd 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:ej;d krdd!l mm>Z>m?Z?m@Z@mAZAdd#l>mBZBmCZCddl>ZDddlEZEddlFZFddlGZGeHZId$gZJeKe d%ZLe.ZMeZNd&d'ZOd(d)ZPd*d+ZQd,d-ZRed.d/ZSd0d1ZTGd2d3d3ed3d4ZUGd5d6d6eUeZVGd7d8d8eZWeVjXfdddd9d:d;ZYe3feZdd?Z[eYZ\e[Z]Gd@dAdAZ^dBdCZ_GdDdEdEe>Z`e`eW_ae^eW_bddd|r,)sourceOptionscCs |dS)NZOP_)r()r)r*r*r+r,r-ZAlertDescriptioncCs |dS)NZALERT_DESCRIPTION_)r()r)r*r*r+r,r-ZSSLErrorNumbercCs |dS)NZ SSL_ERROR_)r()r)r*r*r+r,r- VerifyFlagscCs |dS)NZVERIFY_)r()r)r*r*r+r,r- VerifyModecCs |dS)NZCERT_)r()r)r*r*r+r,r-cCsi|]\}}||qSr*r*).0r)valuer*r*r+ sr4ZPROTOCOL_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+r5sr5win32)enum_certificates enum_crls)socketAF_INET SOCK_STREAMcreate_connection) SOL_SOCKETSO_TYPEz tls-uniqueHOSTFLAG_NEVER_CHECK_SUBJECTcCs|sdS|d}|s&||kS|dkrsole wildcard without additional labels are not support: {!r}.z      rfDefaultVerifyPathszQcafile capath openssl_cafile_env openssl_cafile openssl_capath_env openssl_capathcCsdt}tj|d|d}tj|d|d}ttj|rF|ndtj|rX|ndf|S)z/Return paths to default cafile and capath. rrFN) r9get_default_verify_pathsosenvironr]rgpathisfileisdir)partscafilecapathr*r*r+rj\s rjcsDeZdZdZdZfddZefddZefddZZ S) _ASN1Objectz#ASN.1 object identifier lookup r*cstj|ft|ddS)NF)r))super__new___txt2obj)clsoid) __class__r*r+ruosz_ASN1Object.__new__cstj|ft|S)z3Create _ASN1Object from OpenSSL numeric ID )rtru_nid2obj)rwZnid)ryr*r+fromnidrsz_ASN1Object.fromnidcstj|ft|ddS)z=Create _ASN1Object from short name, long name or OID T)r))rtrurv)rwr))ryr*r+fromnamexsz_ASN1Object.fromname) r6r7r8__doc__ __slots__ru classmethodr{r| __classcell__r*r*)ryr+rsjs  rsznid 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)r6r7r8r} SERVER_AUTHZ CLIENT_AUTHr*r*r*r+rsrcsneZdZdZdZdZdZefddZddZ d/d d Z d0d d Z ddZ ddZ ddZddZejfddZeedrefddZejfddZefddZejfddZefdd Zejfd!d Zeed"red#d$Zejd%d$Zn ed&d$Zefd'd(Zefd)d*Zejfd+d*Zefd,d-Zejfd.d-ZZS)1 SSLContextz|An SSLContext holds various SSL-related configuration options and data, such as certificates and possibly a private key.)ZCAZROOTNcOst||}|S)N)r ru)rwprotocolargskwargsselfr*r*r+rus zSSLContext.__new__cCs4|dkr dSt|tr&|ddS|dSdS)NZidnaascii) isinstancestrencodedecode)rrMr*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_bioszSSLContext.wrap_biocCsdt}xN|D]F}t|d}t|dks2t|dkr:td|t|||q W||dS)Nrrz(NPN protocols must be 1 to 255 in length) bytearraybytesr_r r^extendZ_set_npn_protocols)rZ npn_protocolsprotosrbr*r*r+set_npn_protocolss  zSSLContext.set_npn_protocolscs8dkrd_n$ts tdfdd}|_dS)Nznot a callable objectcs|}|||S)N)r)sslobjZ servernameZsslctx)rserver_name_callbackr*r+shim_cbs z3SSLContext.set_servername_callback..shim_cb)Z sni_callbackcallable TypeError)rrrr*)rrr+set_servername_callbacks z"SSLContext.set_servername_callbackcCsdt}xN|D]F}t|d}t|dks2t|dkr:td|t|||q W||dS)Nrrrz)ALPN protocols must be 1 to 255 in length)rrr_r r^rZ_set_alpn_protocols)rZalpn_protocolsrrrr*r*r+set_alpn_protocolss  zSSLContext.set_alpn_protocolscCszt}y@x:t|D].\}}}|dkr|dks6|j|kr||qWWntk rdtdYnX|rv|j|d|S)NZx509_asnTz-unable to enumerate Windows certificate store)cadata)rr<rxrPermissionErrorwarningswarnload_verify_locations)r storenamepurposeZcertsrcencodingZtrustr*r*r+_load_windows_store_certss z$SSLContext._load_windows_store_certscCsDt|tst|tjdkr8x|jD]}|||q$W|dS)Nr;)rrsrsysplatform_windows_cert_storesrZset_default_verify_paths)rrrr*r*r+load_default_certss    zSSLContext.load_default_certsminimum_versioncs ttjS)N)r5rtr)r)ryr*r+rszSSLContext.minimum_versioncs4|tjkr|jtjM_tttj||dS)N) r5r:optionsr/Z OP_NO_SSLv3rtrr__set__)rr3)ryr*r+rs cs ttjS)N)r5rtmaximum_version)r)ryr*r+rszSSLContext.maximum_versioncstttj||dS)N)rtrrr)rr3)ryr*r+rscs ttjS)N)r/rtr)r)ryr*r+rszSSLContext.optionscstttj||dS)N)rtrrr)rr3)ryr*r+rsrDcCs|jtj@}|tjkS)N) _host_flagsr9rD)rZncsr*r*r+hostname_checks_common_name s z&SSLContext.hostname_checks_common_namecCs,|r|jtjM_n|jtjO_dS)N)rr9rD)rr3r*r*r+rscCsdS)NTr*)rr*r*r+rscs ttjS)N)r&rtr)r)ryr*r+rszSSLContext.protocolcs ttjS)N)r0rt verify_flags)r)ryr*r+rszSSLContext.verify_flagscstttj||dS)N)rtrrr)rr3)ryr*r+r!scs*tj}yt|Stk r$|SXdS)N)rt verify_moder1rT)rr3)ryr*r+r%s zSSLContext.verify_modecstttj||dS)N)rtrrr)rr3)ryr*r+r-s)FTTNN)FNN) r6r7r8r}rrr PROTOCOL_TLSrurrrrrrrrrrhasattrr propertyrsetterrrr9rrrrrr*r*)ryr+rsB          r)rqrrrcCsdt|tst|tt}|tjkr0t|_d|_ |s<|s<|rL| |||n|jt kr`| ||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. T) rrsrrrrr CERT_REQUIREDrcheck_hostnamer CERT_NONEr)rrqrrrrr*r*r+create_default_context2s     rF) cert_reqsrrcertfilekeyfilerqrrrc Cst|tst|t|} |s$d| _|dk r2|| _|rZ"ed?d@Z#fdAdBZ$edCdDZ%edEdFZ&fdGdHZ'edddIdJZ(fdKdLZ)dMdNZ*dOdPZ+fdQdRZ,ededTdUZ-edVdWZ.Z/S)f 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. cOst|jjddS)NzX does not have a public constructor. Instances are returned by SSLContext.wrap_socket().)rryr6)rrrr*r*r+r&szSSLSocket.__init__FTNc s|tttkrtd|r8|r(td|dk r8td|jrJ|sJtdt|j|j |j | d}|j |f|} t t| jf|| |||| _|| _d| _d| _|| _||| _|| _|| _y | Wn6tk r} z| jtjkrd} Wdd} ~ XYnXd} | | _ | ryH| jj!| || j| | jd| _|rj| } | d krbtd | "Wn$ttfk r| #YnX| 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)familytypeprotofilenoFT)rrgzHdo_handshake_on_connect should not be specified for non-blocking sockets)$ getsockoptrBrCr@NotImplementedErrorrTrdictrrrrrurtrr settimeout gettimeoutdetach_context_session_closedrrrrrr getpeernamerRerrnoZENOTCONN _connected _wrap_socketrclose) rwrrrrrrrrreZ connectedtimeout)ryr*r+r-s\        zSSLSocket._createcCs|jS)N)r)rr*r*r+rlszSSLSocket.contextcCs||_||j_dS)N)rrr)rrr*r*r+rqscCs|jdk r|jjSdS)N)rr)rr*r*r+rvs zSSLSocket.sessioncCs||_|jdk r||j_dS)N)rrr)rrr*r*r+r|s cCs|jdk r|jjSdS)N)rr)rr*r*r+rs zSSLSocket.session_reusedcCstd|jjdS)NzCan't dup() %s instances)rryr6)rr*r*r+dupsz SSLSocket.dupcCsdS)Nr*)rmsgr*r*r+ _checkClosedszSSLSocket._checkClosedcCs|js|dS)N)rr)rr*r*r+_check_connectedszSSLSocket._check_connectedc Cs||jdkrtdy&|dk r2|j||S|j|SWnJtk r}z,|jdtkrx|jrx|dk rrdSdSnWdd}~XYnXdS)zORead up to LEN bytes and return them. Return zero-length string on EOF.Nz'Read on closed or unwrapped SSL socket.rr-)rrrTrr rZ SSL_ERROR_EOFr)rr_rxr*r*r+rs zSSLSocket.readcCs&||jdkrtd|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.)rrrTr)rrr*r*r+rs zSSLSocket.writecCs|||j|S)N)rrrr)rrr*r*r+rszSSLSocket.getpeercertcCs*||jdkstjsdS|jSdS)N)rrr9rr)rr*r*r+rszSSLSocket.selected_npn_protocolcCs*||jdkstjsdS|jSdS)N)rrr9rr)rr*r*r+rsz SSLSocket.selected_alpn_protocolcCs$||jdkrdS|jSdS)N)rrr)rr*r*r+rs zSSLSocket.ciphercCs$||jdkrdS|jSdS)N)rrr)rr*r*r+rs zSSLSocket.shared_cipherscCs$||jdkrdS|jSdS)N)rrr)rr*r*r+rs zSSLSocket.compressionrcsF||jdk r4|dkr(td|j|j|St||SdS)Nrz3non-zero flags not allowed in calls to send() on %s)rrrTryrrtsend)rrflags)ryr*r+rs   zSSLSocket.sendcsL||jdk r"td|jn&|dkr8t||St|||SdS)Nz%sendto not allowed on instances of %s)rrrTryrtsendto)rrZ flags_or_addrrX)ryr*r+rs  zSSLSocket.sendtocOstd|jdS)Nz&sendmsg not allowed on instances of %s)rry)rrrr*r*r+sendmsgszSSLSocket.sendmsgc s||jdk r|dkr(td|jd}t|L}|d6}t|}x&||krp|||d}||7}qLWWdQRXWdQRXnt ||SdS)Nrz6non-zero flags not allowed in calls to sendall() on %sB) rrrTry memoryviewcastr_rrtsendall)rrrrHZviewZ byte_viewamountr)ryr*r+r s   "zSSLSocket.sendallcs,|jdk r||||St|||SdS)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_sendrtsendfile)rfileoffsetrH)ryr*r+rs zSSLSocket.sendfilecsD||jdk r2|dkr(td|j||St||SdS)Nrz3non-zero flags not allowed in calls to recv() on %s)rrrTryrrtrecv)rbuflenr)ryr*r+rs   zSSLSocket.recvcsj||r|dkrt|}n |dkr*d}|jdk rV|dkrJtd|j|||St|||SdS)Nirz8non-zero flags not allowed in calls to recv_into() on %s)rr_rrTryrrt recv_into)rrnbytesr)ryr*r+r$s     zSSLSocket.recv_intocs4||jdk r"td|jnt||SdS)Nz'recvfrom not allowed on instances of %s)rrrTryrtrecvfrom)rrr)ryr*r+r3s   zSSLSocket.recvfromcs6||jdk r"td|jnt|||SdS)Nz,recvfrom_into not allowed on instances of %s)rrrTryrt recvfrom_into)rrrr)ryr*r+r;s   zSSLSocket.recvfrom_intocOstd|jdS)Nz&recvmsg not allowed on instances of %s)rry)rrrr*r*r+recvmsgCszSSLSocket.recvmsgcOstd|jdS)Nz+recvmsg_into not allowed on instances of %s)rry)rrrr*r*r+ recvmsg_intoGszSSLSocket.recvmsg_intocCs$||jdk r|jSdSdS)Nr)rrr)rr*r*r+rKs  zSSLSocket.pendingcs|d|_t|dS)N)rrrtr)rZhow)ryr*r+rSszSSLSocket.shutdowncCs.|jr|j}d|_|Stdt|dS)NzNo SSL wrapper around )rrrTr)rsr*r*r+rXs  zSSLSocket.unwrapcCs$|jr|jStdt|dS)NzNo SSL wrapper around )rrrTr)rr*r*r+ras z&SSLSocket.verify_client_post_handshakecsd|_tdS)N)rrt _real_close)r)ryr*r+rhszSSLSocket._real_closec CsF||}z$|dkr(|r(|d|jWd||XdS)Ng)rrrrr)rblockrr*r*r+rls  zSSLSocket.do_handshakec s|jrtd|js|jdk r&td|jj|d|j||jd|_y>|rVt |}nd}t ||s~d|_|j r~| |St tfk rd|_YnXdS)Nz!can't connect in server-side modez/attempt to connect already-connected SSLSocket!F)rrT)rrTrrrrrrrt connect_exconnectrrrR)rrXrrc)ryr*r+ _real_connectws( zSSLSocket._real_connectcCs||ddS)zQConnects to remote ADDR, and then wraps the connection in an SSL channel.FN)r!)rrXr*r*r+rszSSLSocket.connectcCs ||dS)zQConnects to remote ADDR, and then wraps the connection in an SSL channel.T)r!)rrXr*r*r+rszSSLSocket.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)rtacceptrrrr)rZnewsockrX)ryr*r+r"s zSSLSocket.accept tls-uniquecCs4|jdk r|j|S|tkr,td|dSdS)Nz({0} channel binding type not implemented)rrCHANNEL_BINDING_TYPESrTrK)rrr*r*r+rs    zSSLSocket.get_channel_bindingcCs|jdk r|jSdSdS)N)rr)rr*r*r+rs  zSSLSocket.version)FTTNNN)N)rN)F)r)N)r)rN)rr)Nr)rr)Nr)F)r#)0r6r7r8r}rrrrrrrrrrrrrrrrrrrrrrr r rrrrrrrrrrrrrr!rrr"rrrr*r*)ryr+r!sf<                    rTc Csl|r|std|r |s tdt|} || _|r<| ||rL| ||| rZ| | | j||||dS)Nz5certfile must be specified for server-side operationszcertfile must be specified)rrrr)rTrrrrZ set_ciphersr) rrrrr ssl_versionca_certsrrZciphersrr*r*r+rs    rcCsddlm}ddlm}d}d}y||ddd}Wn$tk rbtd ||fYn0X||dd|}||d|f|d d SdS) 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 GMTNrirFz*time data %r does not match format "%%b%s"rh)timer'Zcalendarr(indextitlerT)Z cert_timer'r(ZmonthsZ time_formatZ month_numberttr*r*r+cert_time_to_secondss  r.z-----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*)r2i)fr*r+ sz(DER_cert_to_PEM_cert..rr1 ) rbase64Zstandard_b64encode PEM_HEADERranger_r^ PEM_FOOTERr`)Zder_cert_bytesssr*)r3r+DER_cert_to_PEM_certs "r;cCs\|tstdt|ts0tdt|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 %sr/r0) r(r7rTstripendswithr9r_r6Z decodebytesr)Zpem_cert_stringdr*r*r+PEM_cert_to_DER_certs r?c Csd|\}}|dk rt}nt}t|||d}t|&}||}|d} WdQRXWdQRXt| S)zRetrieve 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.N)rrqT)rr_create_stdlib_contextrArrr;) rXr%r&hostportrrrZsslsockZdercertr*r*r+get_server_certificates  rCcCs t|dS)Nz )_PROTOCOL_NAMESr])Z protocol_coder*r*r+get_protocol_name&srE)kr}rrk collectionsrenumrZ_EnumrZ_IntEnumrZ_IntFlagr9rrrr r r r r rrrrrrrvrrzrrrrr ImportErrorrrrrrrr r!r"r#r$r%_convertr6r&rr' __members__itemsrDrZ_SSLv2_IF_EXISTSr5rr<r=r>r?r@rArBrCrPr6rrrRZ socket_errorr$rZHAS_NEVER_CHECK_COMMON_NAMEZ_RESTRICTED_SERVER_CIPHERSrJrOrYr\rfrgrjrsrrrrrrZ_create_default_https_contextr@rrrrrrr.r7r9r;r?rCrEr*r*r*r+[s $0    1# 9-(