U
    ]M                    @   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mZ ddlmZ ddlmZmZmZ ddlZddlm  mZ ddlm  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a,dZ-de#j.krLe#j/0e#j.d Z-e#j/1dddZ2e#j/3e#j/1e#j4ddddZ5e2ej6d ksej6d 7e5re-Z8ndZ8d9e8Z:dZ;dZ<dZ=e>dZ?e>dZ@e>de>de>de>d d!ZAd"d# ZBG d$d% d%eCZDd&d' ZEdeE_Fd(d) ZGd*d+ ZHd,d- ZIdd/d0ZJd1d2 ZKdd4d5ZLG d6d7 d7eCZMG d8d9 d9ejNZOd:d;d<e:Pd=d>d?d@fdAdBdCdDdEfdFdGdHdIdEfdJdKdKdLdEfdMdNdOdPdEfdQdRdSdTdEfdUdVdWdXdEfdYdZd[d\dEfd]d^d_d`dEfdadbdcdddEfdedfdgdhdEfdidjdkdldEfdmdndodpdEfdqdrds9e#j/1eKdtdudvdEfdwdxdydzdEfgZQeReQZSG d{d| d|eCZTd}d~ ZUdddZVdd ZWG dd deXZYdd ZZdd Z[G dd dej\Z]G dd dej\Z^dd Z_G dd dej\Z`dd Zadd ZbG dd dej\ZcG dd dej\Zddd ZedS )z2Certbot command line argument & config processing.    )print_functionN)
interfaces)
challenges)AnyDictOptional)	constants)crypto_util)errors)hooks)util)os)discozletsencrypt-autoZCERTBOT_AUTOz.localZshareZletsencryptZoptzeff.orgcertbotvenvz
  {0} [SUBCOMMAND] [options] [-d DOMAIN] [-d DOMAIN] ...

Certbot can obtain and install HTTPS/TLS/SSL certificates.  By default,
it will attempt to use a webserver both for obtaining and installing the
certificate. a  The most common SUBCOMMANDS and flags are:

obtain, install, and renew certificates:
    (default) run   Obtain & install a certificate in your current webserver
    certonly        Obtain or renew a certificate, but do not install it
    renew           Renew all previously obtained certificates that are near expiry
    enhance         Add security enhancements to your existing configuration
   -d DOMAINS       Comma-separated list of domains to obtain a certificate for

  %s
  --standalone      Run a standalone webserver for authentication
  %s
  --webroot         Place files in a server's webroot folder for authentication
  --manual          Obtain certificates interactively, or using shell script hooks

   -n               Run non-interactively
  --test-cert       Obtain a test certificate from a staging server
  --dry-run         Test "renew" or "certonly" without saving any certificates to disk

manage certificates:
    certificates    Display information about certificates you have from Certbot
    revoke          Revoke a certificate (supply --cert-path or --cert-name)
    delete          Delete a certificate

manage your account:
    register        Create an ACME account
    unregister      Deactivate an ACME account
    update_account  Update an ACME account
  --agree-tos       Agree to the ACME server's Subscriber Agreement
   -m EMAIL         Email address for important account notifications
a  
More detailed help:

  -h, --help [TOPIC]    print this message, or detailed help on a topic;
                        the available TOPICS are:

   all, automation, commands, paths, security, testing, or any of the
   subcommands or plugins (certonly, renew, install, register, nginx,
   apache, standalone, webroot, etc.)
  -h all                print a detailed help page including all topics 
  --version             print the version number
)constnargstype)helpversion)Zstore_const
store_truestore_falseappend_constcount)server)deploy_hook)dry_runstaging)Zwebroot_path)account
renew_hookr   Zwebroot_mapc                 C   sF   t | tjr| f} t |tjr$|f}| D ]}t|t | q(dS )a  Registers config option interaction to be checked by set_by_cli.

    This function can be called by during the __init__ or
    add_parser_arguments methods of plugins to register interactions
    between config options.

    :param modified: config options that can be modified by modifiers
    :type modified: iterable or str (string_types)
    :param modifiers: config options that modify modified
    :type modifiers: iterable or str (string_types)

    N)
isinstancesixstring_typesVAR_MODIFIERS
setdefaultsetupdate)ZmodifiedZ	modifiersvar r(   -/usr/lib/python3/dist-packages/certbot/cli.pyreport_config_interaction   s    r*   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )_DefaultzAA class to use as a default to detect if a value is set by a userc                 C   s   dS )NFr(   selfr(   r(   r)   __bool__   s    z_Default.__bool__c                 C   s
   t |tS N)r    r+   )r-   otherr(   r(   r)   __eq__   s    z_Default.__eq__c                 C   s   t tS r/   )idr+   r,   r(   r(   r)   __hash__   s    z_Default.__hash__c                 C   s   |   S r/   )r.   r,   r(   r(   r)   __nonzero__   s    z_Default.__nonzero__N)__name__
__module____qualname____doc__r.   r1   r3   r4   r(   r(   r(   r)   r+      s
   r+   c              	   C   s   t j}|dkrTtdk	rTtj }tjtjg }t||dd }t _t	
|\|_|_tt|| ts|td| t||  dS t| g D ](}t |rtd| t| g   dS qdS )z
    Return True if a particular config variable has been set by the user
    (CLI or config file) including if the user explicitly set it to the
    default.  Returns False if the variable was assigned a default value.
    NT)detect_defaultszVar %s=%s (set by user).F)
set_by_clidetectorhelpful_parserplugins_discoZPluginsRegistryZfind_allargsverbprepare_and_parse_argsplugin_selectionZcli_plugin_requestsauthenticator	installerr    getattrr+   loggerdebugr#   get)r'   r;   pluginsZreconstructed_argsZmodifierr(   r(   r)   r:      s,    
  
 
r:   c                 C   s$   t dk	r | t jkot j|  |kS dS )aH  Does option have the default value?

    If the default value of option is not known, False is returned.

    :param str option: configuration variable being considered
    :param value: value of the configuration variable named option

    :returns: True if option has the default value, otherwise, False
    :rtype: bool

    NF)r<   defaultsZoptionvaluer(   r(   r)   has_default_value   s
    
rL   c                 C   s   t | pt| | S )a  Was option set by the user or does it differ from the default?

    :param str option: configuration variable being considered
    :param value: value of the configuration variable named option

    :returns: True if the option was set, otherwise, False
    :rtype: bool

    )r:   rL   rJ   r(   r(   r)   option_was_set   s    
rM   c                 C   s8   t dk	r4t jjD ]"}|jdk	r|j| kr|j  S qtS )zFReturn our argparse type function for a config variable (default: str)N)r<   parserZ_actionsr   deststr)Zvariableactionr(   r(   r)   argparse_type   s
    rR   rbc              
   C   sh   z4t j| } t| |}| }W 5 Q R X | |fW S  tk
