
    M/e0f                     *   d 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 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j\                  e/      Z0g dZ1ddgZ2g dZ3 e4 ejj                  e3e2e1d             Z6d!ejn                  d"e8d#ee"jr                     fd$Z:d!ejn                  d%ee8e	f   d#dfd&Z;d!ejn                  d%ee8e	f   d#dfd'Z<d!ejn                  d%ee8e	f   d#dfd(Z=d%ee8e	f   d#e
e8e	f   fd)Z>d*e8d+eee8   e8f   d#ee8   fd,Z?d-e8d+e8d#e@fd.ZAd-e8d+e8d#eBfd/ZCd-e8d+e8d#ee8   fd0ZDd!ejn                  d1e"jr                  d#e@fd2ZEd!ejn                  d1e"jr                  d3e8d#dfd4ZFd!ejn                  d1e"jr                  d#dfd5ZGd!ejn                  d6eee8      d7ej                  d1e"jr                  d#df
d8ZId9ee8   d:e8d#e8fd;ZJd!ejn                  d<ee8   d=ee8   d>ee8   d?ee8   d#dfd@ZKd!ejn                  d#eeLeLf   fdAZMdBe8d!ejn                  d#dfdCZNy)DzGFunctionality for autorenewal and associated juggling of configurations    N)Any)Dict)Iterable)List)Mapping)Optional)Tuple)Union)default_backend)ec)rsa)load_pem_private_key)configuration)crypto_util)errors)util)cli)client)	constants)hooks)storage)updater)obj)disco)os)
config_dirlogs_dirwork_dir
user_agentserveraccountauthenticator	installer
renew_hookpre_hook	post_hookhttp01_addresspreferred_chainkey_typeelliptic_curversa_key_sizehttp01_port)must_stapleallow_subset_of_names	reuse_key	autorenew)pref_challsconfig	full_pathreturnc                    	 t        j                  ||       }d|j                  vrt
        j                  d|       y|j                  d   }d|vrt
        j                  d|       y|j                  d	d
      |d	<   t        |      }	 t        | |       t        | |       	 |j%                         D cg c]  }t'        j(                  |       c}| _        |S # t        j                  t        f$ rg}t
        j                  d|       t
        j                  dt        |             t
        j                  dt        j                                Y d}~yd}~ww xY w# t         t        j"                  f$ rR}t
        j                  d|t        |             t
        j                  dt        j                                Y d}~yd}~ww xY wc c}w # t        j,                  $ r!}t
        j                  d||       Y d}~yd}~ww xY w)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

    z(Renewal configuration file %s is broken.zThe error was: %s
Skipping.Traceback was:
%sNrenewalparamsz<Renewal configuration file %s lacks renewalparams. Skipping.r"   zJRenewal configuration file %s does not specify an authenticator. Skipping.r)   r   zHAn error occurred while parsing %s. The error was %s. Skipping the file.z{Renewal configuration file %s references a certificate that contains an invalid domain name. The problem was: %s. Skipping.)r   RenewableCertr   CertStorageErrorIOErrorloggererrorstrdebug	traceback
format_excr   get"_remove_deprecated_config_elements restore_required_config_elements_restore_plugin_configs
ValueErrorErrornamesr   enforce_domain_sanitydomainsConfigurationError)r2   r3   renewal_candidater<   r7   ds         ;/usr/lib/python3/dist-packages/certbot/_internal/renewal.pyreconstituterN   9   s   $#11)VD /=== 23<	>%33ODMm+ 56?	A !. 1 1*e DM* 7}EM(?6#4#:#:#<> 44Q7 > Y ##W- ?K3SZ@)9+?+?+AB	8 % !"+SZ	9 	)9+?+?+AB>$$  ,-6	? 	s[   C E !G 3G
G E2AEEG5AGG
G H"G>>Hr7   c                     d|v r| j                  d      s
|d   | _        d|v r2| j                  d      s |d   }t        |t              r|g}|| _        yyy)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)set_by_userrP   
isinstancer=   rQ   )r2   r7   wps      rM   _restore_webroot_configrU   |   si     %f.@.@.O*=9 &v/A/A./Q>*b#B 	 0R&    c           	         g }|d   dk(  rt        | |       n|j                  |d          |j                  d      |j                  |d          t        |      D ]  }|j	                  dd      }|j                         D ]o  \  }}|j                  |dz         s| j                  |      r-|dv rt        | |t        |             Ht        j                  |      }t        | | ||             q  y)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"   webrootr#   N-_)NoneTrueFalse)rU   appendrA   setreplaceitems
startswithrR   setattrevalr   argparse_type)r2   r7   plugin_prefixesplugin_prefixconfig_itemconfig_valuecasts          rM   rD   rD      s    ( "$O_%26}_=>%1}[9:_- E%--c37)6)<)<)> 
	E%K%%mc&9:6CUCUVaCb  #<< FKl1CD,,[9DFKl1CD
	EErV   c                    i }t        j                  dt        fft        t        t        j
                  t                    t        t        t        j
                  t                    t        t        t        j
                  t                          }|D ]-  \  }}||v s| j                  |      r ||||         }|||<   / |j                         D ]  \  }}t        | ||        y)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

    r1   N)	itertoolschain_restore_pref_challszipBOOL_CONFIG_ITEMSrepeat_restore_boolINT_CONFIG_ITEMS_restore_intSTR_CONFIG_ITEMS_restore_strrR   ra   rc   )r2   r7   updated_valuesrequired_items	item_namerestore_funcvaluekeys           rM   rC   rC      s     N__
