U
    eà–_ŒS  ã                   @   s²  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ e e ¡Z!ddddddddddddgZ"ddgZ#ddd d!gZ$e%e &e$e#e"d"¡ƒZ'd#d$„ Z(d%d&„ Z)d'd(„ Z*d)d*„ Z+d+d,„ Z,d-d.„ Z-d/d0„ Z.d1d2„ Z/d3d4„ Z0d5d6„ Z1d7d8„ Z2d9d:„ Z3d;d<„ Z4d=d>„ Z5dS )?zGFunctionality for autorenewal and associated juggling of configurationsé    )Úprint_functionN)ÚList)Úcli)Ú	constants)Úcrypto_util)Úerrors)Úhooks)Ú
interfaces)Ústorage)Úupdater)Úutil)Úos)ÚdiscoZ
config_dirZlogs_dirZwork_dirZ
user_agentÚserverZaccountÚauthenticatorÚ	installerÚ
renew_hookÚpre_hookÚ	post_hookZhttp01_addressZrsa_key_sizeÚhttp01_portZmust_stapleZallow_subset_of_namesÚ	reuse_keyZ	autorenew)Úpref_challsc              
   C   sX  zt  || ¡}W nF tjtfk
rV   tjddd t d|¡ t dt 	¡ ¡ Y dS X d|j
krrt d|¡ dS |j
d }d	|kr”t d
|¡ dS zt| |ƒ t| |ƒ W nR ttjfk
 rþ } z,t d|t|ƒ¡ t dt 	¡ ¡ W Y ¢dS d}~X Y nX zdd„ | ¡ D ƒ| _W n: tjk
rR } zt d||¡ W Y ¢dS d}~X Y nX |S )a•  Try 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

    Ú T)Úexc_infoz2Renewal configuration file %s is broken. Skipping.úTraceback was:
%sNÚrenewalparamsz<Renewal configuration file %s lacks renewalparams. Skipping.r   zJRenewal configuration file %s does not specify an authenticator. Skipping.zHAn error occurred while parsing %s. The error was %s. Skipping the file.c                 S   s   g | ]}t  |¡‘qS © )r   Zenforce_domain_sanity)Ú.0Údr   r   ú1/usr/lib/python3/dist-packages/certbot/renewal.pyÚ
<listcomp>]   s   ÿz!_reconstitute.<locals>.<listcomp>ztRenewal configuration file %s references a cert that contains an invalid domain name. The problem was: %s. Skipping.)r
   ZRenewableCertr   ZCertStorageErrorÚIOErrorÚloggerÚwarningÚdebugÚ	tracebackÚ
format_excÚconfigurationÚ restore_required_config_elementsÚ_restore_plugin_configsÚ
ValueErrorÚErrorÚstrÚnamesÚdomainsZConfigurationError)ÚconfigÚ	full_pathÚrenewal_candidater   Úerrorr   r   r   Ú_reconstitute/   sP    
ÿ
ÿ
 þÿ þr3   c                 C   sR   d|krt  d¡s|d | _d|krNt  d¡sN|d }t|tjƒrH|g}|| _dS )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_clir4   Ú
isinstanceÚsixÚstring_typesr5   )r/   r   Zwpr   r   r   Ú_restore_webroot_configh   s    
r:   c                 C   sÄ   g }|d dkrt | |ƒ n| |d ¡ | d¡dk	rF| |d ¡ t|ƒD ]p}| dd¡}t |¡D ]T\}}| |d ¡rht 	|¡sh|dkr¢t
| |t|ƒƒ qht |¡}t
| |||ƒƒ qhqNdS )a  Sets 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   Zwebrootr   Nú-Ú_)ÚNoneÚTrueÚFalse)r:   ÚappendÚgetÚsetÚreplacer8   Z	iteritemsÚ
startswithr   r6   ÚsetattrÚevalZargparse_type)r/   r   Zplugin_prefixesZplugin_prefixZconfig_itemZconfig_valueÚcastr   r   r   r)   y   s    
r)   c                 C   s„   t  dtfftj tt  t¡¡tj t	t  t
¡¡tj tt  t¡¡¡}|D ]4\}}||krJt |¡sJ|||| ƒ}t| ||ƒ qJdS )a  Sets 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)Ú	itertoolsÚchainÚ_restore_pref_challsr8   ZmovesÚzipÚBOOL_CONFIG_ITEMSÚrepeatÚ_restore_boolÚINT_CONFIG_ITEMSÚ_restore_intÚSTR_CONFIG_ITEMSÚ_restore_strr   r6   rE   )r/   r   Zrequired_itemsZ	item_nameZrestore_funcÚvaluer   r   r   r(   ¤   s    
ür(   c                 C   s    t |tjƒr|gn|}t |¡S )a˜  Restores 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 an bool

    )r7   r8   r9   r   Zparse_preferred_challenges)Zunused_namerS   r   r   r   rJ   ¹   s    rJ   c                 C   s*   |  ¡ }|dkr"t d | |¡¡‚|dkS )a%  Restores an 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 an bool

    )ÚtrueZfalsez,Expected True or False for {0} but found {1}rT   )Úlowerr   r+   Úformat)ÚnamerS   Zlowercase_valuer   r   r   rN   Ï   s    