rb } zt|jW 5 d}~X Y nX dS )a  Returns the given file's contents.

    :param str filename: path to file
    :param str mode: open mode (see `open`)

    :returns: absolute path of filename and its contents
    :rtype: tuple

    :raises argparse.ArgumentTypeError: File does not exist or is not readable.

    N)	r   pathabspathopenreadIOErrorargparseArgumentTypeErrorstrerror)filenamemodeZthe_filecontentsexcr(   r(   r)   	read_file  s    
r`   c                 C   s   t tj|  S )zDefault value for CLI flag.)copydeepcopyr   ZCLI_DEFAULTS)namer(   r(   r)   flag_default  s    rd   Fc                 C   s   |r
t jS tj| }|jS )z5Extract the help message for an `.IConfig` attribute.)rY   SUPPRESSr   ZIConfig__getitem__r8   )rc   ZhiddenZfieldr(   r(   r)   config_help!  s    rg   c                   @   s    e Zd ZdZdd Zdd ZdS )HelpfulArgumentGroupa+  Emulates an argparse group for use with HelpfulArgumentParser.

    This class is used in the add_group method of HelpfulArgumentParser.
    Command line arguments can be added to the group, but help
    suppression and default detection is applied by
    HelpfulArgumentParser when necessary.

    c                 C   s   || _ || _d S r/   )_parser_topic)r-   Zhelpful_arg_parsertopicr(   r(   r)   __init__3  s    zHelpfulArgumentGroup.__init__c                 O   s   | j j| jf|| dS )z6Add a new command line argument to the argument group.N)ri   addrj   )r-   r>   kwargsr(   r(   r)   add_argument7  s    z!HelpfulArgumentGroup.add_argumentN)r5   r6   r7   r8   rl   ro   r(   r(   r(   r)   rh   *  s   rh   c                   @   s   e Zd ZdZdd ZdS )CustomHelpFormatterzThis is a clone of ArgumentDefaultsHelpFormatter, with bugfixes.

    In particular we fix https://bugs.python.org/issue28742
    c                 C   sN   |j }d|j krJd|j krJ|jtjkrJtjtjg}|jsB|j|krJ|d7 }|S )Nz
%(default)z	(default:z (default: %(default)s))r   defaultrY   re   ZOPTIONALZZERO_OR_MOREZoption_stringsr   )r-   rQ   ZhelpstrZdefaulting_nargsr(   r(   r)   _get_help_stringA  s    z$CustomHelpFormatter._get_help_stringN)r5   r6   r7   r8   rr   r(   r(   r(   r)   rp   ;  s   rp   zrun (default)z*Obtain/renew a certificate, and install itz/Options for obtaining & installing certificatesz[SUBCOMMAND] run)shortoptsusagerealnamecertonlyz4Obtain or renew a certificate, but do not install itz3Options for modifying how a certificate is obtainedz

  certbot certonly [options] [-d DOMAIN] [-d DOMAIN] ...

This command obtains a TLS/SSL certificate without installing it anywhere.)ru   rv   rw   renewz:Renew all certificates (or one specified with --cert-name)a]  The 'renew' subcommand will attempt to renew all certificates (or more precisely, certificate lineages) you have previously obtained if they are close to expiry, and print a summary of the results. By default, 'renew' will reuse the options used to create obtain or most recently successfully renew each certificate lineage. You can try it with `--dry-run` first. For more fine-grained control, you can renew individual lineages with the `certonly` subcommand. Hooks are available to run commands before and after renewal; see https://certbot.eff.org/docs/using.html#renewal for more information on these.z4

  certbot renew [--cert-name CERTNAME] [options]

certificatesz$List certificates managed by Certbotzn

  certbot certificates [options] ...

Print information about the status of certificates managed by Certbot.deletez+Clean up all files related to a certificatez"Options for deleting a certificatez)

  certbot delete --cert-name CERTNAME

revokez>Revoke a certificate specified with --cert-path or --cert-namez&Options for revocation of certificatesz]

  certbot revoke [--cert-path /path/to/fullchain.pem | --cert-name example.com] [options]

registerz;Register for account with Let's Encrypt / other ACME serverz Options for account registrationz9

  certbot register --email user@example.com [options]

update_accountz>Update existing account with Let's Encrypt / other ACME serverz Options for account modificationzH

  certbot update_account --email updated_email@example.com [options]


unregisterz#Irrevocably deactivate your accountz!Options for account deactivation.z"

  certbot unregister [options]

installz,Install an arbitrary certificate in a serverz3Options for modifying how a certificate is deployedzc

  certbot install --cert-path /path/to/fullchain.pem  --key-path /path/to/private-key [options]

config_changesz;Show changes that Certbot has made to server configurationsz)Options for viewing configuration changesz&

  certbot config_changes [options]

rollbackzBRoll back server conf changes made during certificate installationz5Options for rolling back server configuration changesz0

  certbot rollback --checkpoints 3 [options]

rH   z<List plugins that are installed and available on your systemz$Options for the "plugins" subcommandz

  certbot plugins [options]

update_symlinksz:Recreate symlinks in your /etc/letsencrypt/live/ directoryzqRecreates certificate and key symlinks in {0}, if you changed them by hand or edited a renewal configuration file
config_dirZlivez'

  certbot update_symlinks [options]

enhancez8Add security enhancements to your existing configurationzhHelps to harden the TLS configuration by adding security enhancements to already existing configuration.z

  certbot enhance [options]

c                   @   s   e Zd ZdZd(ddZddddd	gZd
d Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zd)d!d"Zd#d$ Zd%d& Zd'S )*HelpfulArgumentParserzArgparse Wrapper.

    This class wraps argparse, adding the ability to make --help less
    verbose, and request help on specific subcategories at a time, eg
    'certbot --help security' for security options.

    Fc           
      C   s  ddl m} |j|j|j|j|j|j|j|j|j	|j
|j|j|j|j|j|j|jd| _ztjtjj| _W n& tjk
r   ttjj| _Y nX dddddg}|t| j| j  d	g 7 }t|}|| d g | _!|| _"|| _#| j#r| j#d d
krd| j#d< | $  | %d| j!}| %d| j!}t&|t'rNt&|t'rN|pH|| _(nt&|t)j*r`|n|| _(| +|| j(}	| ,| j(| _-i | _.i | _/t0j1d|	t2ddgt3dd4d5t3dd| _6d| j6_7d S )Nr   )main)authry   r   rt   r   rH   r~   r   r   rz   r}   r   
everythingr   r{   r|   r   allsecuritypaths
automationtestingmanager   --help-hr   z-cz--configZconfig_filesz"path to config file (default: {0})z and )progrw   Zformatter_classZargs_for_setting_config_pathZdefault_config_filesZconfig_arg_help_messageF)8r   r   ry   r   rt   r   Zplugins_cmdr~   r   r   rz   r}   r   r   r{   r|   r   VERBSzopeZ	componentZ
getUtilityr   ZIDisplayZnotificationnotifyzope_interfacesZComponentLookupErrordisplay_utilZNoninteractiveDisplaysysstdoutlistCOMMANDS_TOPICShelp_topicsr9   r>   determine_verbprescan_for_flagr    boolhelp_argr!   r"   _usage_stringdetermine_help_topicsvisible_topicsgroupsrI   configargparseZ	ArgParserrp   rd   formatjoinrN   Z_add_config_file_help)
r-   r>   rH   r9   r   ZHELP_TOPICSZplugin_namesZhelp1Zhelp2Zshort_usager(   r(   r)   rl     sp    

zHelpfulArgumentParser.__init__ZcommandZcommandsZ
subcommandZsubcommandsverbsc                 C   sT   t dd tD }d}ttD ](\}}|dd}|dj|||d7 }q|d7 }|S )	Nc                 s   s   | ]}t |V  qd S r/   )len).0vr(   r(   r)   	<genexpr>	  s     z:HelpfulArgumentParser._list_subcommands.<locals>.<genexpr>z,The full list of available SUBCOMMANDS is:

ru   rs   z{0:<{length}}     {1}
)ZlengthzG
You can get more help on a specific subcommand with --help SUBCOMMAND
)maxVERB_HELP_MAPsorted	VERB_HELPrG   r   )r-   Zlongesttextr?   Zpropsdocr(   r(   r)   _list_subcommands  s    z'HelpfulArgumentParser._list_subcommandsc                 C   s   d|krd}nd}d|kr d}nd}t }|dkrV| |t||f  t  td nb|| jkr~| ||    td n:|d	kr|t||f 7 }n t	|i 	d
d}|r|n|}|S )a#  Make usage strings late so that plugins can be initialised late

        :param plugins: all discovered plugins
        :param help_arg: False for none; True for --help; "TOPIC" for --help TOPIC
        :rtype: str
        :returns: a short usage string for the top of --help TOPIC)
        nginxzH--nginx           Use the Nginx plugin for authentication & installationz+(the certbot nginx plugin is not installed)apachezI--apache          Use the Apache plugin for authentication & installationz,(the certbot apache plugin is not installed)Tr   r   rw   N)
