
/_S                 @   st  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 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 j e  Z  d d d d d d d d d d d d d d g Z! d d d g Z" d  d! d" d# g Z# e$ e j% e# e" e! dA   Z& d% d&   Z' d' d(   Z( d) d*   Z) d+ d,   Z* d- d.   Z+ d/ d0   Z, d1 d2   Z- d3 d4   Z. d5 d6   Z/ d7 d8   Z0 d9 d:   Z1 d; d<   Z2 d= d>   Z3 d? d@   Z4 d S)BzGFunctionality for autorenewal and associated juggling of configurations    )print_functionN)List)cli)	constants)crypto_util)errors)
interfaces)util)hooks)storage)updater)discoZ
config_dirZlogs_dirZwork_dirZ
user_agentserverZaccountauthenticator	installerZstandalone_supported_challenges
renew_hookpre_hook	post_hookZtls_sni_01_addressZhttp01_addressZrsa_key_sizeZtls_sni_01_porthttp01_portZmust_stapleZallow_subset_of_names	reuse_keyZ	autorenewpref_challsc          &   C   s  y t  j | |   } WnX t j t f k
 rp t j d d d t j d |  t j d t j	    d SYn Xd | j
 k r t j d |  d S| j
 d } d	 | k r t j d
 |  d Sy t |  |  t |  |  Wna t t j f k
 rB} z8 t j d | t |   t j d t j	    d SWYd d } ~ Xn Xy  d d   | j   D |  _ Wn? t j k
 r} z t j d | |  d SWYd d } ~ Xn 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

     exc_infoTz2Renewal configuration file %s is broken. Skipping.z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  j |   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   _reconstitute2   sB    					
r1   c             C   sv   d | k r+ t  j d  sr | d |  _ nG d | k rr t j d  | d } t | t j  ri | 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_pathzEAncient renewal conf file without webroot-map, restoring webroot-pathN)	r   
set_by_clir2   r    r"   
isinstancesixstring_typesr3   )r-   r   Zwpr   r   r   _restore_webroot_configk   s    
	r8   c             C   s  g  } | d d k r& t  |  |  n | j | d  | j d  d k	 r] | j | d  x t |  D] } | j d d  } x t j |  D]y \ } } | j | d  r t j	 |  r | d
 k r t
 |  | t |   q t j |  } t
 |  | | |   q Wqj Wd 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)zNonezTruezFalse)r8   appendgetsetreplacer6   Z	iteritems
startswithr   r4   setattrevalZargparse_type)r-   r   Zplugin_prefixesZplugin_prefixZconfig_itemZconfig_valuecastr   r   r   r'   |   s    #r'   c             C   s   t  j d t f f t j j t t  j t   t j j t	 t  j t
   t j j t t  j t    } xS | D]K \ } } | | k rp t j |  rp | | | |  } t |  | |  qp Wd 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_challsr6   ZmoveszipBOOL_CONFIG_ITEMSrepeat_restore_boolINT_CONFIG_ITEMS_restore_intSTR_CONFIG_ITEMS_restore_strr   r4   rC   )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 j |  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

    )r5   r6   r7   r   Zparse_preferred_challenges)Zunused_namerQ   r   r   r   rH      s    !rH   c             C   s=   | j    } | d k r3 t j d j |  |    | 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

    truefalsez,Expected True or False for {0} but found {1})ztruezfalse)lowerr   r)   format)namerQ   Zlowercase_valuer   r   r   rL      s
    rL   c             C   sq   |  d k r2 | d k r2 t  j d  t j d  Sy t |  SWn* t k
 rl t j d j |     Yn Xd 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)   rU   )rV   rQ   r   r   r   rN      s    rN   c             C   sT   |  d k r@ | t  j k r@ t j d t  j d |  t  j d S| d k rP d S| S)zRestores 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    rW   ZCLI_DEFAULTS)rV   rQ   r   r   r   rP      s
    	rP   c             C   sb   |  j  r t j d  d S| j   r7 t j d  d S|  j rQ t j d  d St j 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_autorenewrW   dry_run)r-   lineager   r   r   should_renew  s    		r\   c          
   C   s   t  | j   } | j   } Wd QRXt j j t j j |  } d t | j    j	   k } t
 j |  j  r t
 j |  s | r |  j s d j | j    } t j d j |    d S)z9Do not renew a valid cert with one from a staging server!NZfakez, 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!)opencertreadOpenSSLZcryptoZload_certificateZFILETYPE_PEMreprZ
