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#l7m8Z8e9e:Z;dEe!jej?d$d%d&Z@e!jd4d5d6ZHGd7d8d8ZIdGe#jJe e#jKdd9d:d;ZLeAeMe!jZOe!jzzua_flags..hook ) isinstance DummyConfigZ duplicateappendZrenew_by_defaultallow_subset_of_namesnoninteractive_modeanyjoin)r#flagsZ hook_namesZhooksr3rJr4rCls       rCc@s.eZdZdZddddZeedddZdS) rPz'Shim for computing a sample user agent.Nr&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.Nr3rXr[r3r3r4 __getattr__szDummyConfig.__getattr__)__name__ __module__ __qualname____doc__rYstrrr]r3r3r3r4rPsrPrWcCstttjtS)zd}t|t||j sNt d|j rZd|_t d|j t d}tjt|d}t||}t|||}t||}|||t||||fS)aRegister 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_allloggerinfor/emailZregister_unsafely_without_emailerrorrErrordry_rundebugr rsa_key_sizer joseZJWKRSAZComparableRSAKeyr5perform_registrationrAccountsaverZprepare_subscription) r#rerfmsgZrsa_keyr$acmer%Zaccr3r3r4registers.&         ru)rtr#rfr&c Cs |jo |j}|r8|jj}tjj||j|j|jd}nd}| rV|sVd}t ||jj j }|rp|rp||z|tjj|jd|dWStj y}z\|jdvr|jrd|jd}t |tjdd |_t|||WYd}~SWYd}~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_requiredrrkmetaZterms_of_serviceZ new_accountZNewRegistrationricoderS display_opsZ get_emailrp) rtr#rfZeab_credentials_suppliedrvZeabrsZtoser3r3r4rps8        rpc @seZdZdZd/ejeejee j ee j ee j ddddZd0ejeejeeefdddZd1eeeeeeeejejfd d d Zeeejd d dZeeeeeejdddZejeeeedddZ eeeeeeeejejfdddZ!eeeeedddZ"eedddZ#eeeeeeeeefdddZ$eeeeeedd d!d"Z%d2eeeedd$d%d&Z&d3eeeeedd'd(d)Z'eedd*d+d,Z(edd*d-d.Z)dS)4ClientawCertbot'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}rArtr3r3r4rYszClient.__init__)csrorderrr&cCs |jdur"d}t|t||jdus8|jjdurBtd|jdurVtdtd||durz|j |j dd}t j t j |jjd}td ||jj|||jjdud }|j}|jjr|jrt|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_authorizationsdatadatetimeZnowZ timedeltar#Zissuance_timeoutZfinalize_orderZpreferred_chainZ fullchain_pemZalternative_fullchains_pemrZfind_chain_with_issuerrlZcert_and_chain_from_fullchainencode)rXr~rrsZdeadlineZ fullchaincertchainr3r3r4obtain_certificate_from_csr3s4          z"Client.obtain_certificate_from_csr)domains old_keypathr&c s|durZt|d}|}|}Wdn1s40Ytj||d}td|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}|jjr.|p tjdtj|||jj d d}tjdd t|j||jjd} n<|pNtj|d|jj ||jjd}t||d|jj|jj} z|| j|jj} Wnptjy} zT|jjr| | |} | |krt!| dkr|"|| WYd} ~ SWYd} ~ n d} ~ 00| j#} dd| Dfdd|D} |jjr8| |kr8|"|| Sz|$| | \}}|||| fWStjy} zT|jjr| | |} | |krt!| dkr|"|| WYd} ~ SWYd} ~ n d} ~ 00dS)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.Z secp256r1rZecdsaz./chain-ecdsa.pemz./cert-ecdsa.pemz./key-ecdsa.pemZrsa)bitselliptic_curvekey_typer)rformr)r+Zkey_dirrrstrict_permissionscSsh|]}|jjjqSr3)body identifiervalue)rHar3r3r4 rLz,Client.obtain_certificate..csg|]}|vr|qSr3r3rHdZ auth_domainsr3r4rKrLz-Client.obtain_certificate..)%openreadrKeyrgrhr#rnrOrlistrZauth_chain_pathZauth_cert_pathkey_pathlowerrlrZmake_keyCSRacme_crypto_utilZmake_csrrZ must_stapleZ generate_keyrZ generate_csrrrrRrrk_successful_domains_from_errorlen_retry_obtain_certificateauthorizationsr)rXrrfZkeypathZkeypemr$r+rr~rrjsuccessful_domainsauthzrrrr3rr4obtain_certificate`s &           zClient.obtain_certificate)csr_pemrr&cCs|jstdz|j|}Wntjy>tdYn0|jsPtd|r|jjr|j |\}}|rt d|j|}|rt d|j ||j|}|j|dS)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)rtrrkZ new_order acme_errorsZWildcardUnsupportedErrorrr#rlZdeactivate_valid_authorizationsrgrmZwarningZhandle_authorizationsupdate)rXrrrZ deactivatedZfailedrr3r3r4rs"       z$Client._get_order_and_authorizations)rcertnamer&cCs||||}||\}}}}|jjtjdksB|jjtjdkrLtd|jj rdt d|dSt j |||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#rrZ CLI_DEFAULTSrrgrhrlrmr RenewableCertZ new_lineager)rXrrnew_namerrr$_r3r3r4obtain_and_enroll_certificates   z$Client.obtain_and_enroll_certificate)rjrr&cs4|jdur0dd|jDfdd|D}|SgS)NcSsg|]}|jdur|jjqS)N)rr)rHZproblemr3r3r4rKs z9Client._successful_domains_from_error..csg|]}|vr|qSr3r3)rHxfailed_domainsr3r4rKrL)Z subproblems)rXrjrrr3rr4rs  z%Client._successful_domains_from_error)rrr&cs6fdd|D}d|}td||S)Ncsg|]}|vr|qSr3r3rrr3r4rK rLz4Client._retry_obtain_certificate..z, zNUnable to obtain a certificate with every requested domain. Retrying without: )rU display_utilnotifyr)rXrrrZ domains_listr3rr4rs  z Client._retry_obtain_certificatecCsZd}|r|}n(t|dr.|ddd}n|d}||rD|St|rPdnddS)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.)rZis_wildcard_domain_is_valid_lineagenamerrk)rXrrZ 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 pathsepr\r3r3r4rHs zClient._is_valid_lineagename)cert_pem chain_pem cert_path chain_pathfullchain_pathr&c Cs|||fD]}ttj|d|jjq 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 irrr) rZmake_or_verify_dirr rdirnamer#r_open_pem_filewriteclose _save_chain) rXrrrrrrZ cert_fileZ abs_cert_path chain_fileZabs_chain_pathZfullchain_fileZabs_fullchain_pathr3r3r4save_certificateUs  zClient.save_certificate)r privkey_pathrrrr&c Cs|jdurtdtd|dur*dn tj|}t dd}t |j |V|D]4}|jj |tj|tj|||d|jqX|jdWdn1s0Yd}t |j||jWdn1s0YdS) 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)domainrrrrzDeployed ACME CertificatezuWe were unable to install your certificate, however, we successfully restored your server to its prior configuration.)rArgrjrrkr rabspathrrr ErrorHandler_recovery_routine_with_msgZ deploy_certrr_rollback_and_restartrestart)rXrrrrrrsdomr3r3r4deploy_certificatezs&       *zClient.deploy_certificateT)rrredirect_defaultr&c Cs|jdurtdtdd}dddd|fd f}|j}|D]Z\}}} t|j|} ||vr|d krt| durt|} | r|||| d }qB| rBtd |qBd } |rt |j | |j Wdn1s0YdS)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.rF)Zhstsensure-http-headerzStrict-Transport-Security)redirectrNZstaplez staple-ocsp)ZuirrzUpgrade-Insecure-RequestsrTzKOption %s is not supported by the selected installer. Skipping enhancement.z$We were unable to restart web server) rArgrjrrkZsupported_enhancementsrGr#apply_enhancementrrrr) rXrrrZenhancedZenhancement_infoZ supportedZ config_nameZenhancement_nameoptionZ config_valuersr3r3r4enhance_configs6     zClient.enhance_config)r enhancementoptionsr&c Cs|jstd|dkr|n|}t|jd|D]\}z|j|||Wq4tjylt d|Yq4tj yt d||Yq40q4|j d|Wdn1s0YdS)aApplies 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.rNzEnhancement %s was already set.z(Unable to set the %s enhancement for %s.zAdd enhancement ) rArrkrrrZenhanceZPluginEnhancementAlreadyPresentrgrhZ PluginErrorrjrr)rXrrrZ enh_labelrr3r3r4rs  zClient.apply_enhancement) success_msgr&cCs"|jr|j|rt|dS)zCalls the installer's recovery routine and prints success_msg :param str success_msg: message to show on successful recovery N)rAZrecovery_routinerrrXrr3r3r4rs z!Client._recovery_routine_with_msgcCsP|jrLtdz|j|jWntdYn0t|dS)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)rArgrhrollback_checkpointsrrjrrrr3r3r4rs  zClient._rollback_and_restart)N)N)N)T)N)*r^r_r`rarrcrrrqrZ AuthenticatorZ Installerr,r.rYrrrZ OrderResourcer bytesrrrbrrboolrrrrrkrrrrrrrrrrr3r3r3r4r{ s\  - o $  "   "  %  (  -   r{)privkeyr~r&cCs|jrt|jstd|r|jdkr`tjtjj |j }tj tjj |}t |j|d}|j r|t|j s|td|j r|jrt|j |jstddS)aValidate 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 keyZderrz#The provided CSR is not a valid CSRzThe key and CSR do not matchN)rrZ valid_privkeyrrkrOpenSSLZcryptoZload_certificate_requestZ FILETYPE_ASN1rZdump_certificate_requestZ FILETYPE_PEMrrrZ valid_csrZcsr_matches_pubkey)rr~Zcsr_objZ cert_bufferr3r3r4validate_key_csr s$     r)default_installer checkpointsr#pluginsr&cCs0tj|||dd}|dur,|||dS)aRevert 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_installerrr)rrr#rrAr3r3r4rollback:s  r)r# cli_arg_pathpem_pathr&cCsL||r&tj|dddtj|fSt|dd}|dtj|dfS)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 iwb)chmodmoder)Z set_by_userrZ safe_openr rrZ unique_file)r#rrZuniqr3r3r4rSs  r)rrr&cCs&z||W|n |0dS)zSaves 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)rr)rrr3r3r4rgs r)N)N)N)SrarZloggingr<typingrrrrrrrr Zcryptography.hazmat.backendsr Z-cryptography.hazmat.primitives.asymmetric.rsar Zjosepyror r rrrrtrr,rrrrrr7rrrZcertbot._internalrrrrrrrZcertbot._internal.pluginsrZ plugin_discorrZcertbot.compatr Zcertbot.displayr!ryrZcertbot.interfacesr"Z getLoggerr^rgrcZJWKZRegistrationResourcer.r5rbr-rCrPrdrqrurpr{rrrintZPluginsRegistryrrrrr3r3r3r4s                                          G 2.