SHORT_USAGEr   COMMAND_OVERVIEWHELP_AND_VERSION_USAGEr   exitr   r   r   rG   )r-   rH   r   Z	nginx_docZ
apache_docrw   Zcustomr(   r(   r)   r     s$    
z#HelpfulArgumentParser._usage_stringc                 C   sH   | j dkrD| jj D ],\}}|drd|kr| jr<t ng |_qdS )z8Make "certbot renew" safe if domains are set in cli.ini.rz   Zconfig_filedomainsN)r?   rN   Z_source_to_settingsitems
startswithr9   r+   r   )r-   parsed_argssourceflagsr(   r(   r)   &remove_config_file_domains_for_renewal5  s    
z<HelpfulArgumentParser.remove_config_file_domains_for_renewalc                    s"   j  j} j j |_ j|_ |  jr8|S t fddt	|D  _
 jdkr||jrvtdtjd|_|jr|jrtdtj|js|jr | |jr | |jrd|_|jrt| |jrtdd |jD rtd|jr|jrtd	|S )
zParses command line arguments and returns the result.

        :returns: parsed command line arguments
        :rtype: argparse.Namespace

        c                 3   s$   | ]}|t  j|fV  qd S r/   )ra   rb   rN   Zget_default)r   keyr,   r(   r)   r   M  s   z3HelpfulArgumentParser.parse_args.<locals>.<genexpr>rz   z{0} cannot be used with renewTz.Flag for non-interactive mode and {0} conflictc                 s   s   | ]}t |V  qd S r/   )r   Zis_wildcard_domainr   dr(   r(   r)   r   k  s     zFUsing --allow-subset-of-names with a wildcard domain is not supported.z@Parameters --hsts and --auto-hsts cannot be used simultaneously.) rN   
parse_argsr>   r   r?   funcr   r9   dictvarsrI   force_interactiver
   Errorr   r   FORCE_INTERACTIVE_FLAGnoninteractive_moder   r   set_test_servercsr
handle_csrmust_staplestaplevalidate_hooksr   allow_subset_of_namesanyr   hstsZ	auto_hsts)r-   r   r(   r,   r)   r   =  sN    






z HelpfulArgumentParser.parse_argsc                 C   s   t dtjf}|jr(|j|kr(td|j|kr:tj|_|jr| jdkrZtd| j d |_	|_t

tj|jtjdrd|_d|_dS )zGWe have --staging/--dry-run; perform sanity check and set config.serverr   z'--server value conflicts with --staging)ry   rz   zN--dry-run currently only works with the 'certonly' or 'renew' subcommands (%r)T*N)rd   r   STAGING_URIr   r   r
   r   r   r?   break_my_certsglobr   rT   r   r   ZACCOUNTS_DIRtosregister_unsafely_without_email)r-   r   Zdefault_serversr(   r(   r)   r   u  s    



z%HelpfulArgumentParser.set_test_serverc           
      C   s   |j dkrtd|jr$td|jdd \}}t||\}}}|D ]}t|| qL|sttd|jd  ||f|_t	dd |D }t	|j
}	||	krtd	d
|d
|	dS )zProcess a --csr flag.ry   zCurrently, a CSR file may only be specified when obtaining a new or replacement via the certonly command. Please try the certonly command instead.z1--allow-subset-of-names cannot be used with --csrr      zJUnfortunately, your CSR %s needs to have a SubjectAltName for every domainc                 S   s   g | ]}|  qS r(   )lowerr   r(   r(   r)   
<listcomp>  s     z4HelpfulArgumentParser.handle_csr.<locals>.<listcomp>zMInconsistent domain requests:
From the CSR: {0}
From command line/config: {1}, N)r?   r
   r   r   r   r	   Zimport_csr_fileadd_domainsZ
