[i+@sdZddlZddlZddlZddlZddlmZddlmZ ddl Z ddl m Z m Z m Z ddl mZddl mZmZmZmZmZmZddl mZmZmZdd l mZmZmZmZdd l mZmZdd l m Z m!Z!m"Z"m#Z#ydd l m$Z$Wne%k rZYnXd dZ&e&de&de&de&dddl m'Z'm(Z(m)Z)ddl m*Z*dde+j,DZ-yddl m.Z.e.Z/Wne%k r dZ/Yn Xde-e.e j?rd gZ@ngZ@d!ZAd"ZBGd#d$d$eCZDd%d&d'ZEd(d)ZFed*d+ZGd,d-ZHGd.d/d/ed/d0ZIGd1d2d2eIe ZJGd3d4d4eZKeJjLd5dd6dd7dd8d9ZMeNd:dd;d<d=eJjLd>dd?dd5dd6dd7dd@dAZOdBdCdDZPePdEZQeOZRGdFdGdGe5ZSddd<eeNddHdHddIdJ ZTdKdLZUdMZVdNZWdOdPZXdQdRZYeNddSdTZZdUdVZ[dS)Wa 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()) fetch_server_certificate (HOST, PORT) -- fetch the certificate provided by the server running on HOST at port PORT. No validation of the certificate is performed. 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_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)Enum)OPENSSL_VERSION_NUMBEROPENSSL_VERSION_INFOOPENSSL_VERSION) _SSLContext)SSLErrorSSLZeroReturnErrorSSLWantReadErrorSSLWantWriteErrorSSLSyscallError SSLEOFError) CERT_NONE CERT_OPTIONAL CERT_REQUIRED)VERIFY_DEFAULTVERIFY_CRL_CHECK_LEAFVERIFY_CRL_CHECK_CHAINVERIFY_X509_STRICT)txt2objnid2obj) RAND_statusRAND_add RAND_bytesRAND_pseudo_bytes)RAND_egdcCsCx<ttD].}|j|r tt|t|s r.)PROTOCOL_SSLv2ZSSLv2)PROTOCOL_TLSv1_1PROTOCOL_TLSv1_2zTLSv1.1zTLSv1.2win32)enum_certificates enum_crls)socketAF_INET SOCK_STREAMcreate_connection) SOL_SOCKETSO_TYPEz tls-uniquezECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5zECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:!eNULL:!MD5:!DSS:!RC4c@seZdZdS)CertificateErrorN)__name__ __module__ __qualname__r#r#r#r$r;s r;c CsDg}|sdS|jd^}}|jd}||krYtdt|n|su|j|jkS|dkr|jdnY|jds|jdr|jtj|n"|jtj|j ddx$|D]}|jtj|qWtj d d j |d tj }|j |S) zhMatching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 F.*z,too many wildcards in certificate DNS name: z[^.]+zxn--z\*z[^.]*z\Az\.z\Z)splitcountr;reprlowerappendrreescapereplacecompilejoin IGNORECASEmatch) ZdnhostnameZ max_wildcardsZpatsZleftmostZ remainderZ wildcardsZfragZpatr#r#r$_dnsname_matchs&  " &rOcCs[|stdng}|jdf}xC|D];\}}|dkr4t||r_dS|j|q4q4W|sxc|jdfD]L}xC|D];\}}|dkrt||rdS|j|qqWqWnt|dkrtd|d jtt|fn;t|dkrKtd ||d fn td dS) a)Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. ztempty or no certificate, match_hostname needs a SSL socket or SSL context with either CERT_OPTIONAL or CERT_REQUIREDZsubjectAltNameZDNSNZsubjectZ commonNamer?z&hostname %r doesn't match either of %sz, zhostname %r doesn't match %rrz=no appropriate commonName or subjectAltName fields were found) ValueErrorgetrOrFlenr;rKmaprD)certrNZdnsnamesZsankeyr-subr#r#r$match_hostnames.  %rWDefaultVerifyPathszQcafile capath openssl_cafile_env openssl_cafile openssl_capath_env openssl_capathcCstj}tjj|d|d}tjj|d|d}ttjj|ra|ndtjj|r||nd|S)z/Return paths to default cafile and capath. rr?N) rget_default_verify_pathsosenvironrQrXpathisfileisdir)partscafilecapathr#r#r$r[+s  r[cs^eZdZdZfZfddZefddZefddZS) _ASN1Objectz#ASN.1 object identifier lookup cstj|t|ddS)Nr,F)super__new___txt2obj)clsoid) __class__r#r$rf>sz_ASN1Object.__new__cstj|t|S)z3Create _ASN1Object from OpenSSL numeric ID )rerf_nid2obj)rhZnid)rjr#r$fromnidAsz_ASN1Object.fromnidcstj|t|ddS)z=Create _ASN1Object from short name, long name or OID r,T)rerfrg)rhr,)rjr#r$fromnameGsz_ASN1Object.fromname) r<r=r>__doc__ __slots__rf classmethodrlrmr#r#)rjr$rd9s rdznid shortname longname oidc@s"eZdZdZdZdZdS)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)r<r=r>rn SERVER_AUTH CLIENT_AUTHr#r#r#r$rqNs rqc@s|eZdZdZdZdZddZdd Zd d d d d dZddZ ddZ e j ddZ d S) SSLContextz|An SSLContext holds various SSL-related configuration options and data, such as certificates and possibly a private key.protocol __weakref__CAROOTcOs2tj||}|tkr.|jtn|S)N)rrf_SSLv2_IF_EXISTS set_ciphers_DEFAULT_CIPHERS)rhruargskwargsselfr#r#r$rf\s zSSLContext.__new__cCs ||_dS)N)ru)r~rur#r#r$__init__bszSSLContext.__init__FTNc Cs+td|d|d|d|d|d|S)Nsock server_sidedo_handshake_on_connectsuppress_ragged_eofsserver_hostname_context) SSLSocket)r~rrrrrr#r#r$ wrap_socketes zSSLContext.wrap_socketcCst}xp|D]h}t|d}t|dksIt|dkrXtdn|jt||j|qW|j|dS)Nasciirz(NPN protocols must be 1 to 255 in length) bytearraybytesrRrrFextendZ_set_npn_protocols)r~ npn_protocolsZprotosrubr#r#r$set_npn_protocolsos  $zSSLContext.set_npn_protocolscCswt}xWt|D]I\}}}|dkr|dksL|j|kr_|j|q_qqW|jd||S)NZx509_asnTcadata)rr3rirload_verify_locations)r~ storenamepurposeZcertsrTencodingZtrustr#r#r$_load_windows_store_certszs  z$SSLContext._load_windows_store_certscCsbt|tst|ntjdkrTx$|jD]}|j||q7Wn|jdS)Nr2) isinstancerd TypeErrorsysplatform_windows_cert_storesrZset_default_verify_paths)r~rrr#r#r$load_default_certss zSSLContext.load_default_certs)zprotocolz __weakref__)rwrx)r<r=r>rnrorrfrrrrrqrrrr#r#r#r$rtUs    rtrbrcrcCsBt|tst|ntt}|jtO_|jtO_|jtt ddO_|t j krt |_ d|_np|t jkr|jtt ddO_|jtt ddO_|jtt ddO_|jtn|s |s |r|j|||n|j tkr>|j|n|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. ZOP_NO_COMPRESSIONrTZOP_CIPHER_SERVER_PREFERENCEZOP_SINGLE_DH_USEZOP_SINGLE_ECDH_USE)rrdrrtPROTOCOL_SSLv23options OP_NO_SSLv2 OP_NO_SSLv3rrrqrrr verify_modecheck_hostnamersrz_RESTRICTED_SERVER_CIPHERSrrr)rrbrcrcontextr#r#r$create_default_contexts&   r cert_reqsrFrcertfilekeyfilec Cst|tst|nt|} | jtO_| jtO_|dk r`|| _n|| _|r| rt dn|s|r| j ||n|s|s|r| j |||n| jt kr| j |n| 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. Nzcertfile must be specified)rrdrrtrrrrrrPload_cert_chainrrr) rurrrrrrbrcrrr#r#r$_create_unverified_contexts"       rz%/etc/python3.4/cert-verification.confcsfdd}|S)Nc sitd6td6}ddl}y/|j}|j|jd}Wn|jk rld}YnX|j|tS)NenabledisablerZverify)rr configparserZRawConfigParserreadrQZNoSectionError)Zdefault_contextrZconfigZstatus)confrur#r$inners     z!_get_verify_status..innerr#)rurrr#)rrur$_get_verify_statuss rZhttpsc@s eZdZdZddddeeddeedddddddddZe dd Z e j d d Z d d Z dd dZ ddZddddZddZdddZddZddZddZdddZddd Zd!d"Zdd#d$Zd%dd&d'Zddd(d)Zd%dd*d+Zddd,d-Zd.d/Zd0d1Zd2d3Zd4d5Z d6d7Z!d8d9Z"dd:d;Z#d<d=Z$d>d?Z%d@dAZ&dBdCZ'dDdEdFZ(dS)GrzThis 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.NFTrcCsD|r||_n|r.| r.tdn|rJ| rJtdn|r`| r`|}nt||_||j_|r|jj|n|r|jj||n|r|jj|n|r|jj|n||_||_ ||_ ||_ ||_ ||_ |jtttkr?tdn|rZ|rZtdn|jjr|| r|tdn||_||_||_| |_|dk rtj|d|jd|jd|jd |j|j|j|j nA| dk r"tj|d | ntj|d| d| d| y|j!WnCt"k r}z#|j#t#j$kr|nd }WYdd}~XnXd }d |_%d|_&||_'|r@yY|jj(||||_&|r|j}|d krtd n|j)nWq@t"tfk r<|j*Yq@XndS)Nz5certfile must be specified for server-side operationszcertfile must be specifiedz!only stream sockets are supportedz4server_hostname can only be specified in client modez'check_hostname requires server_hostnamefamilytypeprotofilenoFTgzHdo_handshake_on_connect should not be specified for non-blocking sockets)+rrPrtrrrrrzrrr ssl_versionca_certsciphersZ getsockoptr9r:r7NotImplementedErrorrrrrrr5rrrrr settimeout gettimeoutdetach getpeernameOSErrorerrnoZENOTCONNZ_closed_sslobj _connected _wrap_socket do_handshakeclose)r~rrrrrrrrrrrrrrrrreZ connectedtimeoutr#r#r$rs                                 zSSLSocket.__init__cCs|jS)N)r)r~r#r#r$r_szSSLSocket.contextcCs||_||j_dS)N)rrr)r~Zctxr#r#r$rcs cCstd|jjdS)NzCan't dup() %s instances)NotImplementedrjr<)r~r#r#r$duphsz SSLSocket.dupcCsdS)Nr#)r~msgr#r#r$ _checkClosedlszSSLSocket._checkClosedcCs|js|jndS)N)rr)r~r#r#r$_check_connectedps zSSLSocket._check_connectedcCs|j|js"tdnyD|dk rI|jj||}n|jj|p[d}|SWn[tk r}z;|jdtkr|jr|dk rdSdSnWYdd}~XnXdS)zORead up to LEN bytes and return them. Return zero-length string on EOF.z'Read on closed or unwrapped SSL socket.Nir)rrrPrrr|Z SSL_ERROR_EOFr)r~rRbuffervxr#r#r$rxs    zSSLSocket.readcCs2|j|js"tdn|jj|S)zhWrite DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted.z(Write on closed or unwrapped SSL socket.)rrrPwrite)r~datar#r#r$rs  zSSLSocket.writecCs$|j|j|jj|S)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.)rrrZpeer_certificate)r~Z binary_formr#r#r$ getpeercerts  zSSLSocket.getpeercertcCs3|j|j stj r"dS|jjSdS)N)rrrr)selected_npn_protocol)r~r#r#r$rs zSSLSocket.selected_npn_protocolcCs(|j|jsdS|jjSdS)N)rrcipher)r~r#r#r$rs  zSSLSocket.ciphercCs(|j|jsdS|jjSdS)N)rr compression)r~r#r#r$rs  zSSLSocket.compressioncCs|j|jr|dkr5td|jny|jj|}WnVtk r}z6|jdtkrwdS|jdtkrdSWYdd}~XqX|Snt j |||SdS)Nrz3non-zero flags not allowed in calls to send() on %s) rrrPrjrrr|ZSSL_ERROR_WANT_READZSSL_ERROR_WANT_WRITEr5send)r~rflagsrrr#r#r$rs    zSSLSocket.sendcCsb|j|jr)td|jn5|dkrHtj|||Stj||||SdS)Nz%sendto not allowed on instances of %s)rrrPrjr5sendto)r~rZ flags_or_addraddrr#r#r$rs   zSSLSocket.sendtocOstd|jdS)Nz&sendmsg not allowed on instances of %s)rrj)r~r|r}r#r#r$sendmsgszSSLSocket.sendmsgcCs|j|jr|dkr5td|jnt|}d}x3||kr||j||d}||7}qJW|Stj|||SdS)Nrz6non-zero flags not allowed in calls to sendall() on %s)rrrPrjrRrr5sendall)r~rrZamountrCrr#r#r$rs    zSSLSocket.sendallicCsY|j|jrB|dkr5td|jn|j|Stj|||SdS)Nrz3non-zero flags not allowed in calls to recv() on %s)rrrPrjrr5recv)r~buflenrr#r#r$rs    zSSLSocket.recvcCs|j|r+|dkr+t|}n|dkr@d}n|jr{|dkrktd|jn|j||Stj||||SdS)Nirz8non-zero flags not allowed in calls to recv_into() on %s)rrRrrPrjrr5 recv_into)r~rnbytesrr#r#r$rs     zSSLSocket.recv_intocCs@|j|jr)td|jntj|||SdS)Nz'recvfrom not allowed on instances of %s)rrrPrjr5recvfrom)r~rrr#r#r$rs   zSSLSocket.recvfromcCsC|j|jr)td|jntj||||SdS)Nz,recvfrom_into not allowed on instances of %s)rrrPrjr5 recvfrom_into)r~rrrr#r#r$r s   zSSLSocket.recvfrom_intocOstd|jdS)Nz&recvmsg not allowed on instances of %s)rrj)r~r|r}r#r#r$recvmsgszSSLSocket.recvmsgcOstd|jdS)Nz+recvmsg_into not allowed on instances of %s)rrj)r~r|r}r#r#r$ recvmsg_intoszSSLSocket.recvmsg_intocCs(|j|jr |jjSdSdS)Nr)rrpending)r~r#r#r$rs   zSSLSocket.pendingcCs'|jd|_tj||dS)N)rrr5shutdown)r~Zhowr#r#r$r$s  zSSLSocket.shutdowncCs?|jr%|jj}d|_|Stdt|dS)NzNo SSL wrapper around )rrrPstr)r~sr#r#r$unwrap)s   zSSLSocket.unwrapcCsd|_tj|dS)N)rr5 _real_close)r~r#r#r$r1s zSSLSocket._real_closec Cs|j|j}z3|dkr;|r;|jdn|jjWd|j|X|jjr|js~tdnt |j |jndS)zPerform a TLS/SSL handshake.gNz-check_hostname needs server_hostname argument) rrrrrrrrrPrWr)r~blockrr#r#r$r5s    zSSLSocket.do_handshakec Cs|jrtdn|jr0tdn|jj|d|j|_ya|rltj||}nd}tj |||sd|_|j r|j qn|SWn$t tfk rd|_YnXdS)Nz!can't connect in server-side modez/attempt to connect already-connected SSLSocket!FT) rrPrrrrrr5 connect_exconnectrrr)r~rrZrcr#r#r$ _real_connectFs$     zSSLSocket._real_connectcCs|j|ddS)zQConnects to remote ADDR, and then wraps the connection in an SSL channel.FN)r)r~rr#r#r$r]szSSLSocket.connectcCs|j|dS)zQConnects to remote ADDR, and then wraps the connection in an SSL channel.T)r)r~rr#r#r$rbszSSLSocket.connect_excCsItj|\}}|jj|d|jd|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.rrrT)r5acceptrrrr)r~Znewsockrr#r#r$rgs    zSSLSocket.acceptz tls-uniquecCs_|tkrtdn|dkr?tdj|n|jdkrRdS|jjS)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). z Unsupported channel binding typez tls-uniquez({0} channel binding type not implementedN)CHANNEL_BINDING_TYPESrPrformatrZ tls_unique_cb)r~Zcb_typer#r#r$get_channel_bindingss  zSSLSocket.get_channel_binding))r<r=r>rnrrr6r7rpropertyrsetterrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr#r#r#r$rsP    S                  rTc CsCtd|d|d|d|d|d|d|d|d |d | S) Nrrrrrrrrrr)r) rrrrrrrrrrr#r#r$rs   rcCs%ddl}|j|j|dS)zTakes a date-time string in standard ASN1_print form ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return a Python time value in seconds past the epoch.rNz%b %d %H:%M:%S %Y GMT)timeZmktimeZstrptime)Z cert_timerr#r#r$cert_time_to_secondss rz-----BEGIN CERTIFICATE-----z-----END CERTIFICATE-----cCs?ttj|dd}tdtj|ddtdS)z[Takes a certificate in binary DER format and returns the PEM version of it as a string.ASCIIstrict @)rbase64Zstandard_b64encode PEM_HEADERtextwrapZfill PEM_FOOTER)Zder_cert_bytesfr#r#r$DER_cert_to_PEM_certsrcCs|jts"tdtn|jjtsJtdtn|jtttt }tj|j 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) rrrPstripendswithrrRrZ decodebytesencode)Zpem_cert_stringdr#r#r$PEM_cert_to_DER_certs  #rc Cs|\}}|dk r!t}nt}t|d|d|}t|.}|j|}|jd} WdQXWdQXt| 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.NrrbT)rr_create_stdlib_contextr8rrr) rrrZhostZportrrrZsslsockZdercertr#r#r$get_server_certificates     rcCstj|dS)Nz )_PROTOCOL_NAMESrQ)Z protocol_coder#r#r$get_protocol_namesr)\rnrrGrr\ collectionsrZenumrZ_Enumrrrrrrr r r r r rrrrrrrrrgrrkrrrrr ImportErrorr%r'r(r)r*r itemsrr/ryr0r1rr3r4r5r6r7r8r9r:rrrZ socket_errorZHAS_TLS_UNIQUErr{rrPr;rOrWrXr[rdrqrtrrrrrrZ_create_default_https_contextrrrrrrrrrrr#r#r#r$Xs     .""             "    1 +  8/  '