a
    á `[  ã                   @   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
mZ ddlmZmZ ddlm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$ ddlm%Z% ddl&m'Z( ddl)m*Z* e +e,¡Z-g d¢Z.ddgZ/g d¢Z0e1e 2e0e/e.d¡ƒZ3dd„ Z4dd„ Z5dd„ Z6d d!„ Z7d"d#„ Z8d$d%„ Z9d&d'„ Z:d(d)„ Z;d*d+„ Z<d,d-„ Z=d.d/„ Z>d0d1„ Z?d2d3„ Z@d4d5„ ZAd6d7„ ZBd8d9„ ZCdS ):zGFunctionality for autorenewal and associated juggling of configurationsé    )Úprint_functionN)Údefault_backend)ÚecÚrsa)Úload_pem_private_key)ÚList)ÚOptional)Úcrypto_util)Úutil)Úerrors)Ú
interfaces)Úcli)Úclient)Ú	constants)Úhooks)Ústorage)Úupdater)Údisco)Úos)Z
config_dirZlogs_dirZwork_dirZ
user_agentÚserverZaccountÚauthenticatorÚ	installerÚ
renew_hookÚpre_hookÚ	post_hookZhttp01_addressZpreferred_chainÚkey_typeÚelliptic_curveÚrsa_key_sizeÚhttp01_port)Zmust_stapleZallow_subset_of_namesÚ	reuse_keyZ	autorenew)Úpref_challsc              
   C   sZ  zt  || ¡}W nD tjtfyT   tjddd t d|¡ t dt 	¡ ¡ Y dS 0 d|j
vrpt d|¡ dS |j
d }d	|vr’t d
|¡ dS t|ƒ}zt| |ƒ t| |ƒ W nP ttjfy } z0t d|t|ƒ¡ t dt 	¡ ¡ W Y d}~dS d}~0 0 zdd„ | ¡ D ƒ| _W n8 tjyT } zt d||¡ W Y d}~dS d}~0 0 |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%   ú;/usr/lib/python3/dist-packages/certbot/_internal/renewal.pyÚ
<listcomp>d   s   ÿz!_reconstitute.<locals>.<listcomp>z{Renewal configuration file %s references a certificate that contains an invalid domain name. The problem was: %s. Skipping.)r   ZRenewableCertr   ZCertStorageErrorÚIOErrorÚloggerÚwarningÚdebugÚ	tracebackÚ
format_excÚconfigurationÚ"_remove_deprecated_config_elementsÚ restore_required_config_elementsÚ_restore_plugin_configsÚ
ValueErrorÚErrorÚstrÚnamesÚdomainsZConfigurationError)ÚconfigÚ	full_pathÚrenewal_candidater$   Úerrorr%   r%   r(   Ú_reconstitute5   sN    
ÿ
ÿ
þÿþr=   c                 C   sR   d|v rt  d¡s|d | _d|v 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_clir>   Ú
isinstanceÚsixÚstring_typesr?   )r9   r$   Zwpr%   r%   r(   Ú_restore_webroot_configo   s    
rD   c                 C   sÄ   g }|d dkrt | |ƒ n| |d ¡ | d¡durF| |d ¡ t|ƒD ]p}| dd¡}t |¡D ]T\}}| |d ¡rht 	|¡sh|dv 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)rD   ÚappendÚgetÚsetÚreplacerB   Z	iteritemsÚ
startswithr   r@   ÚsetattrÚevalZargparse_type)r9   r$   Zplugin_prefixesZplugin_prefixZconfig_itemZconfig_valueÚcastr%   r%   r(   r3   €   s    
r3   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\}}||v 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_challsrB   ZmovesÚzipÚBOOL_CONFIG_ITEMSÚrepeatÚ_restore_boolÚINT_CONFIG_ITEMSÚ_restore_intÚSTR_CONFIG_ITEMSÚ_restore_strr   r@   rO   )r9   r$   Zrequired_itemsZ	item_nameZrestore_funcÚvaluer%   r%   r(   r2   «   s    
ür2   c                 C   s   dd„ |   ¡ D ƒS )zàRemoves 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

    c                 S   s    i | ]\}}|t jvr||“qS r%   )r   ZDEPRECATED_OPTIONS)r&   Zoption_nameÚvr%   r%   r(   Ú
<dictcomp>É   s   
ÿz6_remove_deprecated_config_elements.<locals>.<dictcomp>)Úitems)r$   r%   r%   r(   r1   À   s    	r1   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 a bool

    )rA   rB   rC   r   Zparse_preferred_challenges)Zunused_namer]   r%   r%   r(   rT   Í   s    rT   c                 C   s*   |  ¡ }|dvr"t d | |¡¡‚|dkS )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

    )ÚtrueZfalsez,Expected True or False for {0} but found {1}ra   )Úlowerr   r5   Úformat)Únamer]   Zlowercase_valuer%   r%   r(   rX   ã   s    
ÿrX   c                 C   sV   | dkr$|dkr$t  d¡ t d¡S z
t|ƒW S  tyP   t d | ¡¡‚Y n0 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   rG   z!updating legacy http01_port valuez Expected a numeric value for {0}N)	r+   Úinfor   Úflag_defaultÚintr4   r   r5   rc   ©rd   r]   r%   r%   r(   rZ   ö   s    


rZ   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 a 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 %srG   N)r   ZV1_URIr+   re   ZCLI_DEFAULTSrh   r%   r%   r(   r\     s    
ÿ
r\   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_autorenewre   Údry_run)r9   Úlineager%   r%   r(   Úshould_renew%  s    



rk   c                 C   sš   t |jƒ}| ¡ }W d  ƒ n1 s(0    Y  tj tjj|¡}dt| ¡ ƒ 	¡ v}t
 | j¡r–t
 |¡rr|r–| js–d | ¡ ¡}t d |¡¡‚dS )z9Do not renew a valid cert with one from a staging server!NZ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!)ÚopenÚcertÚreadÚOpenSSLZcryptoZload_certificateZFILETYPE_PEMÚreprZ
get_issuerrb   r
   Z
is_stagingr   Zbreak_my_certsÚjoinr7   r   r5   rc   )r9   rj   Úoriginal_serverZthe_fileÚcontentsZlatest_certZ	now_validr7   r%   r%   r(   Ú_avoid_invalidating_lineage4  s    &ÿþÿrt   c                 C   sÈ   |j d }| dt d¡¡}t| ||ƒ |s4| ¡ }| jrTtj 	|j
¡}t|| ƒ 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)r0   rK   r   rf   rt   r7   r   r   ÚpathÚnormpathZprivkeyÚ_update_renewal_params_from_keyZobtain_certificateri   r+   r-   Údirnamerm   Úlatest_common_versionZsave_successorZpemZupdate_all_links_tor   r   Zlive_dir)r9   r8   Z	le_clientrj   Zrenewal_paramsrr   Znew_keyZnew_certZ	new_chainrF   Zprior_versionr%   r%   r(   Ú
renew_certJ  s     
rz   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>g  ó    zreport.<locals>.<genexpr>z  z
  )rq   )Zmsgsr}   Úlinesr%   r|   r(   Úreporte  s    r   c                 C   s>  t j}tj}|d t j¡ƒ | jr&dnd}|rD|dƒ |t|dƒƒ |s„|s„|dj|dƒ | jdusz| j	dusz| j
dur‚|d	ƒ n|r¬|s¬|d
j|dƒ |t|dƒƒ nh|rÎ|sÎ|d|ƒ |t|dƒƒ nF|r|r|dj|dƒ |t|dƒd ƒ |d|ƒ |t|dƒƒ |r0|dƒ |t|dƒƒ |t jƒ dS )aË  
    Print a report to the terminal about the results of the renewal process.

    :param interfaces.IConfig 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 erorrs
    z
{}zsimulated renewalÚrenewalz7The following certificates are not due for renewal yet:ZskippedzNo {renewal}s were attempted.)r‚   NzNo hooks were run.z+Congratulations, all {renewal}s succeeded: Zsuccessz@All %ss failed. The following certificates could not be renewed:Zfailurez#The following {renewal}s succeeded:Ú
zThe following %ss failed:zB
Additionally, the following renewal configurations were invalid: Z	parsefail)Údisplay_utilÚnotifyr+   r<   rc   Z
SIDE_FRAMEri   r   r   r   r   )r9   Úrenew_successesÚrenew_failuresÚrenew_skippedÚparse_failuresr…   Znotify_errorZrenewal_nounr%   r%   r(   Ú_renew_describe_resultsk  s@    
ÿÿ
ÿ
rŠ   c                    s~  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 n\ ty } zBt d||
|¡ t dt ¡ ¡ | |¡ W Y d	}~qjW Y d	}~n
d	}~0 0 zÖ|d	u 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y6 } z6t 3d|
|¡ t dt ¡ ¡ | |j+¡ W Y d	}~qjd	}~0 0 qjt4ˆ ||||ƒ |sV|rpt d 5t6|ƒt6|ƒ¡¡‚t d¡ d	S )z5Examine each lineage; renew if due and report resultsc                 3   s   | ]}|ˆ j vV  qd S )N)r>   )r&   Zdomain©r9   r%   r(   r~   Ÿ  r   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 secondsrm   z%s expires on %sz%Y-%m-%dz-Failed to renew certificate %s with error: %sz*{0} renew failure(s), {1} parse failure(s)zno renewal failures)7Úanyr8   r   r5   Zcertnamer   Zrenewal_file_for_certnameZrenewal_conf_filesÚsysÚstdinÚisattyZrandom_sleep_on_renewÚzopeZ	componentZ
getUtilityr   ZIDisplayZnotificationÚcopyÚdeepcopyZlineagename_for_filenamer=   Ú	Exceptionr+   r,   r-   r.   r/   rJ   ZprovideUtilityZensure_deployedÚcertbot._internalr   Úplugins_discoZPluginsRegistryZfind_allrk   ÚrandomZuniformre   ÚtimeÚsleeprz   Z	fullchainr	   ZnotAfterÚversionry   Ústrftimer   Zrun_generic_updatersr<   rŠ   rc   Úlen)r9   Z
conf_filesr†   r‡   rˆ   r‰   Zapply_random_sleepZrenewal_fileZdispZlineage_configZlineagenamer;   Úer   ZpluginsZ
sleep_timeZexpiryr%   r‹   r(   Úhandle_renewal_request›  s‚    




þ
"

ÿ
ÿ
ÿÿþ$ÿÿr    c                 C   s’   t | dƒ$}t| ¡ d tƒ d}W d   ƒ n1 s40    Y  t|tjƒrZd|_|j|_	n4t|t
jƒrxd|_|jj|_nt d | t|ƒ¡¡‚d S )NÚrb)ZpasswordZbackendr   Zecdsaz*Key at {0} is of an unsupported type: {1}.)rl   r   rn   r   rA   r   ZRSAPrivateKeyr   Zkey_sizer   r   ZEllipticCurvePrivateKeyZcurverd   r   r   r5   rc   Útype)Zkey_pathr9   Zfile_hÚkeyr%   r%   r(   rw     s    2
rw   )DÚ__doc__Z
__future__r   r”   rR   Zloggingr™   r   rš   r.   Zcryptography.hazmat.backendsr   Z)cryptography.hazmat.primitives.asymmetricr   r   Z,cryptography.hazmat.primitives.serializationr   ro   rB   Zzope.componentr“   Zacme.magic_typingr   r   Zcertbotr	   Zcertbot.displayr
   r„   r   r   r—   r   r   r   r   r   r   Zcertbot._internal.pluginsr   r˜   Zcertbot.compatr   Z	getLoggerÚ__name__r+   r[   rY   rV   rL   rS   ZCONFIG_ITEMSr=   rD   r3   r2   r1   rT   rX   rZ   r\   rk   rt   rz   r   rŠ   r    rw   r%   r%   r%   r(   Ú<module>   sh   
ÿ:+0k