actual_csrr%   r   ZConfigurationErrorr   r   )
r-   r   Zcsrfiler^   typr   r   domainZcsr_domainsZconfig_domainsr(   r(   r)   r     s0    




 z HelpfulArgumentParser.handle_csrc                 C   sz   d| j ksd| j krd| _dS t| j D ]F\}}|| jkr(|}|dkrJd}|dkrVd}|| _| j |  dS q(d| _dS )	zDetermines the verb/subcommand provided by the user.

        This function works around some of the limitations of argparse.

        r   r   r   Nr   ry   r   rt   )r>   r?   	enumerater   pop)r-   itokenr?   r(   r(   r)   r     s    
z$HelpfulArgumentParser.determine_verbc                 C   sT   || j krdS | j |}z | j |d  }||kr8|W S W n tk
rN   Y nX dS )as  Checks cli input for flags.

        Check for a flag, which accepts a fixed set of possible arguments, in
        the command line; we will use this information to configure argparse's
        help correctly.  Return the flag's argument, if it has one that matches
        the sequence @possible_arguments; otherwise return whether the flag is
        present.

        F   T)r>   index
IndexError)r-   flagZpossible_argumentsposZnxtr(   r(   r)   r     s    


z&HelpfulArgumentParser.prescan_for_flagc                 O   s   t |tr$| j|kr| jn|d }n|}| jr:| jf |}| j| rv|| jkrf| j| }|j|| q| jj|| nt	j
|d< | jj|| dS )a1  Add a new command line argument.

        :param topics: str or [str] help topic(s) this should be listed under,
                       or None for options that don't fit under a specific
                       topic which will only be shown in "--help all" output.
                       The first entry determines where the flag lives in the
                       "--help all" output (None -> "optional arguments").
        :param list *args: the names of this argument flag
        :param dict **kwargs: various argparse settings for this argument

        r   r   N)r    r   r   r9   #modify_kwargs_for_default_detectionr   r   ro   rN   rY   re   )r-   Ztopicsr>   rn   rk   groupr(   r(   r)   rm     s    




zHelpfulArgumentParser.addc                 K   sL   | dd}|tkrH|tkr dnd|d< t |d< tD ]}||d q6|S )a_  Modify an arg so we can check if it was set by the user.

        Changes the parameters given to argparse when adding an argument
        so we can properly detect if the value was set by the user.

        :param dict kwargs: various argparse settings for this argument

        :returns: a modified versions of kwargs
        :rtype: dict

        rQ   Nr   Zstorerq   )rG   EXIT_ACTIONSZERO_ARG_ACTIONSr+   ARGPARSE_PARAMS_TO_REMOVEr   )r-   rn   rQ   Zparamr(   r(   r)   r     s    
z9HelpfulArgumentParser.modify_kwargs_for_default_detectionc                 C   s   t | jj|| dS )a  Adds a deprecated argument with the name argument_name.

        Deprecated arguments are not shown in the help. If they are used
        on the command line, a warning is shown stating that the
        argument is deprecated and no other action is taken.

        :param str argument_name: Name of deprecated argument.
        :param int nargs: Number of arguments the option takes.

        N)r   add_deprecated_argumentrN   ro   )r-   Zargument_nameZnum_argsr(   r(   r)   r     s
      z-HelpfulArgumentParser.add_deprecated_argumentr(   c                 K   sV   | j | rL| jj|f|| j|< | jrL|D ] }| j| j|t| d d q*t| |S )a  Create a new argument group.

        This method must be called once for every topic, however, calls
        to this function are left next to the argument definitions for
        clarity.

        :param str topic: Name of the new argument group.
        :param str verbs: List of subcommands that should be documented as part of
                          this help group / topic

        :returns: The new argument group.
        :rtype: `HelpfulArgumentGroup`

        ru   r   )r   rN   Zadd_argument_groupr   r   ro   r   rh   )r-   rk   r   rn   r   r(   r(   r)   	add_group&  s    
zHelpfulArgumentParser.add_groupc                 C   s6   t |D ]&\}}| j||jd}|j|| q
dS )z

        Let each of the plugins add its own command line arguments, which
        may or may not be displayed as help topics.

        descriptionN)r!   Z	iteritemsr   Zlong_descriptionZ
plugin_clsZinject_parser_options)r-   rH   rc   Z	plugin_epZparser_or_groupr(   r(   r)   add_plugin_args<  s
    z%HelpfulArgumentParser.add_plugin_argsc                    sd    dkrd  dkrd  dkr4t dd | jD S  sLt dd | jD S t  fd	d| jD S )