-	.0y//>?i..|<=i..|<=	?N
 $2 .	<%f.@.@.K M),DEE(-N9%. %**, $
UU#$rV   c                 z    | j                         D ci c]  \  }}|t        j                  vr|| c}}S c c}}w )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

    )ra   r   DEPRECATED_OPTIONS)r7   option_namevs      rM   rB   rB      sD     4A3F3F3H 6/Qc444 N 6 6 6s   7unused_namer{   c                 V    t        |t              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 a bool

    )rS   r=   r   parse_preferred_challenges)r   r{   s     rM   rn   rn      s'    $ "%-UG5E))%00rV   namec                 j    |j                         }|dvrt        j                  d|  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

    )truefalsezExpected True or False for z but found r   )lowerr   rF   )r   r{   lowercase_values      rM   rr   rr      s@     kkmO//ll8k%QRRf$$rV   c                     | dk(  r/|dk(  r*t         j                  d       t        j                  d      S 	 t	        |      S # t
        $ r t        j                  d|        w xY w)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 )r;   infor   flag_defaultintrE   r   rF   r   r{   s     rM   rt   rt     sh     }&78..C5z Cll:4&ABBCs   
A "A#c                     | dk(  rN|t         j                  k(  r;t        j                  dt         j                  d   |       t         j                  d   S |dk(  rdS |S )zRestores 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 %sr[   N)r   V1_URIr;   r   CLI_DEFAULTSr   s     rM   rv   rv     sZ    " xEY%5%55:**84e	=%%h//F?4--rV   lineagec                    | j                   rt        j                  d       y|j                         rt        j	                  d       y| j
                  rt        j	                  d       yt        j                  d       y)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)renew_by_defaultr;   r>   should_autorenewr   dry_rundisplay_utilnotify)r2   r   s     rM   should_renewr   7  s`    BC!FG~~YZ=>rV   original_serverc                     t        j                  | j                        r[t        j                  |      sE| j                  s8dj	                  |j                               }t        j                  d| d      yyy)z9Do not renew a valid cert with one from a staging server!z, z^You've asked to renew/replace a seemingly valid certificate with a test certificate (domains: z@). We will not do that unless you use the --break-my-certs flag!N)r   
is_stagingr    break_my_certsjoinrG   r   rF   )r2   r   r   rG   s       rM   _avoid_invalidating_lineager   F  su     v}}%/((		'--/2ll4497 ;@@A A ) 0 &rV   c                 R     j                  d      r j                  syj                  s j                  sy j                  ry j                  j	                         dfdfd fdfd fdfg}|D ](  } |d	          st        j                  d
|d    d       y)zDon't allow combining --reuse-key with any flags that would conflict
    with key reuse (--key-type, --rsa-key-size, --elliptic-curve), unless
    --new-key is also set.
    r/   Nz
--key-typec                  >     j                   j                         k7  S N)private_key_typer   )ktr   s   rM   <lambda>z,_avoid_reuse_key_conflicts.<locals>.<lambda>n  s    w//5577 rV   z--rsa-key-sizec                  D    dk(  xr  j                   j                   k7  S )Nr   )r+   r2   r   r   s   rM   r   z,_avoid_reuse_key_conflicts.<locals>.<lambda>p  s!    uL!4!48L8L!L rV   z--elliptic-curvec                      dk(  xrC j                   xr5  j                   j                         j                   j                         k7  S )Necdsa)r*   r   r   s   rM   r   z,_avoid_reuse_key_conflicts.<locals>.<lambda>r  sH    w Q7#9#9 Q&&,,.'2H2H2N2N2PP rV      zUnable to change the r   z of this certificate because --reuse-key is set. To stop reusing the private key, specify --no-reuse-key. To change the private key this one time and then reuse it in future, add --new-key.)rR   r/   new_keyr)   r   r   rF   )r2   r   potential_conflictsconflictr   s   ``  @rM   _avoid_reuse_key_conflictsr   S  s     +&v/?/? V%5%5 ~~				 B 
	7	9		L	N	
Q	R ( "8A;=,,'} 5! !" ""rV   rI   	le_clientc                 "   |j                   d   }|j                  dt        j                  d            }t	        | ||       t        | |       |s|j                         }| j                  rB| j                  s6t        j                  j                  |j                        }t        ||        nd}|j                  ||      \  }}}}	| j                  r>t         j#                  dt        j                  j%                  |j&                               n^|j)                         }
|j+                  |
||j,                  ||        |j/                  |j)                                |j1                          t3        j4                  | ||j6                         y)zRenew a certificate lineage.r7   r    Nz(Dry run: skipping updating lineage at %s)r   rA   r   r   r   r   rG   r/   r   r   pathnormpathprivkey_update_renewal_params_from_keyobtain_certificater   r;   r>   dirnamecertlatest_common_versionsave_successorpemupdate_all_links_totruncater   r$   live_dir)r2   rI   r   r   renewal_paramsr   r   new_cert	new_chainrZ   prior_versions              rM   
renew_certr     s6    **?;N$((33C3CH3MNOAvw/--/ ''""7??3'8&/&B&B7G&T#Hi!~~?QXQ]Q]A^_557}hYPVW##G$A$A$CD	VWg&6&67rV   msgscategoryc                 B    fd| D        }ddj                  |      z   S )z:Format a results report for a category of renewal outcomesc              3   .   K   | ]  }|d d  yw)z ()N ).0mr   s     rM   	<genexpr>zreport.<locals>.<genexpr>  s     51!X&5s   z  z
  )r   )r   r   liness    ` rM   reportr     s!    55E&++e$$$rV   renew_successesrenew_failuresrenew_skippedparse_failuresc                    t         j                  }t        j                  } |dt        j
                          | j                  rdnd}|r |d        |t        |d             |s;|s9 |d| d       | j                  | j                  | j                   |d	       n|r!|s |d
