M/eo dZddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd l mZdd lmZddlZdd lmZddlmZddlmZddlmZddlZddlmZddlmZddlmZddlmZddl Z ddl m!Z!ddl mZddl mZddl m"Z"ddl m#Z#ddl$m%Z%ddl$m&Z&ddl$m'Z'ddl$m(Z(ddl$m)Z)ddl$m*Z*ddl$m+Z+ddl,m-Z.dd l,m/Z0dd!l1m2Z2dd"l3m4Z5ddl3m#Z6dd#l7m8Z8ejre:Z; dBd$e!jxd%ejzd&e ej|d'ej~fd(Z@d$e!jxd'eAfd)ZBd$e!jxd'eAfd*ZCGd+d,ZDd'eAfd-ZE dBd$e!jxd.e8d/e eeAgdfd'e e%jej~ffd0ZGd1ej~d$e!jxd/e eeAgdfd'ej|fd2ZHGd3d4ZIdBd5e#jd6e e#jd'dfd7ZLd8eAd9eMd$e!jxd:e.jd'df d;ZOd$e!jxdZPd?eQd@e d'dfdAZRy)CzCertbot client API.N)Any)Callable)cast)Dict)IO)List)Optional)Tuple)default_backend)generate_private_key)ES256)ES384)ES512)RS256)client) crypto_util)errors)messages) configuration) interfaces)util)account) auth_handler)cli) constants)eff) error_handler)storage)disco) selection)os)ops)AccountStorageconfigkeyregrreturnc |jdk(rc|j}|jdk(rt}nG|jdk(rt}n1|jdk(rt }nt jdt}tj||||j t|}tjj|j|}tj||S)z Wrangle ACME client constructionECii z6No matching signing algorithm can be found for the key)algr verify_ssl user_agent)typr%key_sizer rrrNotSupportedErrorr acme_client ClientNetwork no_verify_ssldetermine_user_agentClientV2 get_directoryserver)r$r%r& public_keyr+net directorys :/usr/lib/python3/dist-packages/certbot/_internal/client.pyacme_from_config_keyr<2s ww$WW   # %C  C 'C  C 'C**H   # #CS$4:4H4H0H/CF/K MC$$226==#FI    3 //c |jd}tjjddk(rd}d}d}n8tj }t j}tj}|jtj|||j|j|jt!|||j"rd|j"z }|Sd }|S|j}|S) z Set a user_agent string in the config based on the choice of plugins. (this wasn't knowable at construction time) :returns: the client's User-Agent string :rtype: `str` z\CertbotACMEClient/{0} ({1}; {2}{8}) Authenticator/{3} Installer/{4} ({5}; flags: {6}) Py/{7} CERTBOT_DOCS1certbotzOS_NAME OS_VERSIONzmajor.minor.patchlevelz; )r-r!environgetr cli_commandrget_os_info_uaplatformpython_versionformatrA __version__ authenticator installerverbua_flagsuser_agent_comment)r$uarEos_inforHs r;r4r4Ls ) ::>>. )S 0#K*G5N//K))+G%446N YYw**K++V-=-=v{{';A;T;Ttf777^ I[]^ I   Ir=ct|tryg}|jr|jd|jr|jd|j r|jd|j r|jdd}|Dcgc]}t||dz}}t|r|jdd j|Scc}w) z@Turn some very important CLI flags into clues in the user agent.FLAGSdupfrnasnn)prepostrenew manual_authmanual_cleanup_hookhook ) isinstance DummyConfig duplicateappendrenew_by_defaultallow_subset_of_namesnoninteractive_modegetattranyjoin)r$flags hook_nameshhookss r;rNrNls&+& E  U  U ## U !! SJJ3= >aWVQ[ ) >E > 5z V 88E? ?sCc(eZdZdZddZdedefdZy)raz'Shim for computing a sample user agent.r'Nc<d|_d|_d|_d|_y)NXXXYYY SUBCOMMAND)rKrLr-rM)selfs r;__init__zDummyConfig.__init__s"  r=namecy)z-Any config properties we might have are None.Nrsrus r; __getattr__zDummyConfig.__getattr__sr=)r'N)__name__ __module__ __qualname____doc__rtstrrryrwr=r;raras1! r=racXtttjt S)z>  667 7))26<<.A--ll3''&00>FL'ff= =  s%:DF)A&FFFFc6eZdZdZ d,dej deejdee jdee jdee jddf d Z d,d ej d eej$deeeffd Zd,d eedeedeeeej0ej ffdZdededej$fdZd eedeedeej:fdZdej>d eedeefdZ d eedeedeeeej0ej ffdZ!d eedeedefdZ"dedefdZ#dedededed edeeeeff d!Z$d eed"ededed eddf d#Z% d-d eeded$eddfd%Z& d,d eed&ed'eeddfd(Z'd)eeddfd*Z(d)eddfd+Z)y).ClientawCertbot's client. :ivar certbot.configuration.NamespaceConfig config: Client configuration. :ivar .Account account: Account registered with `register`. :ivar .AuthHandler auth_handler: Authorizations handler that will dispatch DV challenges to appropriate authenticators (providing `.Authenticator` interface). :ivar .Authenticator auth: Prepared (`.Authenticator.prepare`) authenticator that can solve ACME challenges. :ivar .Installer installer: Installer. :ivar acme.client.ClientV2 acme: Optional ACME client API handle. You might already have one from `register`. Nr$account_authrLrr'cr||_||_||_||_|A|j5t ||jj |jj }||_||Ftj||j|j|jj|_yd|_y)zInitialize a client.N) r$rrrLr<r%r&rr AuthHandler pref_challs)rsr$rrrLrs r;rtzClient.__init__s    " Unable to obtain certificate because authenticator is not set.z+Please register with the ACME server first.ACME client is not set.zCSR: %sF) best_effort)secondsz+Will poll for certificate issuance until %s)fetch_alternative_chains)rrrrrrr&rr_get_order_and_authorizationsdatadatetimenow timedeltar$issuance_timeoutfinalize_orderpreferred_chain fullchain_pemalternative_fullchains_pemrfind_chain_with_issuerrcert_and_chain_from_fullchainencode)rsrrrdeadline fullchaincertchains r;obtain_certificate_from_csrz"Client.obtain_certificate_from_csr3s    $C LL ,,s# # << 4<<#4#4#<,,LM M 99 ,,89 9 Y$ >77e7TF$$((*X-?-?KK00.22  BHM)) Ht{{7R7RZ^7^*`(( ;; & &6+L+L#:: f??? ++1D1D-DFI"?? J e{{}elln,,r=domains old_keypathc |Ut|d5}|}|j}dddtj}tj d|nd}|j j}d}t|j jtr(|j jd|j _ |j jrc|j jdk(rJ|j j}d|j _ d |j _ d |j _nS|j jr=|j jjd k(r|j j}|j j r|xsAtjdt#j$|||j j }tj&dd t)j*|j,||j j.} n|xsBt#j0|d|j j||j j2}t#j4||d|j j.|j j2} |j7| j8|j j:} | jF} | Dchc]"}|jHjJjL$}}|Dcgc] }||vs| } }|j j:r| |k7r|jE|| S |jO| | \}}|||| fS#1swY_xYw#t<j>$rX} |j j:r<|jA| |} | |k7r%tC| dk7r|jE|| cYd} ~ Sd} ~ wwxYwcc}wcc}w#t<j>$rX} |j j:r<|jA| |} | |k7r%tC| dk7r|jE|| cYd} ~ Sd} ~ wwxYw)aObtains a certificate from the ACME server. `.register` must be called before `.obtain_certificate` :param list domains: domains to get a certificate :returns: certificate as PEM string, chain as PEM string, newly generated private key (`.util.Key`), and DER-encoded Certificate Signing Request (`.util.CSR`). :rtype: tuple Nrb)filepemz%Reusing existing private key from %s. secp256r1recdsaz./chain-ecdsa.pemz./cert-ecdsa.pemz./key-ecdsa.pemrsa)bitselliptic_curvekey_typer)rformr)r/key_dirrrstrict_permissions)(openreadrKeyrrr$rr`rlistrauth_chain_pathauth_cert_pathkey_pathlowerrrmake_keyCSRacme_crypto_utilmake_csrr must_staple generate_keyr generate_csrrrrerr_successful_domains_from_errorlen_retry_obtain_certificateauthorizationsbody identifiervaluer)rsrrfkeypathkeypemr%r/rrrrsuccessful_domainsauthzra auth_domainsdrrs r;obtain_certificatezClient.obtain_certificate`s(  "k4( "A% "'+hhG&HC KK? MC;;++$ dkk**D 1#';;#7#7#:DKK ;; % %$++*>*>'*I![[77N*=DKK ');DKK DKK [[ % %$++*>*>*D*D*F%*O{{//H ;;  ((!#1![[11C((5 0 9 9"ww1H1H!JKC11!---#';;#A#A C**WdDKK$;$;T[[=[=[]C 77$++BcBcdF&&9?@A))//@ @)0FAA4EaFF ;; , ,1Cw1N11';MN N ">>sFK eUC,,S " "d~~ {{00%)%H%HPW%X"%0S9K5LPQ5Q99'CUVV  AF>> ;;44)-)L)LUT[)\&)W4=O9PTU9U#==gGYZZ sgM?90N 9'O:& O?0O?$P?N  O7A O2+O71O22O7Q/A Q*#Q/)Q**Q/csr_pemrc|jstjd |jj|}|j stjd|r}|jjrg|j j|\}}|r0tjd|jj|}|rtjd|j j||j|}|j|S#tj $rtjdwxYw)abRequest a new order and complete its authorizations. :param bytes csr_pem: A CSR in PEM format. :param bool best_effort: True if failing to complete all authorizations should not raise an exception :returns: order resource containing its completed authorizations :rtype: acme.messages.OrderResource rzWThe currently selected ACME CA endpoint does not support issuing wildcard certificates.z&No authorization handler has been set.z*Recreating order after authz deactivationszCertbot was unable to obtain fresh authorizations for every domain. The dry run will continue, but results may not be accurate.)r)rrr new_order acme_errorsWildcardUnsupportedErrorrr$rdeactivate_valid_authorizationsrrwarninghandle_authorizationsupdate)rsrrr deactivatedfailedrs r;rz$Client._get_order_and_authorizationssyy,,89 9 NYY((1F   ,,GH H dkk))"&"3"3"S"STZ"[ K IJ,,W5 _`""88kZ}}F}33%33 N,, MN N Ns D)Ecertnamec|j||}|j|\}}}}|jjtj dk7s*|jj tj dk7rtjd|jjrtjd|ytjj|||j||jS)aFObtain and enroll certificate. Get a new certificate for the specified domains using the specified authenticator and installer, and then create a new renewable lineage containing it. :param domains: domains to request a certificate for :type domains: `list` of `str` :param certname: requested name of lineage :type certname: `str` or `None` :returns: A new :class:`certbot._internal.storage.RenewableCert` instance referred to the enrolled cert lineage, or None if doing a successful dry run. config_dirwork_dirzdNon-standard path(s), might not work with crontab installed by your operating system package managerz-Dry run: Skipping creating new lineage for %sN)_choose_lineagenamerr$rr CLI_DEFAULTSrrrrrr RenewableCert new_lineager)rsrrnew_namerrr%_s r;obtain_and_enroll_certificatez$Client.obtain_and_enroll_certificates"++GX>"55g>eS! KK " "i&<&<\&J J $$ (>(>z(JJ KK; < ;;   LLH( S$$00 d GGU KK r=rc|jO|jDcgc]$}|j|jj&}}|Dcgc] }||vs| }}|SgScc}wcc}wN) subproblemsrr)rsrrproblemfailed_domainsxrs r;rz%Client._successful_domains_from_errorsz    (FKFWFWC7#*#5#5#A&0066CNC-4!P8O!!P !P% % C!Ps)A A#A#rc|Dcgc] }||vs| }}dj|}tjd||j|Scc}w)Nz, zNUnable to obtain a certificate with every requested domain. Retrying without: )ri display_utilnotifyr)rsrrrr domains_lists r;rz Client._retry_obtain_certificates`%,L9K0K!LLyy0 ))58 9&&'9:: Ms AAcd}|r|}n&tj|dr |ddd}n|d}|j|r|Stj|rdd)auChooses a name for the new lineage. :param domains: domains in certificate request :type domains: `list` of `str` :param certname: requested name of lineage :type certname: `str` or `None` :returns: lineage name that should be used :rtype: str :raises errors.Error: If the chosen lineage name is invalid. NrzzThe provided certname cannot be used as a lineage name because it contains an illegal character (i.e. filepath separator).zCannot use domain name as lineage name because it contains an illegal character (i.e. filepath separator). Specify an explicit lineage name with --cert-name.)ris_wildcard_domain_is_valid_lineagenamerr)rsrr lineagenames r;rzClient._choose_lineagename&sx "K  $ $WQZ 0!!*QR.K!!*K  % %k 2 ,,EMB% %$% %r=ruc:tjj|vS)aNDetermines whether the provided name is a valid lineagename. A lineagename is invalid when it contains filepath separators. :param name: the lineage name to determine validity for :type name: `str` :returns: Whether the provided string constitutes a valid lineage name. :rtype: bool )r!pathseprxs r;r'zClient._is_valid_lineagenameHsww{{$&&r=cert_pem chain_pem cert_path chain_pathfullchain_pathc|||fD]J}tjtjj |d|j j Lt|j d|\}} |j||jt|j d|\} } t|j d|\} } t|| t||z| || | fS#|jwxYw)a$Saves the certificate received from the ACME server. :param bytes cert_pem: :param bytes chain_pem: :param str cert_path: Candidate path to a certificate. :param str chain_path: Candidate path to a certificate chain. :param str fullchain_path: Candidate path to a full cert chain. :returns: cert_path, chain_path, and fullchain_path as absolute paths to the actual files :rtype: `tuple` of `str` :raises IOError: If unable to find room to write the cert files ir.r/r0) rmake_or_verify_dirr!r*dirnamer$r_open_pem_filewriteclose _save_chain) rsr,r-r.r/r0r* cert_file abs_cert_path chain_fileabs_chain_pathfullchain_fileabs_fullchain_paths r;save_certificatezClient.save_certificateUs$z>9 bD  # #BGGOOD$95$++B`B` a b$2$++{I#V =  OOH % OO %3DKKz%Z" N-; KK)>.;** Iz*Hy(.9n.@@@ OO s .C##C5 privkey_pathc |j*tjdtjd|dnt j j|}tjdd}tj|j|5|D]v}|jj|t j j|t j j||||jjx|jjddddd}tj|j|5|jj!dddy#1swYOxYw#1swYyxYw) abInstall certificate :param list domains: list of domains to install the certificate :param str privkey_path: path to certificate private key :param str cert_path: certificate file path (optional) :param str fullchain_path: path to the full chain of the certificate :param str chain_path: chain file path NzANo installer specified, client is unable to deploythe certificateNo installer availablezDeploying certificatezCould not install certificate)domainr.rr/r0zDeployed ACME CertificatezuWe were unable to install your certificate, however, we successfully restored your server to its prior configuration.)rLrrrrr!r*abspathr!r"r ErrorHandler_recovery_routine_with_msg deploy_certr_rollback_and_restartrestart)rsrr?r.r/r0rdoms r;deploy_certificatezClient.deploy_certificatezsE >> ! LL- .,,78 8'/TRWW__Z5P 34-  ' '(G(G M = &**"''//)*DWW__\:)#1 +3 ##%  & NN   ; < =4 ' '(B(BC H % NN " " $ % % = = % %sBE6F6E?F redirect_defaultc"|j*tjdtjdd}dddd|fd f}|jj }|D][\}}} t |j|} ||vr"|d k(r| |} | s-|j||| d }C| sFtjd |]d } |rDtj|j| 5|jjdddyy#1swYyxYw)afEnhance the configuration. :param list domains: list of domains to configure :param chain_path: chain file path :type chain_path: `str` or `None` :param redirect_default: boolean value that the "redirect" flag should default to :raises .errors.Error: if no installer is specified in the client. NzDNo installer is specified, there isn't any configuration to enhance.rAF)hstsensure-http-headerzStrict-Transport-Security)redirectrONstaplez staple-ocsp)uirrNzUpgrade-Insecure-RequestsrOTzKOption %s is not supported by the selected installer. Skipping enhancement.z$We were unable to restart web server) rLrrrrsupported_enhancementsrgr$apply_enhancementrrDrGrH) rsrr/rKenhancedenhancement_info supported config_nameenhancement_nameoption config_valuers r;enhance_configzClient.enhance_configs& >> ! LL7 8,,78 8 G * }j 1 F I NN99; 5E : 1K)6"4;;  ? @ @==NKK A9M))LL!KYX[\ @ @s0 C1B/ C1)C.C1+C..C11C: success_msgc|jr3|jj|rtj|yyy)zCalls the installer's recovery routine and prints success_msg :param str success_msg: message to show on successful recovery N)rLrecovery_routiner!r"rsrcs r;rEz!Client._recovery_routine_with_msgs6 >> NN + + -##K0 r=c|jr`tjd |jj|jj t j|yy#tj dxYw)zRollback the most recent checkpoint and restart the webserver :param str success_msg: message to show on successful rollback z0Rolling back to previous server configuration...zAn error occurred and we failed to restore your config and restart your server. Please post to https://community.letsencrypt.org/c/help with details about your configuration and this error you received.N)rLrrrollback_checkpointsrHrr!r"rfs r;rGzClient._rollback_and_restartsp >> KKJ K 335&&(    ,    Y s 4A..Br)T)*rzr{r|r}rrr rrr Authenticator Installerr1r5rtrrr OrderResourcer bytesrrr~rrboolrrrrrrrrr'r>rJr[rSrErGrwr=r;rr s $9=%}<<%QXQ`Q`Ha% 8 89%$Z%9%9:% 4 45%BF%.PT+-txx+-,4X5K5K,L+-).ue|)<+-Zm$s)m(3-m %eUDHHdhh&F Gm^"4U"437"4rs8N&0&!%*!'!+%;C.0-   8 $JN0!>!>0TXX0'(E(EF0)2204!>!>3@]22s(  T3T8<D]22D^Dhud{34D)=)==>DN/{33/]=Z=Z/!)(C5$;*?!@/EMEbEb/d|-|-~+Cdhh+CXdhh-?+C4+C\#"22=I=Y=Y^b2-=88-!$-03-8=b#g-( 5 b T r=