z

        The user may have requested help on a topic, return a dict of which
        topics to display. @chosen_topic has prescan_for_flag's return type

        :returns: dict

        r   ry   r   rt   r   c                 S   s$   g | ]}|d kr|dfn|dfqS )zcertbot-route53:authTFr(   r   tr(   r(   r)   r   Y  s   z?HelpfulArgumentParser.determine_help_topics.<locals>.<listcomp>c                 S   s   g | ]}|d fqS )Fr(   r   r(   r(   r)   r   \  s     c                    s   g | ]}|| kfqS r(   r(   r   chosen_topicr(   r)   r   ]  s     )r   r   )r-   r   r(   r   r)   r   H  s    z+HelpfulArgumentParser.determine_help_topicsN)F)r(   )r5   r6   r7   r8   rl   r   r   r   r   r   r   r   r   r   rm   r   r   r   r   r   r(   r(   r(   r)   r     s"   	
J"8"!
r   c                 C   s   | j ddd | j ddd | j ddd | j dd	d | j d
ddddddgd tD ]&\}}|d|}| j ||d d qVd S )Nr   z-Flags for automating execution & other tweaksr   r   z%Security parameters & server settingsr   zHThe following flags are meant for testing and integration purposes only.r   z,Flags for changing execution paths & serversr   zKVarious subcommands and flags are available for managing your certificates:r{   r|   rz   r}   r   )r   r   rx   rv   )r   r   rG   )helpfulr?   Zdocsrc   r(   r(   r)   _add_all_groups_  s    r   c                 C   s  t || |}t| |jdddddtddd |jddd	d
dtd
tjd |jddttddd |jdddddgdddddtddd |jdddddgtjdtddd |jdddddgddd d!d"t	td!d#d$	 |jddddgd%d&d'd(d) |jddddgd*d+d,d-d) |jdddd.d/dd0dgd1d2d3td2d4d5 |jdd6d0dgd7dd8td8d9d: |jddgd;dtd<d=d |jdd>dtd?d?tjd@ |jddAdBdgdCdDtdEt
dEdF |jddAdgdGdtdHdHdId@ |jddAdgdJdKtdHdHdLd@ |jdddgdMdNdOdPdtdPdQd |jddRdtdSdTd |jddUdVdWtjdXdY |jdd0gdZd[d\dtd\d]d |jdd^d_dtd_d`d |jddadbdtdbdcd |jdd0dgdddtdedfd |jddgdhdtdhdid |jdBdgdjdktdldmdn |jddodpdtdpdqd |jddrdtdsdtd |jddudtdvdwd |jddxdtdydzd |jdd{dtd|d}d |jdd0ddgd~dddtddd |jd6ddgddddtddtj d |jd6ddtddd |jdddgddtddd |jd6ddt
dtdd |jd6ddgdtdtdt
dd |jd6dgddtdt
dd |jd6dgdttdt
dd |jd6ddtddd |jddtdtdt
dd |jddddtdt
dd: |jddgdddtddd: |jdddKdtddd: |jddgdddtddd: |jdddKdtdtjd: |jddgdddtddd: |jdddKdtdtjd: |jddddtddd: |jdddKdtdtjd: |jdddtddd |jdddd0gddttddd |jd0ddd |jd0ddd |jd0dttjd |jd0ddKtdădtjd@ |jd0dtdd |jd0ddKdtdȃdd: |jd0ddKtd˃ddd@ |jd0ddtd΃ddd@ |jd0ddKtdуddd@ t|j t| t| t||  |s|a| S )zReturns parsed command line arguments.

    :param .PluginsRegistry plugins: available plugins
    :param list args: command line arguments with the program name removed

    :returns: parsed command line arguments
    :rtype: argparse.Namespace

    Nz-vz	--verboseZverbose_countr   zbThis flag can be used multiple times to incrementally increase the verbosity of output, e.g. -vvv.)rO   rQ   rq   r   z-tz--textZ	text_moder   z--max-log-backupsZmax_log_backupszSpecifies the maximum number of backup logs that should be kept by Certbot's built in log rotation. Setting this flag to 0 disables log rotation entirely, causing Certbot to always append to the same log file.r   rq   r   r   rt   ry   r   z-nz--non-interactivez--noninteractiver   zRun without ever asking for user input. This may require additional command line flags; the client will try to explain which ones are required if it finds one missingr~   r   zForce Certbot to be interactive even if it detects it's not being run in a terminal. This flag cannot be used with the renew subcommand.rQ   rq   r   r{   z-dz	--domainsz--domainr   ZDOMAINaK  Domain names to apply. For multiple domains you can use multiple -d flags or enter a comma separated list of domains as a parameter. The first domain provided will be the subject CN of the certificate, and all domains will be Subject Alternative Names on the certificate. The first domain will also be used in some software user interfaces and as the file paths for the certificate and related material unless otherwise specified or you already have a certificate with the same name. In the case of a name collision it will append a number like 0001 to the file path name. (default: Ask))rO   metavarrQ   rq   r   z	--eab-kidZeab_kidZEAB_KIDz+Key Identifier for External Account Binding)rO   r   r   z--eab-hmac-keyZeab_hmac_keyZEAB_HMAC_KEYz%HMAC key for External Account Bindingr   r|   rz   z--cert-nameZcertnameZCERTNAMEa  Certificate name to apply. This name is used by Certbot for housekeeping and in file paths; it doesn't affect the content of the certificate itself. To see certificate names, run 'certbot certificates'. When creating a new certificate, specifies the new certificate's name. (default: the first provided domain or the name of an existing certificate on your system for the same domains))rO   r   rq   r   r   z	--dry-runr   a  Perform a test run of the client, obtaining test (invalid) certificates but not saving them to disk. This can currently only be used with the 'certonly' and 'renew' subcommands. 
Note: Although --dry-run tries to avoid making any persistent changes on a system, it  is not completely side-effect free: if used with webserver authenticator plugins like apache and nginx, it makes and then reverts temporary config changes in order to obtain test certificates, and reloads webservers to deploy and then roll back those changes.  It also calls --pre-hook and --post-hook commands if they are defined because they may be necessary to accurately simulate renewal. --deploy-hook commands are not called.rQ   rO   rq   r   z!--register-unsafely-without-emailr   a  Specifying this flag enables registering an account with no email address. This is strongly discouraged, because in the event of key loss or account compromise you will irrevocably lose access to your account. You will also be unable to receive notice about impending expiration or revocation of your certificates. Updates to the Subscriber Agreement will still affect you, and will be effective 14 days after posting an update to the web site.z--update-registrationZupdate_registration)rQ   rq   rO   r   r   r   z-mz--emailZemailrq   r   z--eff-emailZ	eff_emailz"Share your e-mail address with EFFz--no-eff-emailr   z(Don't share your e-mail address with EFFz--keep-until-expiringz--keepz--reinstallZ	reinstallzIf the requested certificate matches an existing certificate, always keep the existing one until it is due for renewal (for the 'run' subcommand this means reinstall the existing certificate). (default: Ask)z--expandexpandzIf an existing certificate is a strict subset of the requested names, always expand and replace it with the additional names. (default: Ask)z	--versionr   z%(prog)s {0}z&show program's version number and exit)rQ   r   r   z--force-renewalz--renew-by-defaultZrenew_by_defaultzIf a certificate already exists for the requested domains, renew it now, regardless of whether it is near expiry. (Often --keep-until-expiring is more appropriate). Also implies --expand.z--renew-with-new-domainsZrenew_with_new_domainszIf a certificate already exists for the requested certificate name but does not match the requested domains, renew it now, regardless of whether it is near expiry.z--reuse-keyZ	reuse_keyzDWhen renewing, use the same private key as the existing certificate.z--allow-subset-of-namesr   a8  When performing domain validation, do not consider it a failure if authorizations can not be obtained for a strict subset of the requested domains. This may be useful for allowing renewals for multiple domains to succeed even if some domains no longer point at this system. This option cannot be used with --csr.z--agree-tosr   z5Agree to the ACME Subscriber Agreement (default: Ask)z	--accountZ
ACCOUNT_IDr   zAccount ID to use)r   rq   r   z--duplicateZ	duplicatezdAllow making a certificate lineage that duplicates an existing one (both can be renewed in parallel)z--os-packages-onlyZos_packages_onlyzA(certbot-auto only) install OS package dependencies and then stopz--no-self-upgradeZno_self_upgradez(certbot-auto only) prevent the certbot-auto script from upgrading itself to newer released versions (default: Upgrade automatically)z--no-bootstrapZno_bootstrapz(certbot-auto only) prevent the certbot-auto script from installing OS-level dependencies (default: Prompt to install  OS-wide dependencies, but exit if the user says 'No')z--no-permissions-checkZno_permissions_checkz\(certbot-auto only) skip the check on the file system permissions of the certbot-auto scriptz-qz--quietquietz\Silence all output except errors. Useful for automation via cron. Implies --non-interactive.r}   z--test-certz	--stagingr   z_Use the staging server to obtain or revoke test (invalid) certificates; equivalent to --server z--debugrF   z]Show tracebacks in case of errors, and allow certbot-auto execution on experimental platformsz--debug-challengesZdebug_challengeszHAfter setting up challenges, wait for user input before submitting to CAz--no-verify-sslZno_verify_ssl)rQ   r   rq   
standalonemanualz--http-01-portZhttp01_port)r   rO   rq   r   z--http-01-addressZhttp01_address)rO   rq   r   r   z--https-portZ
https_portz--break-my-certsr   z]Be willing to replace or renew valid certificates with invalid (testing/staging) certificatesr   z--rsa-key-sizeNZrsa_key_sizer   r   rq   r   z--must-stapler   z
--redirectZredirectzbAutomatically redirect all HTTP traffic to HTTPS for the newly authenticated vhost. (default: Ask)z--no-redirectziDo not automatically redirect all HTTP traffic to HTTPS for the newly authenticated vhost. (default: Ask)z--hstsr   zAdd the Strict-Transport-Security header to every HTTP response. Forcing browser to always use SSL for the domain. Defends against SSL Stripping.z	--no-hstsz--uirZuirzAdd the "Content-Security-Policy: upgrade-insecure-requests" header to every HTTP response. Forcing the browser to use https:// for every http:// resource.z--no-uirz--staple-ocspr   zmEnables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS.z--no-staple-ocspz--strict-permissionsZstrict_permissionsz}Require that all configuration files are owned by the current user; only needed if your config is somewhere unsafe like /tmp/z--preferred-challengespref_challsa  A sorted, comma delimited list of the preferred challenge to use during authorization with the most preferred challenge listed first (Eg, "dns" or "http,dns"). Not all plugins support all challenges. See https://certbot.eff.org/docs/using.html#plugins for details. ACME Challenges are versioned, but if you pick "http" rather than "http-01", Certbot will select the latest version automatically.z
--pre-hookaz  Command to be run in a shell before obtaining any certificates. Intended primarily for renewal, where it can be used to temporarily shut down a webserver that might conflict with the standalone plugin. This will only be called if a certificate is actually to be obtained/renewed. When renewing several certificates that have identical pre-hooks, only the first will be executed.r   z--post-hookaK  Command to be run in a shell after attempting to obtain/renew certificates. Can be used to deploy renewed certificates, or to restart any servers that were stopped by --pre-hook. This is only run if an attempt was made to obtain/renew a certificate. If multiple renewed certificates have identical post-hooks, only one will be run.z--renew-hook)rQ   r   z--no-random-sleep-on-renewZrandom_sleep_on_renewz--deploy-hooka  Command to be run in a shell once for each successfully issued certificate. For this command, the shell variable $RENEWED_LINEAGE will point to the config live subdirectory (for example, "/etc/letsencrypt/live/example.com") containing the new certificates and keys; the shell variable $RENEWED_DOMAINS will contain a space-delimited list of renewed certificate domains (for example, "example.com www.example.com"z--disable-hook-validationr   a  Ordinarily the commands specified for --pre-hook/--post-hook/--deploy-hook will be checked for validity, to see if the programs being run are in the $PATH, so that mistakes can be caught early, even when the hooks aren't being run just yet. The validation is rather simplistic and fails if you use more advanced shell constructs, so you can use this switch to disable it. (default: False)z--no-directory-hooksZdirectory_hooksz`Disable running executables found in Certbot's hook directories during renewal. (default: False)z--disable-renew-updatesZdisable_renew_updatesa  Disable automatic updates to your server configuration that would otherwise be done by the selected installer plugin, and triggered when the user executes "certbot renew", regardless of if the certificate is renewed. This setting does not apply to important TLS configuration updates.z--no-autorenewZ	autorenewz%Disable auto renewal of certificates.)r   r   rm   rd   rY   re   nonnegative_intr   r   _DomainsActionrg   r   r   __version__r   int_PrefChallAction_RenewHookAction_DeployHookActionenhancementsZpopulate_cli_create_subparsers_paths_parser_plugins_parsingr<   r   )rH   r>   r9   r   r(   r(   r)   r@   o  s                       
 
    

       
              
   	       	                
                                                        
          
           
