3 گa\@svdZddlZddlZddlZddlZddlZddlZddlZddlm Z ddlm Z ddlm Z ddlm Z ddlm Z ddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddl&m'Z(ddl)m*Z+ddl,m-Z-ddl.mZ/ej0e1Z2ddddd d!d"d#d$d%d&d'd(d)d*gZ3d+d,gZ4d-d.d/d0gZ5e6ej7e5e4e3d^Z8ej9e:ee$j;d2d3d4Zej9e e:e fdd5d:d;Z?e e:e fe e:e fd<d=d>Z@e:ee e:e:fe e:d?d@dAZAe:e:eBdBdCdDZCe:e:eDdBdEdFZEe:e:ee:dBdGdHZFej9e$j;eBdIdJdKZGej9e$j;e:ddLdMdNZHej9ee e:e!jIe$j;ddOdPdQZJe e:e:e:dRdSdTZKej9e e:e e:e e:e e:ddUdVdWZLej9ddXdYdZZMe:ej9dd[d\d]ZNdS)_zGFunctionality for autorenewal and associated juggling of configurationsN)Any)Dict)Iterable)List)Mapping)Optional)Union)default_backend)ec)rsa)load_pem_private_key) configuration) crypto_util)errors) interfaces)util)cli)client) constants)hooks)storage)updater)obj)disco)osZ config_dirZlogs_dirZwork_dirZ user_agentserverZaccount authenticator installer renew_hookpre_hook post_hookZhttp01_addressZpreferred_chainkey_typeelliptic_curve rsa_key_size http01_portZ must_stapleZallow_subset_of_names reuse_keyZ autorenew pref_challs)config full_pathreturnc,Cs\ytj||}WnRtjtfk rb}z0tjd|tjdt|tjdt j dSd}~XnXd|j kr~tjd|dS|j d}d|krtjd|dSt |}yt ||t||WnJttjfk r }z&tjd |t|tjdt j dSd}~XnXyd d |jD|_Wn2tjk rV}ztjd ||dSd}~XnX|S) aTry to instantiate a RenewableCert, updating config with relevant items. This is specifically for use in renewal and enforces several checks and policies to ensure that we can try to proceed with the renewal request. The config argument is modified by including relevant options read from the renewal configuration file. :param configuration.NamespaceConfig config: configuration for the current lineage :param str full_path: Absolute path to the configuration file that defines this lineage :returns: the RenewableCert object or None if a fatal error occurred :rtype: `storage.RenewableCert` or NoneType z(Renewal configuration file %s is broken.zThe error was: %s Skipping.zTraceback was: %sN renewalparamszjsz!_reconstitute..z{Renewal configuration file %s references a certificate that contains an invalid domain name. The problem was: %s. Skipping.)r RenewableCertrZCertStorageErrorIOErrorloggererrorstrdebug traceback format_excr "_remove_deprecated_config_elements restore_required_config_elements_restore_plugin_configs ValueErrorErrornamesdomainsZConfigurationError)r'r(renewal_candidater3r*r+r+r. _reconstitute:sD     r@)r'r*r)cCsTd|krtjd r|d|_d|krPtjd rP|d}t|trJ|g}||_dS)z webroot_map is, uniquely, a dict, and the general-purpose configuration restoring logic is not able to correctly parse it from the serialized form. webroot_map webroot_pathN)r set_by_clirA isinstancer4rB)r'r*Zwpr+r+r._restore_webroot_configus  rEcCsg}|ddkrt||n|j|d|jddk rF|j|dxt|D]t}|jdd}xb|jD]V\}}|j|drjtj| rj|d krt ||t |qjtj |}t ||||qjWqPWdS) aSets plugin specific values in config from renewalparams :param configuration.NamespaceConfig config: configuration for the current lineage :param configobj.Section renewalparams: Parameters from the renewal configuration file that defines this lineage rZwebrootrN-_NoneTrueFalse)rHrIrJ) rEappendgetsetreplaceitems startswithrrCsetattrevalZ argparse_type)r'r*Zplugin_prefixesZ plugin_prefixZ config_itemZ config_valuecastr+r+r.r:s    r:cCstjdtfftttjttttjttt tjt }x@|D]8\}}||kr@t j | r@||||}t |j||q@WdS)aSets non-plugin specific values in config from renewalparams :param configuration.NamespaceConfig config: configuration for the current lineage :param configobj.Section renewalparams: parameters from the renewal configuration file that defines this lineage r&N) itertoolschain_restore_pref_challszipBOOL_CONFIG_ITEMSrepeat _restore_boolINT_CONFIG_ITEMS _restore_intSTR_CONFIG_ITEMS _restore_strrrCrQ namespace)r'r*Zrequired_itemsZ item_nameZ restore_funcvaluer+r+r.r9s r9)r*r)cCsdd|jDS)zRemoves deprecated config options from the parsed renewalparams. :param dict renewalparams: list of parsed renewalparams :returns: list of renewalparams with deprecated config options removed :rtype: dict cSs i|]\}}|tjkr||qSr+)rZDEPRECATED_OPTIONS)r,Z option_namevr+r+r. sz6_remove_deprecated_config_elements..)rO)r*r+r+r.r8s r8) unused_namer`r)cCst|tr|gn|}tj|S)aRestores preferred challenges from a renewal config file. If value is a `str`, it should be a single challenge type. :param str unused_name: option name :param value: option value :type value: `list` of `str` or `str` :returns: converted option value to be stored in the runtime config :rtype: `list` of `str` :raises errors.Error: if value can't be converted to a bool )rDr4rZparse_preferred_challenges)rcr`r+r+r.rVsrV)namer`r)cCs*|j}|dkr"tjdj|||dkS)a#Restores a boolean key-value pair from a renewal config file. :param str name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: bool :raises errors.Error: if value can't be converted to a bool truefalsez,Expected True or False for {0} but found {1})rerf)lowerrr<format)rdr`Zlowercase_valuer+r+r.rZs rZc CsV|dkr$|dkr$tjdtjdSyt|Stk rPtjdj|YnXdS)a#Restores an integer key-value pair from a renewal config file. :param str name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: int :raises errors.Error: if value can't be converted to an int r$rHz!updating legacy http01_port valuez Expected a numeric value for {0}N) r2infor flag_defaultintr;rr<rh)rdr`r+r+r.r\s   r\cCs@|dkr0|tjkr0tjdtjd|tjdS|dkrtjddStjddS)zDReturn true if any of the circumstances for automatic renewal apply.z+Auto-renewal forced with --force-renewal...Tz0Certificate is due for renewal, auto-renewing...zCCertificate not due for renewal, but simulating renewal for dry runz#Certificate not yet due for renewalF)Zrenew_by_defaultr2r5Zshould_autorenewridry_run display_utilnotify)r'rlr+r+r. should_renew.s    rp)r'rloriginal_serverr)cCs>tj|jr:tj|s:|js:dj|j}tjdj|dS)z9Do not renew a valid cert with one from a staging server!z, zYou've asked to renew/replace a seemingly valid certificate with a test certificate (domains: {0}). We will not do that unless you use the --break-my-certs flag!N) rZ is_stagingrZbreak_my_certsjoinr=rr<rh)r'rlrqr=r+r+r._avoid_invalidating_lineage=s  rs)r'r> le_clientrlr)c Cs|jd}|jdtjd}t||||s4|j}|jrTtjj |j }t ||nd}|j ||\}}}} |j rtjdtjj|jn*|j} |j| ||j|||j|jtj|||jdS)zRenew a certificate lineage.r*rNz(Dry run: skipping updating lineage at %s)r rLrrjrsr=r%rpathnormpathZprivkey_update_renewal_params_from_keyZobtain_certificatermr2r5dirnamecertlatest_common_versionZsave_successorZpemZupdate_all_links_torrZlive_dir) r'r>rtrlZrenewal_paramsrqZnew_keyZnew_certZ new_chainrGZ prior_versionr+r+r. renew_certJs    r{)msgscategoryr)cs fdd|D}ddj|S)z:Format a results report for a category of renewal outcomesc3s|]}d|fVqdS)z%s (%s)Nr+)r,m)r}r+r. gszreport..z z )rr)r|r}linesr+)r}r.reportesr)r'renew_successesrenew_failures renew_skippedparse_failuresr)cCsDtj}tj}|djtj|jr&dnd}|rD|d|t|d| r| r|dj|d|j dk s~|j dk s~|j dk r|d n|r| r|d j|d|t|d nh|r| r|d ||t|d nD|o|r|dj|d|t|d d|d||t|d |r6|d|t|d|tjdS)a Print a report to the terminal about the results of the renewal process. :param configuration.NamespaceConfiguration config: Configuration :param list renew_successes: list of fullchain paths which were renewed :param list renew_failures: list of fullchain paths which failed to be renewed :param list renew_skipped: list of messages to print about skipped certificates :param list parse_failures: list of renewal parameter paths which had errors z {}zsimulated renewalrenewalz7The following certificates are not due for renewal yet:ZskippedzNo {renewal}s were attempted.)rNzNo hooks were run.z+Congratulations, all {renewal}s succeeded: successz@All %ss failed. The following certificates could not be renewed:Zfailurez#The following {renewal}s succeeded: zThe following %ss failed:zB Additionally, the following renewal configurations were invalid: Z parsefail) rnror2r3rh display_objZ SIDE_FRAMErmrrrr )r'rrrrroZ notify_errorZ renewal_nounr+r+r._renew_describe_resultsks8        r)r'r)csltfddjDr"tjdjr:tjjg}n tj}g}g}g}g}tj j odj }x|D]}t j d|ddtj}tj|} yt||} WnNtk r} z2tjd|| | tjdtj|j|wnWYd d } ~ XnXy| s |j|ntjj|tj| jd d lm } t!j"j#} t$|| r|rrt%j&d d}tj'd|t(j)|d}| j*|| | |j| j+n0t,j-| j.d| j/}|jd| j+|j0dft1j2|| | Wqntk r"} z6tjd| | tjdtj| r|j| j+WYd d } ~ XqnXqnWt3|||||sD|r^tjdj4t5|t5|tjdd S)z5Examine each lineage; renew if due and report resultsc3s|]}|jkVqdS)N)rA)r,Zdomain)r'r+r.rsz)handle_renewal_request..afCurrently, the renew verb is capable of either renewing all installed certificates that are due to be renewed or renewing a single certificate specified by its name. If you would like to renew specific certificates by their domains, use the certonly command instead. The renew verb may provide other options for selecting certificates to renew in the future.z Processing F)pausezTRenewal configuration file %s (cert: %s) produced an unexpected error: %s. Skipping.zTraceback was: %sNr)main<z3Non-interactive renewal: random delay of %s secondsryz%s expires on %sz%Y-%m-%dz-Failed to renew certificate %s with error: %sz*{0} renew failure(s), {1} parse failure(s)zno renewal failuresi)6anyr>rr<ZcertnamerZrenewal_file_for_certnameZrenewal_conf_filessysstdinisattyZrandom_sleep_on_renewrnZ notificationcopydeepcopyZlineagename_for_filenamer@ Exceptionr2r3r5r6r7rKzopeZ componentZprovideUtilityrZIConfigZensure_deployedcertbot._internalr plugins_discoZPluginsRegistryZfind_allrprandomZuniformritimeZsleepr{Z fullchainrZnotAfterversionrzZstrftimerZrun_generic_updatersrrhlen)r'Z conf_filesrrrrZapply_random_sleepZ renewal_fileZlineage_configZ lineagenamer?erZpluginsZ sleep_timeZexpiryr+)r'r.handle_renewal_requestsr              " r)key_pathr'r)c Cs~t|d}t|jdtd}WdQRXt|tjrFd|_|j|_ n4t|t j rdd|_|j j |_ntjdj|t|dS)Nrb)ZpasswordZbackendr Zecdsaz*Key at {0} is of an unsupported type: {1}.)openr readr rDr Z RSAPrivateKeyr!Zkey_sizer#r ZEllipticCurvePrivateKeyZcurverdr"rr<rhtype)rr'Zfile_hkeyr+r+r.rws     rw)r&)O__doc__rrTZloggingrrrr6ZtypingrrrrrrrZcryptography.hazmat.backendsr Z)cryptography.hazmat.primitives.asymmetricr r Z,cryptography.hazmat.primitives.serializationr Zzope.componentrZcertbotr rrrrrrrrrrrZcertbot._internal.displayrrZcertbot._internal.pluginsrrZcertbot.compatrZcertbot.displayrnZ getLogger__name__r2r]r[rXrMrUZ CONFIG_ITEMSZNamespaceConfigr4r0r@rEr:r9r8rVboolrZrkr\r^rprsZClientr{rrrrwr+r+r+r.s                            :+ "   .l