a ‚oeo�ã@s"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#l7m8Z8e 9e:¡Z;dEe!jej?d$œd%d&„Z@e!jd4œd5d6„ZHGd7d8„d8ƒZIdGe#jJe e#jKdd9œd:d;„ZLeAeMe!j„ZOe!jzózua_flags..Úhookú ) Ú isinstanceÚ DummyConfigZ duplicateÚappendZrenew_by_defaultÚallow_subset_of_namesÚnoninteractive_modeÚanyÚjoin)r#ÚflagsZ hook_namesZhooksr3rJr4rCls       rCc@s.eZdZdZddœdd„Zeedœdd„ZdS) rPz'Shim for computing a sample user agent.N©r&cCsd|_d|_d|_d|_dS)NZXXXZYYYZ SUBCOMMAND)r@rAr)rB)Úselfr3r3r4Ú__init__‚szDummyConfig.__init__©Únamer&cCsdS)z-Any config properties we might have are None.Nr3©rXr[r3r3r4Ú __getattr__ˆszDummyConfig.__getattr__)Ú__name__Ú __module__Ú __qualname__Ú__doc__rYÚstrrr]r3r3r3r4rP€srPrWcCstttjtƒƒƒS)zd}t |¡t |¡‚|j sNt  d¡|j rZd|_t d|j t ƒd�}tjt |¡d�}t||ƒ}t|||ƒ}t ||¡}| ||¡t ||¡||fS)a˜Register new account with an ACME CA. This function takes care of generating fresh private key, registering the account, optionally accepting CA Terms of Service and finally saving the account. It should be called prior to initialization of `Client`, unless account has already been created. :param certbot.configuration.NamespaceConfig config: Client configuration. :param .AccountStorage account_storage: Account storage where newly registered account will be saved to. Save happens only after TOS acceptance step, so any account private keys or `.RegistrationResource` will not be persisted if `tos_cb` returns ``False``. :param tos_cb: If ACME CA requires the user to accept a Terms of Service before registering account, client action is necessary. For example, a CLI tool would prompt the user acceptance. `tos_cb` must be a callable that should accept a Term of Service URL as a string, and raise an exception if the TOS is not accepted by the client. ``tos_cb`` will be called only if the client action is necessary, i.e. when ``terms_of_service is not None``. This argument is optional, if not supplied it will default to automatic acceptance! :raises certbot.errors.Error: In case of any client problems, in particular registration failure, or unaccepted Terms of Service. :raises acme.errors.Error: In case of any protocol problems. :returns: Newly registered and saved account, as well as protocol API handle (should be used in `Client` initialization). :rtype: `tuple` of `.Account` and `acme.client.Client` z*There are already existing accounts for %sNzLNo email was provided and --register-unsafely-without-email was not present.zRegistering without email!i)Zpublic_exponentr+Zbackend)r$)Zfind_allÚloggerÚinfor/ÚemailZregister_unsafely_without_emailÚerrorrÚErrorÚdry_runÚdebugr Ú rsa_key_sizer ÚjoseZJWKRSAZComparableRSAKeyr5Úperform_registrationrÚAccountÚsaverZprepare_subscription) r#rerfÚmsgZrsa_keyr$Úacmer%Zaccr3r3r4Úregister”s.&    ý     ru)rtr#rfr&c Cs |jo |j}|r8|jj ¡}tjj||j|j|jd�}nd}|  ¡rV|sVd}t   |¡‚|jj j }|rp|rp||ƒz| tjj|jd|d�¡WStj �y}z\|jdvrî|jrÈd|j›d�}t   |¡‚tjdd �|_t|||ƒWYd}~S‚WYd}~n d}~00dS) a… Actually register new account, trying repeatedly if there are email problems :param acme.client.Client acme: ACME client object. :param certbot.configuration.NamespaceConfig config: Client configuration. :param Callable tos_cb: a callback to handle Term of Service agreement. :returns: Registration Resource. :rtype: `acme.messages.RegistrationResource` )Úaccount_public_keyZkidZhmac_keyr2NzRServer requires external account binding. Please use --eab-kid and --eab-hmac-key.T)riZterms_of_service_agreedZexternal_account_binding)Z invalidEmailZinvalidContactzThe ACME server believes z_ is an invalid email address. Please ensure it is a valid email and attempt registration again.)Zinvalid)Zeab_kidZ eab_hmac_keyr1r$r0rZExternalAccountBindingZ from_datar2Zexternal_account_requiredrrkÚmetaZterms_of_serviceZ new_accountZNewRegistrationriÚcoderSÚ display_opsZ get_emailrp) rtr#rfZeab_credentials_suppliedrvZeabrsZtosÚer3r3r4rpÛs8  ý   ÿ   rpc @sÒeZdZdZd/ejeejee j ee j ee j ddœdd„Zd0ejeejeeefdœdd„Zd1eeeeeeeejejfd œd d „Zeeejd œd d„Zeeeeeejdœdd„Zejeeeedœdd„Z eeeeeeeejejfdœdd„Z!eeeeedœdd„Z"eedœdd„Z#eeeeeeeeefdœdd„Z$eeeeeedd œd!d"„Z%d2eeeedd$œd%d&„Z&d3eeeeedd'œd(d)„Z'eedd*œd+d,„Z(edd*œd-d.„Z)dS)4Ú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`. N)r#Úaccount_ÚauthrArtr&cCsv||_||_||_||_|dur>|jdur>t||jj|jjƒ}||_||durlt  ||j|j|jj ¡|_nd|_dS)zInitialize a client.N) r#rr}rAr5r$r%rtrZ AuthHandlerZ pref_challs)rXr#r|r}rArtr3r3r4rYsÿzClient.__init__)ÚcsrÚorderrr&cCs |jdur"d}t |¡t |¡‚|jdus8|jjdurBt d¡‚|jdurVt d¡‚t d|¡|durz|j |j dd�}t j   ¡t j |jjd�}t d |¡|jj|||jjdud �}|j}|jjrî|jrît |g|j|jj|jj ¡}t |¡\}}| ¡| ¡fS) aWObtain certificate. :param .util.CSR csr: PEM-encoded Certificate Signing Request. The key used to generate this CSR can be different than `authkey`. :param acme.messages.OrderResource orderr: contains authzrs :returns: certificate and chain as PEM byte strings :rtype: tuple Nz>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)Zsecondsz+Will poll for certificate issuance until %s)Zfetch_alternative_chains)rrgrjrrkrr%rtrmÚ_get_order_and_authorizationsÚdataÚdatetimeZnowZ timedeltar#Zissuance_timeoutZfinalize_orderZpreferred_chainZ fullchain_pemZalternative_fullchains_pemrZfind_chain_with_issuerrlZcert_and_chain_from_fullchainÚencode)rXr~rrsZdeadlineZ fullchainÚcertÚchainr3r3r4Úobtain_certificate_from_csr3s4        ÿ ÿ þz"Client.obtain_certificate_from_csr)ÚdomainsÚ old_keypathr&c sÌ|durZt|dƒ�}|}| ¡}Wdƒn1s40Ytj||d�}t d|¡nd}|jj}d}t|jj t ƒrˆ|jj d|j_ |jj r¾|jj dkr¾|jj }d|j_ d |j_ d |j_n |jjrÞ|jj  ¡d krÞ|jj}|jj�r.|�p tjdtj|||jj d �d�}tjdd t |j||jj¡d�} n<|�pNtj|d|jj ||jjd�}t ||d|jj|jj¡} z| | j|jj¡} Wnptj�yð} zT|jj�rÚ|  | |¡} | |k�rÚt!| ƒdk�rÚ| "|| ¡WYd} ~ S‚WYd} ~ n d} ~ 00| j#} dd„| Dƒ‰‡fdd„|Dƒ} |jj�r8| |k�r8| "|| ¡Sz| $| | ¡\}}|||| fWStj�yÆ} zT|jj�r°|  | |¡} | |k�r°t!| ƒdk�r°| "|| ¡WYd} ~ S‚WYd} ~ n d} ~ 00dS)aˆObtains 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 NÚrb)ÚfileÚpemz%Reusing existing private key from %s.Z secp256r1rZecdsaz./chain-ecdsa.pemz./cert-ecdsa.pemz./key-ecdsa.pemZrsa)ÚbitsÚelliptic_curveÚkey_typer�)rŒÚformrƒ)r+Zkey_dirr�r�Ústrict_permissionscSsh|]}|jjj’qSr3)ÚbodyÚ identifierÚvalue)rHÚar3r3r4Ú ·rLz,Client.obtain_certificate..csg|]}|ˆvr|‘qSr3r3©rHÚd©Z auth_domainsr3r4rK¸rLz-Client.obtain_certificate..)%ÚopenÚreadrÚKeyrgrhr#rnrOr�Úlistr�Zauth_chain_pathZauth_cert_pathÚkey_pathÚlowerrlrZmake_keyÚCSRÚacme_crypto_utilZmake_csrr�Z must_stapleZ generate_keyr’Z generate_csrr‚rƒrRrrkÚ_successful_domains_from_errorÚlenÚ_retry_obtain_certificateÚauthorizationsrˆ)rXr‰rŠÚfZkeypathZkeypemr$r+r�r~rrjÚsuccessful_domainsÚauthzrr†r‡r3ršr4Úobtain_certificate`s€ &   ýþ  ÿÿ ûÿ     zClient.obtain_certificate)Úcsr_pemr�r&cCs²|jst d¡‚z|j |¡}Wntjy>t d¡‚Yn0|jsPt d¡‚|r”|jjr”|j  |¡\}}|r†t   d¡|j |¡}|r”t   d¡|j  ||j|¡}|j|d�S)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 r€zWThe 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¦)rtrrkZ new_orderÚ acme_errorsZWildcardUnsupportedErrorrr#rlZdeactivate_valid_authorizationsrgrmZwarningZhandle_authorizationsÚupdate)rXr«r�rZ deactivatedZfailedr©r3r3r4r‚Ïs"       z$Client._get_order_and_authorizations)r‰Úcertnamer&cCs|| ||¡}| |¡\}}}}|jjtjdksB|jjtjdkrLt d¡|jj rdt  d|¡dSt j   |||j||j¡S)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_dirÚwork_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_lineagenamerªr#r¯rZ CLI_DEFAULTSr°rgrhrlrmrÚ RenewableCertZ new_lineager�)rXr‰r®Únew_namer†r‡r$Ú_r3r3r4Úobtain_and_enroll_certificateós  ÿÿ ýz$Client.obtain_and_enroll_certificate)rjr‰r&cs4|jdur0dd„|jDƒ‰‡fdd„|Dƒ}|SgS)NcSsg|]}|jdur|jj‘qS)N)r”r•)rHZproblemr3r3r4rKs ÿz9Client._successful_domains_from_error..csg|]}|ˆvr|‘qSr3r3)rHÚx©Úfailed_domainsr3r4rKrL)Z subproblems)rXrjr‰r¨r3r·r4r£s  z%Client._successful_domains_from_error)r‰r¨r&cs6‡fdd„|Dƒ}d |¡}t d|›�¡| ˆ¡S)Ncsg|]}|ˆvr|‘qSr3r3r˜©r¨r3r4rK rLz4Client._retry_obtain_certificate..z, zNUnable to obtain a certificate with every requested domain. Retrying without: )rUÚ display_utilÚnotifyrª)rXr‰r¨r¸Z domains_listr3r¹r4r¥s  ÿz Client._retry_obtain_certificatecCsZd}|r|}n(t |d¡r.|ddd…}n|d}| |¡rD|St |rPdnd¡‚dS)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. NrézzThe provided certname cannot be used as a lineage name because it contains an illegal character (i.e. filepath separator).z�Cannot use domain name as lineage name because it contains an illegal character (i.e. filepath separator). Specify an explicit lineage name with --cert-name.)rZis_wildcard_domainÚ_is_valid_lineagenamerrk)rXr‰r®Z lineagenamer3r3r4r±&s ÿýzClient._choose_lineagenamerZcCs 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 ÚpathÚsepr\r3r3r4r½Hs zClient._is_valid_lineagename)Úcert_pemÚ chain_pemÚ cert_pathÚ chain_pathÚfullchain_pathr&c Cs¤|||fD]}t tj |¡d|jj¡q t|jd|ƒ\}}z| |¡W|  ¡n |  ¡0t|jd|ƒ\} } t|jd|ƒ\} } t || ƒt ||| ƒ|| | fS)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 iírÂrÃrÄ) rZmake_or_verify_dirr r¾Údirnamer#r’Ú_open_pem_fileÚwriteÚcloseÚ _save_chain) rXrÀrÁrÂrÃrÄr¾Z cert_fileZ abs_cert_pathÚ chain_fileZabs_chain_pathZfullchain_fileZabs_fullchain_pathr3r3r4Úsave_certificateUs ÿ zClient.save_certificate)r‰Ú privkey_pathrÂrÃrÄr&c Csø|jdurt d¡t d¡‚|dur*dn tj |¡}t  d¡d}t   |j |¡�V|D]4}|jj |tj |¡tj |¡||d�|j ¡qX|j d¡Wdƒn1s®0Yd}t   |j|¡�|j ¡Wdƒn1sê0YdS) 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 certificateúNo installer availablezDeploying certificatezCould not install certificate)ÚdomainrÂrŸrÃrÄzDeployed ACME CertificatezuWe were unable to install your certificate, however, we successfully restored your server to its prior configuration.)rArgrjrrkr r¾Úabspathrºr»rÚ ErrorHandlerÚ_recovery_routine_with_msgZ deploy_certrrÚ_rollback_and_restartÚrestart)rXr‰rÌrÂrÃrÄrsÚdomr3r3r4Údeploy_certificatezs&      ü *zClient.deploy_certificateT)r‰rÃÚredirect_defaultr&c Csâ|jdurt d¡t d¡‚d}dddd|fd f}|j ¡}|D]Z\}}} t|j|ƒ} ||vrŒ|d krt| durt|} | rœ| ||| ¡d }qB| rBt d |¡qBd } |rÞt   |j | ¡�|j  ¡Wdƒn1sÔ0YdS)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.rÍF)Zhstsúensure-http-headerzStrict-Transport-Security)ÚredirectrØNZstaplez staple-ocsp)Zuirr×zUpgrade-Insecure-RequestsrØTzKOption %s is not supported by the selected installer. Skipping enhancement.z$We were unable to restart web server) rArgrjrrkZsupported_enhancementsrGr#Úapply_enhancementrrÐrÒrÓ) rXr‰rÃrÖZenhancedZenhancement_infoZ supportedZ config_nameZenhancement_nameÚoptionZ config_valuersr3r3r4Úenhance_config¡s6   ü  þzClient.enhance_config)r‰Ú enhancementÚoptionsr&c CsÆ|jst d¡‚|dkr|n|}t |jd¡�„|D]\}z|j |||¡Wq4tjylt  d|¡Yq4tj yŽt  d||¡‚Yq40q4|j  d|›�¡Wdƒn1s¸0YdS)aåApplies an enhancement on all domains. :param list domains: list of ssl_vhosts (as strings) :param str enhancement: name of enhancement, e.g. ensure-http-header :param str options: options to enhancement, e.g. Strict-Transport-Security .. note:: When more `options` are needed, make options a list. :raises .errors.PluginError: If Enhancement is not supported, or if there is any other problem with the enhancement. z!No installer plugin has been set.r×NzEnhancement %s was already set.z(Unable to set the %s enhancement for %s.zAdd enhancement ) rArrkrrÐrÑZenhanceZPluginEnhancementAlreadyPresentrgrhZ PluginErrorrjrr)rXr‰rÜrÝZ enh_labelrÔr3r3r4rÙÍs  zClient.apply_enhancement)Ú success_msgr&cCs"|jr|j ¡|rt |¡dS)z�Calls the installer's recovery routine and prints success_msg :param str success_msg: message to show on successful recovery N)rAZrecovery_routinerºr»©rXrÞr3r3r4rÑës z!Client._recovery_routine_with_msgcCsP|jrLt d¡z|j ¡|j ¡Wnt d¡‚Yn0t |¡dS)z�Rollback the most recent checkpoint and restart the webserver :param str success_msg: message to show on successful rollback z0Rolling back to previous server configuration...zÊAn 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)rArgrhÚrollback_checkpointsrÓrjrºr»rßr3r3r4rÒös  ÿzClient._rollback_and_restart)N)N)N)T)N)*r^r_r`rarrcrrrqrZ AuthenticatorZ Installerr,r.rYrr¡rZ OrderResourcer Úbytesrˆrrbr�rªÚboolr‚rr²rµrkr£r¥r±r½rËrÕrÛrÙrÑrÒr3r3r3r4r{ s\ý ý ÿ þ -ÿ oÿ $ ÿ " ÿ ÿ "  þ % ÿ (ÿ ÿ -ÿ ÿ  r{)Úprivkeyr~r&cCs¦|jrt |j¡st d¡‚|r¢|jdkr`tj tjj |j ¡}tj  tjj |¡}t  |j|d¡}|j r|t |j ¡s|t d¡‚|j r¢|jr¢t |j |j¡s¢t d¡‚dS)aéValidate Key and CSR files. Verifies that the client key and csr arguments are valid and correspond to one another. This does not currently check the names in the CSR due to the inability to read SANs from CSRs in python crypto libraries. If csr is left as None, only the key will be validated. :param privkey: Key associated with CSR :type privkey: :class:`certbot.util.Key` :param .util.CSR csr: CSR :raises .errors.Error: when validation fails z#The provided key is not a valid keyZderr�z#The provided CSR is not a valid CSRzThe key and CSR do not matchN)r�rZ valid_privkeyrrkr‘ÚOpenSSLZcryptoZload_certificate_requestZ FILETYPE_ASN1rƒZdump_certificate_requestZ FILETYPE_PEMrr¡rŒZ valid_csrZcsr_matches_pubkey)rãr~Zcsr_objZ cert_bufferr3r3r4Úvalidate_key_csr s$   ÿÿ  ÿrå)Údefault_installerÚ checkpointsr#Úpluginsr&cCs0tj|||dd�}|dur,| |¡| ¡dS)aªRevert configuration the specified number of checkpoints. :param str default_installer: Default installer name to use for the rollback :param int checkpoints: Number of checkpoints to revert. :param config: Configuration. :type config: :class:`certbot.configuration.NamespaceConfiguration` :param plugins: Plugins available :type plugins: :class:`certbot._internal.plugins.disco.PluginsRegistry` z,Which installer should be used for rollback?)ZquestionN)Úplugin_selectionZpick_installerràrÓ)rærçr#rèrAr3r3r4Úrollback:s ÿ rê)r#Ú cli_arg_pathÚpem_pathr&cCsL| |¡r&tj|ddd�tj |¡fSt |dd¡}|dtj |d¡fS)a'Open a pem file. If cli_arg_path was set by the client, open that. Otherwise, uniquify the file path. :param str cli_arg_path: the cli arg name, e.g. cert_path :param str pem_path: the pem file path to open :returns: a tuple of file object and its absolute file path i¤Úwb)ÚchmodÚmoderé)Z set_by_userrZ safe_openr r¾rÏZ unique_file)r#rërìZuniqr3r3r4rÆSs  ÿrÆ)rÁrÊr&cCs&z| |¡W| ¡n | ¡0dS)z¥Saves chain_pem at a unique path based on chain_path. :param bytes chain_pem: certificate chain in PEM format :param str chain_file: chain file object N)rÇrÈ)rÁrÊr3r3r4rÉgs rÉ)N)N)N)Srar„Zloggingr<Útypingrrrrrrrr Zcryptography.hazmat.backendsr Z-cryptography.hazmat.primitives.asymmetric.rsar Zjosepyror r rrrärtrr,rr¢rr¬rr7rrrZcertbot._internalrrrrrrrZcertbot._internal.pluginsrZ plugin_discorréZcertbot.compatr Zcertbot.displayr!ryrºZcertbot.interfacesr"Z getLoggerr^rgrcZJWKZRegistrationResourcer.r5rbr-rCrPrdrqrurpr{r�r¡råÚintZPluginsRegistryrêrÆrárÉr3r3r3r4Ús’                                     ÿ þ   ÿþ Gÿ 2. ÿ ÿ