o ^Ub%@s\ddlmZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl mZmZm Z mZddlmZmZmZhd Ze ed d ZeZe ed eed r^ede edeedrmede edeedr|edddZddZd)ddZ d*ddZGdddeZ d+dd Z!d!d"Z"d#d$Z#d%d&Z$d'd(Z%dS),)absolute_importN)_)getattr)hex)encodingerrorpycompatutil)hashutil resourceutil stringutil>tls1.0tls1.1tls1.2HAS_SNIF HAS_TLSv1PROTOCOL_TLSv1r HAS_TLSv1_1PROTOCOL_TLSv1_1r HAS_TLSv1_2PROTOCOL_TLSv1_2rc Cst|}dgddddddd}dd}tdhsJd}d }|d ||}|||d |}|d ||}||||d d }|d d ||}|jrSd}|sSd}||d <||d <|d d|} | D]/} | ds{tjt d|| ft dd| dd\} } | dd } |d | | fqe|d|D]} | dd } |d d| fd|d<q|drtj|d<d|d<n|jrd|d<tj|d<d|d<|ddrd|d<|d d |} |dr| r|t d!||ddurj| rt| } tj| stt d"d#|f| f| |d$<n<|d%d&} | r@t| } tj| s?tt d'| t d(d)n|drSt|} | rS|d*| | |d$<| s_|dretj|d<ntj|d<|ddussJ|S)+zhObtain security settings for a hostname. Returns a dict of settings relevant to that hostname. TNF)allowloaddefaultcertscertfingerprintscafiledisablecertverificationlegacyfingerprintminimumprotocol verifymodecipherscSs8|tvrtjtd||ftddttddS)Ns-unsupported protocol from hostsecurity.%s: %ssvalid protocols: %s hint)configprotocolsrAbortrjoinsorted)protocolkeyr)3/usr/lib/python3/dist-packages/mercurial/sslutil.pyvalidateprotocol[s z'_hostsettings..validateprotocolrrr hostsecuritys%s:minimumprotocolrs %s:cipherssDEFAULTs%s:fingerprints)ssha1:ssha256:ssha512:sinvalid fingerprint for %s: %ss0must begin with "sha1:", "sha256:", or "sha512:"r!:rrshostfingerprintssha1rrrrdevelsdisableloaddefaultcertss%s:verifycertsfiless(hostsecurity.%s:verifycertsfile ignored when host fingerprints defined; using host fingerprints for verification) s'path specified by %s does not exist: %sshostsecurity.%s:verifycertsfilerswebscacertsscould not find web.cacerts: %ss (try installing the %s package)sca-certificatessusing %s for CA file )r bytesurlsupportedprotocolsconfiginsecureconnections configlist startswithrr$rsplitreplacelowerappendssl CERT_NONE configboolwarnr expandpathospathexists_defaultcacertsdebug CERT_REQUIRED) uihostname bhostnamesr+defaultminimumprotocolr(minimumprotocolciphers fingerprints fingerprintalgcafiler)r)r* _hostsettings>s                     rQcCsz|tvr td|tjtjB}|dkrn|dkr|tjO}n|dkr,|tjtjBO}ntt d|t tddO}|S)z8Return SSLContext options common to servers and clients.s protocol value not supported: %srrrthis should not happenOP_NO_COMPRESSIONr) r# ValueErrorr; OP_NO_SSLv2 OP_NO_SSLv3 OP_NO_TLSv1 OP_NO_TLSv1_1rr$rr)rKoptionsr)r)r*commonssloptionss   rZc s|s ttddtjvr3zddl}|ttjd dWnt y2 dYnwfD]}|rSt j |sStjtd|t|ftdd q7t|}ttd rttj}|d } | d krttd dttjj|_Wdn1swYn6| dkrttd dttjj|_Wdn1swYn| dkrtjj|_nttd|jttddO_nttj }|jt!|d O_d|_"|d|_#|dr z |$t%|dWn%tj&y} ztjtdt'(| j)dtd|dd d} ~ wwdur4fdd} |*| |ddur~z |j+|ddWn5tj&yz} z't,| j)dkr]| j)d} n| j)d} tjtd|dt'(| ftdd d} ~ wwd } n|d!r|-d } nd} z |j.||d"}Wntj&y9} zz| r|dtj/kr|0s1td#Wn tj&yYnwt| d$r4| j2d%vr#|d d krt3d hkr1td&t|d'4t5t3f1td(t|1td)|d t|f1td*t|1td+| j2d,kr4tj6r41td-d} ~ ww|7sFt8td.| ||d/|_9|S)0aAdd SSL/TLS to a socket. This is a glorified wrapper for ``ssl.wrap_socket()``. It makes sane choices based on what security options are available. In addition to the arguments supported by ``ssl.wrap_socket``, we allow the following additional arguments: * serverhostname - The expected hostname of the remote server. If the server (and client) support SNI, this tells the server which certificate to use. s#serverhostname argument is requireds SSLKEYLOGFILErNs8sslkeylog enabled by SSLKEYLOGFILE environment variable s?sslkeylog module missing, but SSLKEYLOGFILE set in environment s:certificate file (%s) does not exist; cannot connect to %ss:restore missing file or fix references in Mercurial configr!PROTOCOL_TLS_CLIENTrrignore"ssl.TLSVersion.TLSv1 is deprecatedr$ssl.TLSVersion.TLSv1_1 is deprecatedrrRrSFrrscould not set ciphers: %ss#change cipher string (%s) in configcsp}td|dS)Nspassphrase for %s: r.)getpassr)fcertfilekeyfilerFr)r*passwordiszwrapsocket..passwordrrPrserror loading CA file %s: %ssfile is empty or malformed?Tr)server_hostnames(an attempt was made to load CA certificates but none were loaded; see https://mercurial-scm.org/wiki/SecureConnections for how to configure Mercurial to avoid this error) sreason)UNSUPPORTED_PROTOCOLTLSV1_ALERT_PROTOCOL_VERSIONs(could not communicate with %s using security protocols %s; if you are using a modern Mercurial version, consider contacting the operator of this server; see https://mercurial-scm.org/wiki/SecureConnections for more info) , s(could not communicate with %s using TLS 1.0; the likely cause of this is the server no longer supports TLS 1.0 because it has known security vulnerabilities; see https://mercurial-scm.org/wiki/SecureConnections for more info) s(could not negotiate a common security protocol (%s+) with %s; the likely cause is Mercurial is configured to be more secure than the server can support) s(consider contacting the operator of this server and ask them to support modern TLS protocol versions; or, set hostsecurity.%s:minimumprotocol=tls1.0 to allow use of legacy, less secure protocols when communicating with this server) sE(see https://mercurial-scm.org/wiki/SecureConnections for more info) CERTIFICATE_VERIFY_FAILEDsR(the full certificate chain may not be available locally; see "hg help debugssl") sssl connection failed)caloadedhostnamesettingsui):rr$rrenviron sslkeylog set_keylogr fsdecode warnnoi18n ImportErrorr@rArBr1rQr safehasattrr; SSLContextr[warningscatch_warningsfilterwarningsDeprecationWarning TLSVersionTLSv1minimum_versionTLSv1_1TLSv1_2rYrPROTOCOL_SSLv23rZcheck_hostname verify_mode set_cipherssysstrSSLErrorr forcebytestrargsload_cert_chainload_verify_locationslenload_default_certs wrap_socketrE get_ca_certsr>reasonr2r%r& iswindowscipher SecurityError_hgstate)sockrcrbrFserverhostnamerpr`settings sslcontextrKerdmsgcaloaded sslsocketr)rar* wrapsocketsN                      D5   src Cs |||fD]}|rtj|sttd|qttdrt tj }|j t tddO_ | dd}|dkrkdtvrEttdttd d ttjj|_tjj|_Wd n1sewYn|d krd tvrzttd ttd dttjj|_tjj|_Wd n1swYn|dkrdtvrttdtjj|_tjj|_nl|rttd|n`tj} td} | dd}|dkrdtvrttdtj} n4|d krd tvrttd tj} n!|dkrdtvr ttdtj} n |rttd|t | }|j | O_ |j t tddO_ |j t tddO_ |rE|dnttdr]|j t tddO_ |tj|retj |_!ntj"|_!|so|rv|j#||d|r|j$|d|j%|ddS)aWrap a socket for use by servers. ``certfile`` and ``keyfile`` specify the files containing the certificate's public and private keys, respectively. Both keys can be defined in the same file via ``certfile`` (the private key must come first in the file). ``cafile`` defines the path to certificate authorities. ``requireclientcert`` specifies whether to require client certificates. Typically ``cafile`` is only defined if ``requireclientcert`` is true. s/referenced certificate file (%s) does not existPROTOCOL_TLS_SERVERrSrr0sserverexactprotocolrs$TLS 1.0 not supported by this Pythonr\r]Nrs$TLS 1.1 not supported by this Pythonr^rs$TLS 1.2 not supported by this Pythons)invalid value for serverexactprotocol: %sOP_SINGLE_DH_USEOP_SINGLE_ECDH_USEDEFAULTs_RESTRICTED_SERVER_CIPHERSOP_CIPHER_SERVER_PREFERENCE)rbrcreT) server_side)&r@rArBrr$rr rur;rvrrYrr3r2rwrxryrzr{r|r}maximum_versionr~rrrZrrrr_RESTRICTED_SERVER_CIPHERSrErr<rrr) rrFrbrcrPrequireclientcertr`r exactprotocolr'rYr)r)r*wrapserversockets                       rc@seZdZdZdS) wildcarderrorz2Represents an error parsing wildcards in DNS name.N)__name__ __module__ __qualname____doc__r)r)r)r*rysrc Cs g}|sdSt|}t|}|d}|d}|dd}|d}||kr0ttd||s:||kS|dkrD|dn|d sN|d rW|t |n |t | d d |D] }|t |qet d d |dt j} | |duS)zMatch DNS names according RFC 6125 section 6.4.3. This code is effectively copied from CPython's ssl._dnsname_match. Returns a bool indicating whether the expected hostname matches the value in ``dn``. F.rrN*s.too many wildcards in certificate DNS name: %ss[^.]+sxn--s\*s[^.]*s\As\.s\Z)r r1r7countrrr9r:r6r reescaper8recompiler% IGNORECASEmatch) dnrG maxwildcardspatspiecesleftmost remainder wildcardsfragpatr)r)r* _dnsnamematch}s0       rc Cs|stdSg}|dg}|D]5\}}|dkrEz t||r"WdSWnty?}zt|jdWYd}~Sd}~ww||q|s|dgD]V}|D]Q\}}|dkrz|d}Wnt yrtd YSwz t||r~WdSWnty}zt|jdWYd}~Sd}~ww||qRqNd d |D}t |d krtd d |St |d krtd |dStdS)zVerify that cert (in socket.getpeercert() format) matches hostname. CRLs is not handled. Returns error message if any problems are found and None on success. sno certificate receivedsubjectAltNameDNSNrsubject commonNameasciis IDN in certificate not supportedcSsg|]}t|qSr))r r1).0dr)r)r* sz_verifycert..rscertificate is for %sris4no commonName or subjectAltName found in certificate) rgetrrr rrr:encodeUnicodeEncodeErrorrr%)certrGdnsnamessanr(valuersubr)r)r* _verifycertsT         $   rcCs>tjr ts tjs dStjtj}| dp| dS)a@return true if this seems to be a pure Apple Python that * is unfrozen and presumably has the whole mercurial module in the file system * presumably is an Apple Python that uses Apple OpenSSL which has patches for using system certificate store CAs in addition to the provided cacerts file Fs/usr/bin/pythons,/system/library/frameworks/python.framework/) r isdarwinr mainfrozen sysexecutabler@rArealpathr9r6)exer)r)r*_plainapplepythons rc Cszddl}|}tj|r|dt|WSWn tt fy&Ynwt r@tj tj tt d}tj|r@|SdS)areturn path to default CA certificates or None. It is assumed this function is called when the returned certificates file will actually be used to validate connections. Therefore this function may print warnings or debug messages assuming this usage. We don't print a message when the Python is able to load default CA certs because this scenario is detected at socket connect time. rNs#using ca certificates from certifi s dummycert.pem)certifiwherer@rArBrDr fsencodertAttributeErrorrr%dirname__file__)rFrcerts dummycertr)r)r*rCs"     rCcCs|jd}t|}|jd}|jd}z |d}|}Wnty/ttd|w|s;ttd||drJ|td|d St t | t t | t t | d }d d }d ||d} |dr|dD]+\} } || | kr|d|| || f|dr|td||| fd Sqy|drd} ||d} n d} d| ||| f} tjtd|| ftd| d|jdstjtd|td|| fdt||}|rtjtd||ftd|| fdd S)zxValidate a socket meets security requirements. The passed socket must have been created with ``wrapsocket()``. rlrnrmTs%s ssl connection errors-%s certificate error: no certificate receivedrswarning: connection security to %s is disabled per current settings; communication is susceptible to eavesdropping and tampering N)r/sha256ssha512cs$dfddtdtdDS)Nr-csg|] }||dqS)r))rxrIr)r*rJsz:validatesocket..fmtfingerprint..rr)r%rangerrr)rr*fmtfingerprintIs$z&validatesocket..fmtfingerprints sha256:%srrs)%s certificate matched fingerprint %s:%s rs(SHA-1 fingerprint for %s found in legacy [hostfingerprints] section; if you trust this fingerprint, remove the old SHA-1 fingerprint from [hostfingerprints] and add the following entry to the new [hostsecurity] section: %s:fingerprints=%s) shostfingerprintr/r,s%s:%ss0certificate for %s has unexpected fingerprint %sscheck %s configurationr!rksPunable to verify security of %s (no loaded CA certificates); refusing to connectssee https://mercurial-scm.org/wiki/SecureConnections for how to configure Mercurial to avoid this error or set hostsecurity.%s:fingerprints=%s to trust this servers%s certificate error: %ss^set hostsecurity.%s:certfingerprints=%s config setting or use --insecure to connect insecurely)rr r1 getpeercertrrrrr>rr sha1digesthashlibsha256sha512r9rDr)rshosthostrFrpeercert peercert2peerfingerprintsrnicefingerprinthashrNsectionnicerr)r)r*validatesockets             r)N)NNNF)r)& __future__rrr@rr;rwi18nrr rnoderrrr utilsr r r r#hassnisetr2ruaddrQrZrr ExceptionrrrrrCrr)r)r)r*sD        2  s 43 #