| d        |t        |d             n`|r|s |d|        |t        |d             n@|r>|r< |d| d        |t        |d      dz           |d|        |t        |d             |r |d        |t        |d              |t        j
                         y)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simulated renewalrenewalz7The following certificates are not due for renewal yet:skippedzNo zs were attempted.NzNo hooks were run.zCongratulations, all zs succeeded: successz@All %ss failed. The following certificates could not be renewed:failurezThe following zs succeeded:zThe following %ss failed:zB
Additionally, the following renewal configurations were invalid: 	parsefail)r   r   r;   r<   display_obj
SIDE_FRAMEr   r   r%   r$   r&   )r2   r   r   r   r   r   notify_errorrenewal_nouns           rM   _renew_describe_resultsr     sS      F<<L
R&&'()*0..&iLHIvmY/0>\N"345OO'!!-1A1A1M'(	&|nMBCvoy12	 !".	0VNI67	O~\:;voy1D890,?VNI67   	!vnk23
;!!"rV   c                     t         fd j                  D              rt        j                  d       j                  r"t        j                    j                        g}nt        j                         }g }g }g }g }g }g }t        j                  j                          xr  j                  }|D ]  }	t        j                  d|	z   d       t        j                         }
t        j                   |	      }	 t#        |
|	      }	 |s|j1                  |	       nL|j3                          d	d
lm} t8        j:                  j=                         }t?        |
|      r|rCtA        jB                  dd      }t&        jE                  d|       tG        jH                  |       d}|jK                  |
||       |j1                  |jL                         |jO                  |jQ                                nbtS        jT                  |jW                  d|jY                                     }|j1                  |jL                  d|j[                  d             t]        j^                  |
||        ta         ||||       |s|r-t        j                  tc        |       dtc        |       d      t&        j+                  d       ||fS # t$        $ r\}t&        j)                  d|	||       t&        j+                  dt-        j.                                |j1                  |	       Y d}~sd}~ww xY w# t$        $ r}t&        j)                  d||       t&        j+                  dt-        j.                                |r:|j1                  |jL                         |jO                  |jQ                                Y d}~d}~ww xY w)z5Examine each lineage; renew if due and report resultsc              3   :   K   | ]  }|j                   v  y wr   )rP   )r   domainr2   s     rM   r   z)handle_renewal_request.<locals>.<genexpr>  s     
I6+++
Is   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.r6   Nr   )mainr   i  z3Non-interactive renewal: random delay of %s secondsr   z expires on z%Y-%m-%dz-Failed to renew certificate %s with error: %sz renew failure(s), z parse failure(s)zno renewal failures)2anyrI   r   rF   certnamer   renewal_file_for_certnamerenewal_conf_filessysstdinisattyrandom_sleep_on_renewr   notificationcopydeepcopylineagename_for_filenamerN   	Exceptionr;   r<   r>   r?   r@   r^   ensure_deployedcertbot._internalr   plugins_discoPluginsRegistryfind_allr   randomuniformr   timesleepr   	fullchainextendrG   r   notAfterversionr   strftimer   run_generic_updatersr   len)r2   
conf_filesr   r   r   r   renewed_domainsfailed_domainsapply_random_sleeprenewal_filelineage_configlineagenamerK   er   plugins
sleep_timeexpirys   `                 rM   handle_renewal_requestr    s\    
I&..
II ll P Q 	Q 77PQ
//7
ONMNON !YY--//PF4P4P" <A!!-,">eLv.66|D	 ,^\ J+	A$%%l3!1132'77@@B0AB)%+^^Av%>
$Y$.0