r@   c              	   C   sD  ddl m} | jd dtdd| d | jd dtdtd	d
 | jddtdtdd
 | jdddttt	j
t	j
jdttddd | jdddtddd | jddddtddd | jddtd td!d"d# | jd$d%dtd&d'd | jd$d(dtd)d*d | jd$d+d,d-td-tjd.d/ | jd$d0d,d-td-tjd1d/ d S )2Nr   )sample_user_agentz--user-agentZ
user_agenta  Set a custom user agent string for the client. User agent strings allow the CA to collect high level statistics about success rates by OS, plugin and use case, and to know when to deprecate support for past Python versions and flags. If you wish to hide this information from the Let's Encrypt server, set this to "". (default: {0}). The flags encoded in the user agent are: --duplicate, --force-renew, --allow-subset-of-names, -n, and whether any hooks are set.r  z--user-agent-commentZuser_agent_commentzAdd a comment to the default user agent string. May be used when repackaging Certbot or calling it from another tool to allow additional statistical data to be collected. Ignored if --user-agent is set. (Example: Foo-Wrapper/1.0)rq   r   r   ry   z--csrr   z|Path to a Certificate Signing Request (CSR) in DER or PEM format. Currently --csr only works with the 'certonly' subcommand.r}   z--reasonreason)r   z?Specify reason for revoking certificate. (default: unspecified))rO   choicesrQ   rq   r   z--delete-after-revoker   Zdelete_after_revokezjDelete certificates after revoking them, along with all previous and later versions of those certificates.r   z--no-delete-after-revoker   zDo not delete certificates after revoking them. This option should be used with caution because the 'renew' subcommand will attempt to renew undeleted revoked certificates.r   r   z--checkpointsr  Zrollback_checkpointsz-Revert configuration N number of checkpoints.r  rH   z--initZinitzInitialize plugins.z	--prepareZpreparezInitialize and prepare plugins.z--authenticatorsr   Zifacesz$Limit to authenticator plugins only.)rQ   rO   rq   r   r   z--installersz Limit to installer plugins only.)Zcertbot.clientr  rm   rd   r   _user_agent_comment_typer`   CaseInsensitiveListr   r   REVOCATION_REASONSrG   _EncodeReasonActionr  r   ZIAuthenticatorZ
IInstaller)r   r  r(   r(   r)   r    s      
                    r  c                       s    e Zd ZdZ fddZ  ZS )r  a  A list that will ignore case when searching.

    This class is passed to the `choices` argument of `argparse.add_arguments`
    through the `helpful` wrapper. It is necessary due to special handling of
    command line arguments by `set_by_cli` in which the `type_func` is not applied.c                    s   t t| | S r/   )superr  __contains__r   )r-   element	__class__r(   r)   r  3  s    z CaseInsensitiveList.__contains__)r5   r6   r7   r8   r  __classcell__r(   r(   r  r)   r  -  s   r  c                 C   sT  | j }| j}|dkr| j}d}dddddg}|dkrP||dtjjtd	|d
 n0|dkrl||dtd|d n||dtjj|d d}|dkr|}||d|dkrtptjjdd d }|dkrtd}|ddgd|tjjdd |dd|tjjdd |ddtdtdd |ddtdtdd |ddtddd |ddtd td d d S )!Nr   zQPath to where certificate is saved (with auth --csr), installed from, or revoked.r   r   r}   ry   r   z--cert-pathZauth_cert_pathr   F)r   Zrequiredr   )r   r   )r   r}   z
