3 گā@sdZddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z ddlZdd lmZdd lmZddlZddlZddlmZddlmZddlmZddlmZddlZddlmZddlmZddlmZddlm Z ddlm!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.ddl/m0Z0ddl1m2Z3ddl1m!Z4dd l5m6Z6ej7e8Z9dBej:ej;e ej<ej=d!d"d#Z>ej:e?d$d%d&Z@ej:e?d$d'd(ZAGd)d*d*ZBe?d+d,d-ZCdCej:e6e ee?gdfe e#jDej=fd.d/d0ZEej=ej:e ee?gdfejZNeOe dd?d@dAZPdS)EzCertbot client API.N)cast)Any)Callable)Dict)IO)List)Optional)Tuple)Union)default_backend)generate_private_key)client) crypto_util)errors)messages) configuration) interfaces)util)account) auth_handler)cli) constants)eff) error_handler)storage)disco) selection)os)ops)AccountStorage)configkeyregrreturnc Csntj|||j t|d}tjBtjdttj|||j }|j dkrXt j d|j t tj|SQRXdS)z Wrangle ACME client construction)rZ verify_ssl user_agentignorezCertbot is configured to use an ACMEv1 server (%s). ACMEv1 support is deprecated and will soon be removed. See https://community.letsencrypt.org/t/143839 for more information.N) acme_clientZ ClientNetworkZ no_verify_ssldetermine_user_agentwarningscatch_warnings simplefilterDeprecationWarningBackwardsCompatibleClientV2serverZ acme_versionloggerwarningrClientV2)r r!r"netr r3/usr/lib/python3.6/client.pyacme_from_config_key0s    r5)r r#c Cs|jdkrzd}tjjddkr,d}d}d}ntj}tj}tj }|j t j |||j |j|jt|||jrrd|jnd }n|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` Nz\CertbotACMEClient/{0} ({1}; {2}{8}) Authenticator/{3} Installer/{4} ({5}; flags: {6}) Py/{7}Z CERTBOT_DOCS1certbotzOS_NAME OS_VERSIONzmajor.minor.patchlevelz; )r$renvirongetr cli_commandrZget_os_info_uaplatformpython_versionformatr7 __version__ authenticator installerverbua_flagsZuser_agent_comment)r Zuar;Zos_infor=r3r3r4r(Ds   r(csttrdSg}jr"|jdjr2|jdjrB|jdjrR|jdd}fd d |D}t|rz|jd dj|S)z@Turn some very important CLI flags into clues in the user agent.FLAGSdupZfrnZasnnprepostrenew manual_authmanual_cleanupcsg|]}t|dqS)Z_hook)getattr).0h)r r3r4 rszua_flags..hook )rGrHrIrJrK) isinstance DummyConfigZ duplicateappendZrenew_by_defaultallow_subset_of_namesnoninteractive_modeanyjoin)r flagsZ hook_namesZhooksr3)r r4rCds       rCc@s.eZdZdZddddZeedddZdS) rSz'Shim for computing a sample user agent.N)r#cCsd|_d|_d|_d|_dS)NZXXXZYYYZ SUBCOMMAND)r@rAr$rB)selfr3r3r4__init__zszDummyConfig.__init__)namer#cCsdS)z-Any config properties we might have are None.Nr3)rZr\r3r3r4 __getattr__szDummyConfig.__getattr__)__name__ __module__ __qualname____doc__r[strrr]r3r3r3r4rSxsrS)r#cCstttjtS)zd}tj|tj||j sNtj d|j rZd|_t d|j t d}tjtj|d}t||}t|||}tj||}|j||tj||||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_exponentkey_sizeZbackend)r!)Zfind_allr/infor.emailZregister_unsafely_without_emailerrorrErrordry_rundebugr rsa_key_sizer joseZJWKRSAZComparableRSAKeyr5perform_registrationrAccountsaverZprepare_subscription) r rerfmsgZrsa_keyr!acmer"Zaccr3r3r4registers,&          ru)rtr rfr#c Cs |jo |j}|r8|jjj}tjj||j|j|jd}nd}|j rV|sVd}t j |yJtj j|j |d}yttj|j||Stk rt j dYnXWnftj k r}zF|jd kr|jrd|j }t j |tjd d |_ t|||SWYdd}~XnXdS) 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_key directoryNzRServer requires external account binding. Please use --eab-kid and --eab-hmac-key.)riZexternal_account_bindingzNThe ACME client must be an instance of acme.client.BackwardsCompatibleClientV2 invalidEmailinvalidContactzzThe ACME server believes %s is an invalid email address. Please ensure it is a valid email and attempt registration again.T)Zinvalid)rxry)Zeab_kidZ eab_hmac_keyr2r!Z public_keyrZExternalAccountBindingZ from_datarwZexternal_account_requiredrrkZNewRegistrationrirr'r-Znew_account_and_tosAttributeErrorcoderV display_opsZ get_emailrp) rtr rfZeab_credentials_suppliedrvZeabrsZnewreger3r3r4rps:        rpc @seZdZdZd&ejeejee j ee j ee j ddddZd'ejeejeeefdddZd(eeeeeeeejejfd d d Zeeejd d dZeeeeeejdddZeeeeedddZeeeeeeeeefdddZ eeeeeeddddZ!d)eeeeddddZ"d*eeeee#eeefdddd Z$eedd!d"d#Z%edd!d$d%Z&dS)+ClientaCertbot'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.BackwardsCompatibleClientV2 acme: Optional ACME client API handle. You might already have one from `register`. N)r account_authrArtr#cCsv||_||_||_||_|dkr>|jdk r>t||jj|jj}||_||dk rltj ||j|j|jj |_nd|_dS)zInitialize a client.N) r rrrAr5r!r"rtrZ AuthHandlerZ pref_challs)rZr rrrArtr3r3r4r[szClient.__init__)csrorderrr#cCs |jdkr"d}tj|tj||jdks8|jjdkrBtjd|jdkrVtjdtjd||dkrz|j |j dd}t j j t j |jjd}tjd ||jj|||jjdk d }|j}|jjr|jrtj|g|j|jj|jj }tj|\}}|j|jfS) 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.zACME client is not set.zCSR: %sF) best_effort)Zsecondsz+Will poll for certificate issuance until %s)Zfetch_alternative_chains)rr/rjrrkrr"rtrm_get_order_and_authorizationsdatadatetimeZnowZ timedeltar Zissuance_timeoutZfinalize_orderZpreferred_chainZ fullchain_pemZalternative_fullchains_pemrZfind_chain_with_issuerrlZcert_and_chain_from_fullchainencode)rZrrrsZdeadlineZ fullchaincertchainr3r3r4obtain_certificate_from_csr0s.          z"Client.obtain_certificate_from_csr)domains old_keypathr#cs|dk rFt|d}|}|j}WdQRXtj||d}tjd|nd}|jj}d}t|jj t rt|jj d|j_ |jj r|jj dkr|jj }d|j_ d |j_ d |j_n |jjr|jj jd kr|jj}|jjr|ptjdtj|||jj d d}tjdd tj|j||jjd} nD|psz,Client.obtain_certificate..csg|]}|kr|qSr3r3)rMd) auth_domainsr3r4rOsz-Client.obtain_certificate..)'openreadrKeyr/rhr rnrRrlistrZauth_chain_pathZauth_cert_pathkey_pathlowerrlrZmake_keyCSRacme_crypto_utilZmake_csrrZ must_stapleZ generate_keyrrZ generate_csrZcsr_dirrrrUauthorizationssetrremoverobtain_certificater)rZrrfZkeypathZkeypemr!rgrrrauthzrZsuccessful_domainsrrr3)rr4r]s^         zClient.obtain_certificate)csr_pemrr#c Cs|jstjdy|jj|}Wn tjk r@tjdYnX|jsRtjd|r|jjr|jj |\}}|rt j d|jj|}|rt j d|jj ||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 zACME client is not set.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_authorizationsr/rmr0Zhandle_authorizationsupdate)rZrrrZ deactivatedZfailedrr3r3r4rs"       z$Client._get_order_and_authorizations)rcertnamer#cCs||j|\}}}}|jjtjdks6|jjtjdkr@tjd|j||}|jj rdtj d|dSt j 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)rr rrZ CLI_DEFAULTSrr/rh_choose_lineagenamerlrmr RenewableCertZ new_lineager)rZrrrrr!_new_namer3r3r4obtain_and_enroll_certificates  z$Client.obtain_and_enroll_certificatecCs.|r|Stj|dr&|dddS|dS)a/Chooses 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 rN)rZis_wildcard_domain)rZrrr3r3r4rs zClient._choose_lineagename)cert_pem chain_pem cert_path chain_pathfullchain_pathr#c Csx,|||fD]}tjtjj|d|jjq Wtd|\}}z|j|Wd|j Xtd|\} } td|\} } 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 irNrr) rZmake_or_verify_dirrpathdirnamer r_open_pem_filewriteclose _save_chain) rZrrrrrrZ cert_fileZ abs_cert_path chain_fileZabs_chain_pathZfullchain_fileZabs_fullchain_pathr3r3r4save_certificates  zClient.save_certificate)r privkey_pathrrrr#cCs|jdkrtjdtjd|dkr*dn tjj|}tj dd}t j |j |Px<|D]4}|jj |tjj|tjj|||d|jjqZW|jjdWdQRXd}t j |j||jjWdQRXdS) aInstall 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 chain_path: chain file path NzANo installer specified, client is unable to deploythe certificatezNo installer availablezDeploying certificatezCould not install certificate)ZdomainrrrrzDeployed ACME CertificatezuWe were unable to install your certificate, however, we successfully restored your server to its prior configuration.)rAr/rjrrkrrabspath display_utilnotifyr ErrorHandler_recovery_routine_with_msgZ deploy_certrr_rollback_and_restartrestart)rZrrrrrrsdomr3r3r4deploy_certificate9s$       zClient.deploy_certificateT)rrredirect_defaultr#c Cs|jdkrtjdtjdd}ddd d |fdf}|jj}xb|D]Z\}}} t|j|} ||kr|dkrv| dkrv|} | r|j||| d }qD| rDtjd|qDWd} |rt j |j | |jj WdQRXdS)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.zNo installer availableFhstsensure-http-headerStrict-Transport-SecurityredirectZstaplez staple-ocspuirUpgrade-Insecure-RequestsTzKOption %s is not supported by the selected installer. Skipping enhancement.z$We were unable to restart web server)rrr)rrN)rrr) rAr/rjrrkZsupported_enhancementsrLr apply_enhancementrrrr) rZrrrZenhancedZenhancement_infoZ supportedZ config_nameZenhancement_nameZoptionZ config_valuersr3r3r4enhance_config_s2      zClient.enhance_config)r enhancementoptionsr#cCs|jstjd|dkr|n|}tj|jdxh|D]`}y|jj|||Wq6tjk rptj d|Yq6tj k rtj d||Yq6Xq6W|jj d|WdQRXdS)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.zensure-http-headerNzEnhancement %s was already set.z(Unable to set the %s enhancement for %s.zAdd enhancement ) rArrkrrrZenhanceZPluginEnhancementAlreadyPresentr/rhZ PluginErrorrjrr)rZrrrZ enh_labelrr3r3r4rs   zClient.apply_enhancement) success_msgr#cCs"|jr|jj|rtj|dS)zCalls the installer's recovery routine and prints success_msg :param str success_msg: message to show on successful recovery N)rAZrecovery_routinerr)rZrr3r3r4rs z!Client._recovery_routine_with_msgc CsP|jrLtjdy|jj|jjWntjdYnXtj|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)rAr/rhrollback_checkpointsrrjrr)rZrr3r3r4rs  zClient._rollback_and_restart)N)N)N)T)N)'r^r_r`rarrcrrrqrZ AuthenticatorZ Installerr'r1r[rrrZ OrderResourcer bytesrrrbrrboolrrrrrrrrr rrrr3r3r3r4r~ s(4+]# "" &,* r~)privkeyrr#cCs|jrtj|j rtjd|r|jdkrbtjjtjj |j }tjj tjj |}t j|j|d}|j rtj|j  rtjd|j r|jrtj|j |jstjddS)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)rrZcsr_objZ cert_bufferr3r3r4validate_key_csrs      r)default_installer checkpointsr pluginsr#cCs0tj|||dd}|dk r,|j||jdS)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 rrAr3r3r4rollbacks  r) cli_arg_pathpem_pathr#cCsLtj|r&tj|dddtjj|fStj|dd}|dtjj|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)chmodmoderr&)rZ set_by_clirZ safe_openrrrZ unique_file)rrZuniqr3r3r4rs r)rrr#c Csz|j|Wd|jXdS)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)rrr3r3r4r$sr)N)N)N)QrarZloggingr<Ztypingrrrrrrrr r r)Zcryptography.hazmat.backendsr Z-cryptography.hazmat.primitives.asymmetric.rsar Zjosepyrorrtr r'rrrrrr7rrrZcertbot._internalrrrrrrrZcertbot._internal.pluginsrZ plugin_discorrZcertbot.compatrZcertbot.displayrr|rZcertbot.interfacesrZ getLoggerr^r/rcZJWKZRegistrationResourcer1r5rbr(rCrSrdrqrurpr~rrrintZPluginsRegistryrrrrr3r3r3r4sx                                    E 6C.