a }|g4@s2dZddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd l mZdd lmZdd lmZddlmZddlZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z!ddlm"Z"ddl#Z#ddl#m$Z$ddl#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-dd l'm.Z.dd!l/m0Z1dd"l/m2Z3dd#l4m5Z5dd$l6m7Z8ddl6m&Z9dd%l:m;Z;edGe$j?ej@e e"jAejBd&d'd(ZCe$j?eDd)d*d+ZEe$j?eDd)d,d-ZFGd.d/d/ZGeDd0d1d2ZHdHe$j?e;e eeDgdfe e(jIejBfd3d4d5ZJejBe$j?e eeDgdfe"jAd6d7d8ZKGd9d:d:ZLdIe&jMe e&jNdd;dd?d@ZRe$j?eDeDe e eDfdAdBdCZSeTe ddDdEdFZUdS)JzCertbot client API.N)Any)Callable)cast)Dict)IO)List)Optional)Tuple)x509)default_backend) serialization)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)AccountStorage)configkeyregrreturncCs|jdkrL|j}|jdkr t}qP|jdkr0t}qP|jdkr@t}qPtdnt}t j ||||j t |d}t j |j|}t ||S)z Wrangle ACME client constructionZECii z6No matching signing algorithm can be found for the key)algrZ verify_ssl user_agent)typr&key_sizerrrrZNotSupportedErrorr acme_clientZ ClientNetworkZ no_verify_ssldetermine_user_agentClientV2Z get_directoryserver)r%r&r' public_keyr*net directoryr5{zua_flags..hook ) isinstance DummyConfigZ duplicateappendZrenew_by_defaultallow_subset_of_namesnoninteractive_modeanyjoin)r%flagsZ hook_namesZhooksr5rLr6rEms       rEc@s.eZdZdZddddZeedddZdS) rRz'Shim for computing a sample user agent.Nr(cCsd|_d|_d|_d|_dS)NZXXXZYYYZ SUBCOMMAND)rBrCr+rD)selfr5r5r6__init__szDummyConfig.__init__namer(cCsdS)z-Any config properties we might have are None.Nr5rZr]r5r5r6 __getattr__szDummyConfig.__getattr__)__name__ __module__ __qualname____doc__r[strrr_r5r5r5r6rRsrRrYcCstttjtS)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_allloggerinfor1emailZregister_unsafely_without_emailerrorrErrordry_rundebugr rsa_key_sizer joseZJWKRSAZComparableRSAKeyr7perform_registrationrAccountsaverZprepare_subscription) r%rgrhmsgZrsa_keyr&acmer'Zaccr5r5r6registers.&         rw)rvr%rhr(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_keyr4NzRServer requires external account binding. Please use --eab-kid and --eab-hmac-key.T)rkZterms_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_keyr3r&r2rZExternalAccountBindingZ from_datar4Zexternal_account_requiredrrmmetaZterms_of_serviceZ new_accountZNewRegistrationrkcoderU display_opsZ get_emailrr) rvr%rhZeab_credentials_suppliedrxZeabruZtoser5r5r6rrs8        rrc @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_authrCrvr(cCsv||_||_||_||_|dur>|jdur>t||jj|jj}||_||durlt ||j|j|jj |_nd|_dS)zInitialize a client.N) r%rrrCr7r&r'rvrZ AuthHandlerZ pref_challs)rZr%r~rrCrvr5r5r6r[szClient.__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)rrirlrrmrr'rvro_get_order_and_authorizationsdatadatetimeZnowZ timedeltar%Zissuance_timeoutZfinalize_orderZpreferred_chainZ fullchain_pemZalternative_fullchains_pemrZfind_chain_with_issuerrnZcert_and_chain_from_fullchainencode)rZrrruZdeadlineZ fullchaincertchainr5r5r6obtain_certificate_from_csr4s4          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|]}|jjjqSr5)body identifiervalue)rJar5r5r6 rNz,Client.obtain_certificate..csg|]}|vr|qSr5r5rJdZ auth_domainsr5r6rMrNz-Client.obtain_certificate..)%openreadrKeyrirjr%rprQrlistrZauth_chain_pathZauth_cert_pathkey_pathlowerrnrZmake_keyCSRacme_crypto_utilZmake_csrrZ must_stapleZ generate_keyrZ generate_csrrrrTrrm_successful_domains_from_errorlen_retry_obtain_certificateauthorizationsr)rZrrfZkeypathZkeypemr&r-rrrrlsuccessful_domainsauthzrrrr5rr6obtain_certificateas &           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)rvrrmZ new_order acme_errorsZWildcardUnsupportedErrorrr%rnZdeactivate_valid_authorizationsriroZwarningZhandle_authorizationsupdate)rZrrrZ deactivatedZfailedrr5r5r6rs"       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_DEFAULTSrrirjrnror RenewableCertZ new_lineager)rZrrnew_namerrr&_r5r5r6obtain_and_enroll_certificates   z$Client.obtain_and_enroll_certificate)rlrr(cs4|jdur0dd|jDfdd|D}|SgS)NcSsg|]}|jdur|jjqS)N)rr)rJZproblemr5r5r6rMs z9Client._successful_domains_from_error..csg|]}|vr|qSr5r5)rJxfailed_domainsr5r6rMrN)Z subproblems)rZrlrrr5rr6rs  z%Client._successful_domains_from_error)rrr(cs6fdd|D}d|}td||S)Ncsg|]}|vr|qSr5r5rrr5r6rM!rNz4Client._retry_obtain_certificate..z, zNUnable to obtain a certificate with every requested domain. Retrying without: )rW display_utilnotifyr)rZrrrZ domains_listr5rr6rs  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_lineagenamerrm)rZrrZ lineagenamer5r5r6r's zClient._choose_lineagenamer\cCs 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^r5r5r6rIs 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) rZrrrrrrZ cert_fileZ abs_cert_path chain_fileZabs_chain_pathZfullchain_fileZabs_fullchain_pathr5r5r6save_certificateVs  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.)rCrirlrrmr"rabspathrrr ErrorHandler_recovery_routine_with_msgZ deploy_certrt_rollback_and_restartrestart)rZrrrrrrudomr5r5r6deploy_certificate{s&       *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) rCrirlrrmZsupported_enhancementsrIr%apply_enhancementrrrr) rZrrrZenhancedZenhancement_infoZ supportedZ config_nameZenhancement_nameoptionZ config_valuerur5r5r6enhance_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 ) rCrrmrrrZenhanceZPluginEnhancementAlreadyPresentrirjZ PluginErrorrlrt)rZrrrZ enh_labelrr5r5r6rs  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)rCZrecovery_routinerrrZrr5r5r6rs 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)rCrirjrollback_checkpointsrrlrrrr5r5r6rs  zClient._rollback_and_restart)N)N)N)T)N)*r`rarbrcrrerrrsrZ AuthenticatorZ Installerr.r0r[rrrZ OrderResourcer bytesrrrdrrboolrrrrrmrrrrrrrrrrr5r5r5r6r}s\  - o $  "   "  %  (  -   r})privkeyrr(cCs|jrt|jstd|r|jdkrTt|j}| t j j }t |j|d}|jrpt|jsptd|jr|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_privkeyrrmrr Zload_der_x509_csrrZ public_bytesr ZEncodingZPEMrrrZ valid_csrZcsr_matches_pubkey)rrZcsr_objrr5r5r6validate_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%rrCr5r5r6rollback8s  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%rrZuniqr5r5r6rQs  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)rrr5r5r6res r)N)N)N)VrcrZloggingr>typingrrrrrrrr Z cryptographyr Zcryptography.hazmat.backendsr Zcryptography.hazmat.primitivesr Z-cryptography.hazmat.primitives.asymmetric.rsar Zjosepyrqrrrrrvrr.rrrrrr9rrrZcertbot._internalrrrrrrrZcertbot._internal.pluginsr Z plugin_discor!rZcertbot.compatr"Zcertbot.displayr#r{rZcertbot.interfacesr$Z getLoggerr`rireZJWKZRegistrationResourcer0r7rdr/rErRrfrsrwrrr}rrrintZPluginsRegistryrrrrr5r5r5r6s                                            G 2+