--key-pathzZPath to private key for certificate installation or revocation (if account key is missing)Zauth_chain_pathz--fullchain-pathzGAccompanying path to a full certificate chain (certificate plus chain).r  z--chain-pathz)Accompanying path to a certificate chain.z--config-dirr   r  z
--work-dirZwork_dirz
--logs-dirZlogs_dirzLogs directory.z--serverr   )	rm   r?   r   r   rT   rU   rd   r`   rg   )r   rm   r?   ZcphZsectionsZsectionZ
default_cpr(   r(   r)   r  7  sT     r  c                 C   s~  | j ddd | jddtddd | jddd	td
dd | jdddtddd | jddddgddtddd | jddddgddtddd | jddgddtddd | jddgddtdd d | jddgd!dtd"d#d | jddgd$dtd%d&d | jddgd'dtd(d)d | jddgd*dtd+d,d | jddgd-dtd.d/d | jddgd0dtd1d2d | jddgd3dtd4d5d | jddgd6dtd7d8d | jddgd9dtd:d;d | jddgd<dtd=d>d | jddgd?dtd@dAd | jddgdBdtdCdDd | jddgdEdtdFdGd | jddgdHdtdIdJd | jddgdKdtdLdMd | | d S )NNrH   a$  Plugin Selection: Certbot client supports an extensible plugins architecture. See '%(prog)s plugins' for a list of all installed plugins and their names. You can force a particular plugin by setting options provided below. Running --help <plugin_name> will list flags specific to that plugin.r   z--configuratorZconfiguratorzName of the plugin that is both an authenticator and an installer. Should not be used together with --authenticator or --installer. (default: Ask)r  z-az--authenticatorrB   zAuthenticator plugin name.z-iz--installerrC   z2Installer plugin name (also used to find domains).ry   rt   r   z--apacher   r   z,Obtain and install certificates using Apacher   z--nginxr   z+Obtain and install certificates using Nginxz--standaloner  z3Obtain certificates using a "standalone" webserver.z--manualr  zAProvide laborious manual instructions for obtaining a certificatez	--webrootZwebrootz<Obtain certificates by placing files in a webroot directory.z--dns-cloudflareZdns_cloudflarezQObtain certificates using a DNS TXT record (if you are using Cloudflare for DNS).z--dns-cloudxnsZdns_cloudxnszOObtain certificates using a DNS TXT record (if you are using CloudXNS for DNS).z--dns-digitaloceanZdns_digitaloceanzSObtain certificates using a DNS TXT record (if you are using DigitalOcean for DNS).z--dns-dnsimpleZdns_dnsimplezOObtain certificates using a DNS TXT record (if you are using DNSimple for DNS).z--dns-dnsmadeeasyZdns_dnsmadeeasyzTObtain certificates using a DNS TXT record (if you are using DNS Made Easy for DNS).z--dns-gehirnZ
dns_gehirnzdObtain certificates using a DNS TXT record (if you are using Gehirn Infrastracture Service for DNS).z--dns-googleZ
dns_googlezOObtain certificates using a DNS TXT record (if you are using Google Cloud DNS).z--dns-linodeZ
dns_linodezMObtain certificates using a DNS TXT record (if you are using Linode for DNS).z--dns-luadnsZ
dns_luadnszMObtain certificates using a DNS TXT record (if you are using LuaDNS for DNS).z--dns-nsoneZ	dns_nsonezJObtain certificates using a DNS TXT record (if you are using NS1 for DNS).z	--dns-ovhZdns_ovhzJObtain certificates using a DNS TXT record (if you are using OVH for DNS).z--dns-rfc2136Zdns_rfc2136zKObtain certificates using a DNS TXT record (if you are using BIND for DNS).z--dns-route53Zdns_route53zNObtain certificates using a DNS TXT record (if you are using Route53 for DNS).z--dns-sakuracloudZdns_sakuracloudzSObtain certificates using a DNS TXT record (if you are using Sakura Cloud for DNS).)r   rm   rd   r   )r   rH   r(   r(   r)   r  a  s         	r  c                   @   s   e Zd ZdZdddZdS )r  z+Action class for parsing revocation reason.Nc                 C   s    t j|  }t|| j| dS )z.Encodes the reason for certificate revocation.N)r   r  r   setattrrO   )r-   rN   	namespacer  option_stringcoder(   r(   r)   __call__  s    z_EncodeReasonAction.__call__)Nr5   r6   r7   r8   r&  r(   r(   r(   r)   r    s   r  c                   @   s   e Zd ZdZdddZdS )r
  z!Action class for parsing domains.Nc                 C   s   t || dS )z%Just wrap add_domains in argparseese.N)r   )r-   rN   r#  r   r$  r(   r(   r)   r&    s    z_DomainsAction.__call__)Nr'  r(   r(   r(   r)   r
    s   r
  c                 C   sF   g }| dD ]2}t| }|| || jkr| j| q|S )a  Registers new domains to be used during the current client run.

    Domains are not added to the list of requested domains if they have
    already been registered.

    :param args_or_config: parsed command line arguments
    :type args_or_config: argparse.Namespace or
        configuration.NamespaceConfig
    :param str domain: one or more comma separated domains

    :returns: domains after they have been normalized and validated
    :rtype: `list` of `str`

    ,)splitr   Zenforce_domain_sanitystripappendr   )Zargs_or_configr   Zvalidated_domainsr   r(   r(   r)   r     s    

r   c                   @   s   e Zd ZdZdddZdS )r  z.Action class for parsing preferred challenges.Nc              
   C   sX   zt |d}W n4 tjk
rF } zt| t|W 5 d }~X Y nX |j| d S )Nr(  )	parse_preferred_challengesr)  r
   r   rY   ArgumentErrorrP   r  extend)r-   rN   r#  r  r$  challserrorr(   r(   r)   r&    s
    "z_PrefChallAction.__call__)Nr'  r(   r(   r(   r)   r    s   r  c                    sV   ddd dd | D } fdd|D }d dd	 |D }|rRtd
||S )a   Translate and validate preferred challenges.

    :param pref_challs: list of preferred challenge types
    :type pref_challs: `list` of `str`

    :returns: validated list of preferred challenge types
    :rtype: `list` of `str`

    :raises errors.Error: if pref_challs is invalid

    zdns-01zhttp-01)ZdnsZhttpc                 S   s   g | ]}|  qS r(   )r*  r   cr(   r(   r)   r      s     z.parse_preferred_challenges.<locals>.<listcomp>c                    s   g | ]}  ||qS r(   )rG   r1  aliasesr(   r)   r     s     r   c                 s   s   | ]}|t jjkr|V  qd S r/   )r   Z	ChallengeZTYPES)r   rc   r(   r(   r)   r     s    z-parse_preferred_challenges.<locals>.<genexpr>zUnrecognized challenges: {0})r   r
   r   r   )r  r/  Zunrecognizedr(   r3  r)   r,    s    
r,  c                 C   s   d| ksd| krt d| S )N()zmay not contain parentheses)rY   rZ   )rK   r(   r(   r)   r    s    
r  c                   @   s   e Zd ZdZdddZdS )r  z&Action class for parsing deploy hooks.Nc                 C   s6   |j |jk}|r&|j|kr&t| d| |_ |_d S )Nz!conflicts with --renew-hook value)r   r   rY   r-  )r-   rN   r#  valuesr$  Zrenew_hook_setr(   r(   r)   r&    s     z_DeployHookAction.__call__)Nr'  r(   r(   r(   r)   r    s   r  c                   @   s   e Zd ZdZdddZdS )r  z%Action class for parsing renew hooks.Nc                 C   s.   |j d k	}|r$|j |kr$t| d||_d S )Nz"conflicts with --deploy-hook value)r   rY   r-  r   )r-   rN   r#  r7  r$  Zdeploy_hook_setr(   r(   r)   r&    s    
 z_RenewHookAction.__call__)Nr'  r(   r(   r(   r)   r    s   r  c                 C   sB   zt | }W n tk
r*   tdY nX |dk r>td|S )a[  Converts value to an int and checks that it is not negative.

    This function should used as the type parameter for argparse
    arguments.

    :param str value: value provided on the command line

    :returns: integer representation of value
    :rtype: int

    :raises argparse.ArgumentTypeError: if value isn't a non-negative integer

    zvalue must be an integerr   zvalue must be non-negative)r  
ValueErrorrY   rZ   )rK   Z	int_valuer(   r(   r)   r	  '  s    
r	  )rS   )F)F)fr8   Z
__future__r   rY   ra   r   Zlogging.handlersZloggingr   r   r!   Zzope.componentr   Zzope.interfacer   r   Zacmer   Zacme.magic_typingr   r   r   r   Zcertbot.plugins.enhancementsrH   r  Zcertbot.plugins.selectionZ	selectionrA   r   r	   r
   r   r   Zcertbot.compatr   Zcertbot.displayr   Zcertbot.pluginsr   r=   Z	getLoggerr5   rE   r<   ZLEAUTOenvironrT   basenamer   Zold_path_fragmentrU   sepZnew_path_prefixargvr   Zcli_commandr   r   r   r   r   r%   r   r   r#   r*   objectr+   r:   r;   rL   rM   rR   r`   rd   rg   rh   ZHelpFormatterrp   replacer   r   r   r   r   r@   r  r   r  r  r  ZActionr  r
  r   r  r,  r  r  r  r	  r(   r(   r(   r)   <module>   sL  

  "	""	
	
	
a   /
   =
*_	