ÿrN   c                 C   sX   | dkr$|dkr$t  d¡ t d¡S z
t|ƒW S  tk
rR   t d | ¡¡‚Y nX dS )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   r=   z!updating legacy http01_port valuez Expected a numeric value for {0}N)	r"   Úinfor   Úflag_defaultÚintr*   r   r+   rV   ©rW   rS   r   r   r   rP   â   s    


rP   c                 C   s@   | dkr0|t jkr0t dt jd |¡ t jd S |dkr<dS |S )zéRestores an string 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: str or None

    r   z$Using server %s instead of legacy %sr=   N)r   ZV1_URIr"   rX   ZCLI_DEFAULTSr[   r   r   r   rR   ø   s     ÿ
rR   c                 C   sL   | j rt d¡ dS | ¡ r*t d¡ dS | jr>t d¡ dS t d¡ dS )zDReturn true if any of the circumstances for automatic renewal apply.z+Auto-renewal forced with --force-renewal...Tz)Cert is due for renewal, auto-renewing...z<Cert not due for renewal, but simulating renewal for dry runzCert not yet due for renewalF)Zrenew_by_defaultr"   r$   Zshould_autorenewrX   Údry_run)r/   Úlineager   r   r   Úshould_renew  s    



r^   c              	   C   s†   t |jƒ}| ¡ }W 5 Q R X tj tjj|¡}dt| ¡ ƒ 	¡ k}t
 | j¡r‚t
 |¡r^|r‚| js‚d | ¡ ¡}t d |¡¡‚dS )z9Do not renew a valid cert with one from a staging server!Zfakez, z¡You'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)ÚopenÚcertÚreadÚOpenSSLZcryptoZload_certificateZFILETYPE_PEMÚreprZ
get_issuerrU   r   Z
is_stagingr   Zbreak_my_certsÚjoinr-   r   r+   rV   )r/   r]   Úoriginal_serverZthe_fileÚcontentsZlatest_certZ	now_validr-   r   r   r   Ú_avoid_invalidating_lineage   s      ÿþÿrg   c                 C   s¼   |j d }| dt d¡¡}t| ||ƒ |s4| ¡ }| jrHtj 	|j
¡nd}| ||¡\}}}}	| jr~t dtj |j¡¡ n*| ¡ }
| |
||j|| ¡ | | ¡ ¡ t | ||j¡ dS )zRenew a certificate lineage.r   r   Nz(Dry run: skipping updating lineage at %s)r'   rA   r   rY   rg   r-   r   r   ÚpathÚnormpathZprivkeyZobtain_certificater\   r"   r$   Údirnamer`   Úlatest_common_versionZsave_successorZpemZupdate_all_links_tor   r   Zlive_dir)r/   r.   Z	le_clientr]   Zrenewal_paramsre   Znew_keyZnew_certZ	new_chainr<   Zprior_versionr   r   r   Ú
renew_cert6  s    
ÿrl   c                    s    ‡ fdd„| D ƒ}dd  |¡ S )z:Format a results report for a category of renewal outcomesc                 3   s   | ]}d |ˆ f V  qdS )z%s (%s)Nr   )r   Úm©Úcategoryr   r   Ú	<genexpr>O  s     zreport.<locals>.<genexpr>z  z
  )rd   )Zmsgsro   Úlinesr   rn   r   ÚreportM  s    rr   c                    s\  g }|j ‰ tj tj¡}‡ fdd„}| jr:ˆ dƒ ˆ dƒ ˆ dƒ |r\ˆ dƒ ˆ t|dƒƒ |s”|s”ˆ dƒ | jd k	sŠ| j	d k	sŠ| j