get_issuerrT   r	   Z
is_stagingr   Zbreak_my_certsjoinr+   r   r)   rU   )r-   r[   original_serverZthe_filecontentsZlatest_certZ	now_validr+   r   r   r   _avoid_invalidating_lineage#  s    		re   c             C   s  | j  d } | j d t j d   } t |  | |  | sJ | j   } |  j rh t j j	 | j
  n d } | j | |  \ } } } }	 |  j r t j d t j j | j   n; | j   }
 | j |
 | | j | |   | j | j    t j |  | | j  d S)zRenew a certificate lineage.r   r   Nz(Dry run: skipping updating lineage at %s)r%   r?   r   rX   re   r+   r   ospathnormpathZprivkeyZobtain_certificaterZ   r    r"   dirnamer^   latest_common_versionZsave_successorZpemZupdate_all_links_tor
   r   Zlive_dir)r-   r,   Z	le_clientr[   Zrenewal_paramsrc   Znew_keyZnew_certZ	new_chainr:   Zprior_versionr   r   r   
renew_cert9  s    $		rk   c                s*     f d d   |  D } d d j  |  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>R  s    zreport.<locals>.<genexpr>z  z
  )rb   )Zmsgsrm   linesr   )rm   r   reportP  s    rp   c                s  g  } | j    t j j t j  }   f d d   } |  j rS   d    d    d  | r   d    t | d   | r | r   d  |  j d  k	 s |  j	 d  k	 s |  j
 d  k	 rv  d	  n | r | r   d
    t | d   nw | r,| r,| d  | t | d   nJ | rv| rv  d    t | d  d  | d  | t | d   | r  d    t | d   |  j r  d    d  | j d j |  d d d  S)Nc                s!     t  |    t j |   d S)zNotify and log errors.N)r*   r    r0   )err)notifyr   r   notify_error\  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.)ZwrapF)r>   zope	component
getUtilityr   IDisplayrZ   rp   r   r   r   notificationrb   )r-   renew_successesrenew_failuresrenew_skippedparse_failuresoutdisprs   r   )rr   r   _renew_describe_resultsU  sD    		









	

r   c                 sH  t    f d d     j D  r1 t j d     j rU t j     j  g } n t j    } g  } g  } g  } g  } t j	 j
   o   j } xS| D]K} t j j t j  } | j d | d d t j    }	 t j |  }
 y t |	 |  } Wna t k
 rb} zA t j d | |
 |  t j d t j    | j |  w WYd	 d	 } ~ Xn Xy | d	 k r| j |  n t j j |	  | j   d
 d l m  } t! j" j#   } t$ |	 |  r+| rt% j& d d  } t j' d |  t( j) |  d } | j* |	 | |  | j | j+  nD t, j- | j. d | j/     } | j d | j+ | j0 d  f  t1 j2 |	 | |  Wq t k
 r} zA t j d |
 | |  t j d t j    | j | j+  WYd	 d	 } ~ Xq Xq Wt3   | | | |  | s| r7t j d j4 t5 |  t5 |     n t j d  d	 S)z5Examine each lineage; renew if due and report resultsc             3   s   |  ] } |   j  k Vq d  S)N)r2   )r   Zdomain)r-   r   r   rn     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 pauseFzTRenewal configuration file %s (cert: %s) produced an unexpected error: %s. Skipping.zTraceback was:
%sNr   )main   <      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 failuresi  )6anyr,   r   r)   Zcertnamer   Zrenewal_file_for_certnameZrenewal_conf_filessysstdinisattyZrandom_sleep_on_renewru   rv   rw   r   rx   ry   copydeepcopyZlineagename_for_filenamer1   	Exceptionr    r!   r"   r#   r$   r>   ZprovideUtilityZensure_deployedcertbotr   plugins_discoZPluginsRegistryZfind_allr\   randomZrandintrW   timeZsleeprk   Z	fullchainr   ZnotAfterversionrj   Zstrftimer   Zrun_generic_updatersr   rU   len)r-   Z
conf_filesrz   r{   r|   r}   Zapply_random_sleepZrenewal_filer   Zlineage_configZlineagenamer/   er   ZpluginsZ
sleep_timeZexpiryr   )r-   r   handle_renewal_request  sr    "		
		
'
r   )zpref_challs)5__doc__Z
__future__r   r   rF   Zloggingrf   r#   r   r   r   r6   Zzope.componentru   r`   Zacme.magic_typingr   r   r   r   r   r   r   r	   r
   r   r   Zcertbot.pluginsr   r   Z	getLogger__name__r    rO   rM   rJ   r@   rG   ZCONFIG_ITEMSr1   r8   r'   r&   rH   rL   rN   rP   r\   re   rk   rp   r   r   r   r   r   r   <module>   s`   					9+2