:.-2* OONG=NO#**+<+F+FG#**+<+B+B+DE(112C2K2K 1 G G I3K LF!((?P?Z?Z)/)D*F G ,,^=N-46a<A~ FO^)>; ll>"##6s>7J6KK\]_ 	_
 LL&'^,,C  	LL I'a9 LL-y/C/C/EF!!,/	T  		ALL?Q LL-y/C/C/EF %%&7&A&AB%%&7&=&=&?@		As3   <K	E!L.	L+AL&&L+.	N=7A;N88N=key_pathc                    t        | d      5 }t        |j                         d t                     }d d d        t	        t
        j                        rd|_        |j                  |_	        y t	        |t        j                        r#d|_        |j                  j                  |_        y t        j                   d|  dt#        |       d      # 1 sw Y   xY w)Nrb)passwordbackendr   r   zKey at z is of an unsupported type: .)openr   readr   rS   r   RSAPrivateKeyr)   key_sizer+   r   EllipticCurvePrivateKeycurver   r*   r   rF   type)r  r2   file_hr|   s       rM   r   r   B  s    	h	 \"6;;=4IZ[\#s(()!ll	C33	4! #		llWXJ.J4PS9+UVWXX\ \s   %CC)O__doc__r   rl   loggingr   r   r   r?   typingr   r   r   r   r   r   r	   r
   cryptography.hazmat.backendsr   )cryptography.hazmat.primitives.asymmetricr   r   ,cryptography.hazmat.primitives.serializationr   certbotr   r   r   r   r   r   r   r   r   r   r   certbot._internal.displayr   r   certbot._internal.pluginsr   r   certbot.compatr   certbot.displayr   	getLogger__name__r;   ru   rs   rp   r_   rm   CONFIG_ITEMSNamespaceConfigr=   r8   rN   rU   rD   rC   rB   rn   boolrr   r   rt   rv   r   r   r   Clientr   r   r   listr  r   r   rV   rM   <module>r,     s   M     
           8 8 9 M !    ! $ ' # % % 8 <  0			8	$E  #M2 "  ?9??')9;KM N@66 @ @%-g.C.C%D@F!M$A$A !+238+<!AE!$)EM$A$A )E+238+<)EAE)EX$]-J-J $4;CH4E$JN$2
6gc3h6G 
6DQTVYQYN 
61c 1%S	32G 1DQTI 1,% %C %D %$Cs C3 C3 C,.s .3 .8C= .266 AVAV [_ 
A(E(E 
A)0)>)>
AQT
AY]
A)"}'D'D )"(/(=(=)"BF)"X8}44 8xS	?R 8 --8292G2G8LP8:%# %# %# %-#M$A$A -#TXY\T] -#,0I-#FJ3i-#,0I-#:>-#`m-=#@#@ m-U4QU:EV m-`
Yc 
Y=;X;X 
Y]a 
YrV   