d k	r’ˆ d	ƒ n||r´|s´ˆ d
ƒ ˆ t|dƒƒ n\|rÔ|sÔ|dƒ |t|dƒƒ n<|r|rˆ dƒ ˆ t|dƒd ƒ |dƒ |t|dƒƒ |r,ˆ dƒ ˆ t|dƒƒ | jrDˆ dƒ ˆ dƒ |jd |¡dd d S )Nc                    s   ˆ t | ƒƒ t | ¡ dS )zNotify and log errors.N)r,   r"   r2   )Úerr©Znotifyr   r   Únotify_errorY  s    z-_renew_describe_results.<locals>.notify_errorz;** DRY RUN: simulating 'certbot renew' close to cert expiryz>**          (The test certificates below have not been saved.)r   z0The following certs are not due for renewal yet:ZskippedzNo renewals were attempted.zNo hooks were run.zOCongratulations, all renewals succeeded. The following certs have been renewed:ZsuccesszFAll renewal attempts failed. The following certs could not be renewed:Zfailurez.The following certs were successfully renewed:Ú
z)The following certs could not be renewed:zB
Additionally, the following renewal configurations were invalid: Z	parsefailz>**          (The test certificates above have not been saved.)F)Zwrap)r@   ÚzopeÚ	componentÚ
getUtilityr	   ÚIDisplayr\   rr   r   r   r   Únotificationrd   )r/   Úrenew_successesÚrenew_failuresÚrenew_skippedÚparse_failuresÚoutÚdispru   r   rt   r   Ú_renew_describe_resultsR  sJ    
ÿÿ
r‚   c                    sz  t ‡ fdd„ˆ jD ƒƒr"t d¡‚ˆ jr:t ˆ ˆ j¡g}n
t ˆ ¡}g }g }g }g }tj	 
¡  odˆ j}|D ]Æ}tj tj¡}|jd| dd t ˆ ¡}	t |¡}
zt|	|ƒ}W nV tk
r } z6t d||
|¡ t dt ¡ ¡ | |¡ W Y ¢qjW 5 d	}~X Y nX zÖ|d	kr"| |¡ n¼tj |	¡ | ¡  d
dlm } t!j" #¡ }t$|	|ƒr |r„t% &dd¡}t 'd|¡ t( )|¡ d}| *|	||¡ | |j+¡ n0t, -| .d| /¡ ¡¡}| d|j+| 0d¡f ¡ t1 2|	||¡ W qj tk
r0 } z0t d|
||¡ t dt ¡ ¡ | |j+¡ W 5 d	}~X Y qjX qjt3ˆ ||||ƒ |sP|rlt d 4t5|ƒt5|ƒ¡¡‚n
t d¡ d	S )z5Examine each lineage; renew if due and report resultsc                 3   s   | ]}|ˆ j kV  qd S )N)r4   )r   Zdomain©r/   r   r   rp   ˆ  s     z)handle_renewal_request.<locals>.<genexpr>af  Currently, 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.r   Nr   )Úmainé   ià  z3Non-interactive renewal: random delay of %s secondsr`   z%s expires on %sz%Y-%m-%dzQAttempting to renew cert (%s) from %s produced an unexpected error: %s. Skipping.z*{0} renew failure(s), {1} parse failure(s)zno renewal failures)6Úanyr.   r   r+   Zcertnamer
   Zrenewal_file_for_certnameZrenewal_conf_filesÚsysÚstdinÚisattyZrandom_sleep_on_renewrw   rx   ry   r	   rz   r{   ÚcopyÚdeepcopyZlineagename_for_filenamer3   Ú	Exceptionr"   r#   r$   r%   r&   r@   ZprovideUtilityZensure_deployedÚcertbotr…   Úplugins_discoZPluginsRegistryZfind_allr^   ÚrandomZuniformrX   ÚtimeÚsleeprl   Z	fullchainr   ZnotAfterÚversionrk   Ústrftimer   Zrun_generic_updatersr‚   rV   Úlen)r/   Z
conf_filesr|   r}   r~   r   Zapply_random_sleepZrenewal_filer   Zlineage_configZlineagenamer1   Úer…   ZpluginsZ
sleep_timeZexpiryr   rƒ   r   Úhandle_renewal_request„  sŽ    




  þ


ÿ
 ÿ
ÿÿ þ  ÿ ÿr—   )6Ú__doc__Z
__future__r   r‹   rH   Zloggingr   rˆ   r‘   r%   rb   r8   Zzope.componentrw   Zacme.magic_typingr   rŽ   r   r   r   r   r   r	   r
   r   r   Zcertbot.compatr   Zcertbot.pluginsr   r   Z	getLoggerÚ__name__r"   rQ   rO   rL   rB   rI   ZCONFIG_ITEMSr3   r:   r)   r(   rJ   rN   rP   rR   r^   rg   rl   rr   r‚   r—   r   r   r   r   Ú<module>   st   
      þÿ   ÿ9+2