"""Let's Encrypt CLI.""" # TODO: Sanity check all input. Be sure to avoid shell code etc... import argparse import atexit import logging import logging.handlers import os import sys import time import configargparse import zope.component import zope.interface.exceptions import zope.interface.verify import letsencrypt from letsencrypt import account from letsencrypt import configuration from letsencrypt import constants from letsencrypt import client from letsencrypt import errors from letsencrypt import interfaces from letsencrypt import le_util from letsencrypt import log from letsencrypt import reporter from letsencrypt.display import util as display_util from letsencrypt.display import ops as display_ops from letsencrypt.plugins import disco as plugins_disco # Argparse's help formatting has a lot of unhelpful peculiarities, so we want # to replace as much of it as we can... # This is the stub to include in help generated by argparse SHORT_USAGE = """ letsencrypt [SUBCOMMAND] [options] [domains] The Let's Encrypt agent can obtain and install HTTPS/TLS/SSL certificates. By default, it will attempt to use a webserver both for obtaining and installing the cert. """ # This is the short help for letsencrypt --help, where we disable argparse # altogether USAGE = SHORT_USAGE + """Major SUBCOMMANDS are: (default) everything Obtain & install a cert in your current webserver auth Authenticate & obtain cert, but do not install it install Install a previously obtained cert in a server revoke Revoke a previously obtained certificate rollback Rollback server configuration changes made during install config-changes Show changes made to server config during installation Choice of server for authentication/installation: --apache Use the Apache plugin for authentication & installation --nginx Use the Nginx plugin for authentication & installation --standalone Run a standalone HTTPS server (for authentication only) OR: --authenticator standalone --installer nginx More detailed help: -h, --help [topic] print this message, or detailed help on a topic; the available topics are: all, apache, automation, nginx, paths, security, testing, or any of the sucommands """ logger = logging.getLogger(__name__) def _account_init(args, config): # Prepare for init of Client if args.email is None: return client.determine_account(config) else: try: # The way to get the default would be args.email = "" # First try existing account return account.Account.from_existing_account(config, args.email) except errors.LetsEncryptClientError: try: # Try to make an account based on the email address return account.Account.from_email(config, args.email) except errors.LetsEncryptClientError: return None def _find_domains(args, installer): if args.domains is None: domains = display_ops.choose_names(installer) else: domains = args.domains if not domains: raise errors.Error("Please specify --domains, or --installer that " "will help in domain names autodiscovery") return domains def _init_acme(config, acc, authenticator, installer): acme = client.Client(config, acc, authenticator, installer) # Validate the key and csr client.validate_key_csr(acc.key) if authenticator is not None: if acc.regr is None: try: acme.register() except errors.LetsEncryptClientError as error: logger.debug(error) raise errors.Error("Unable to register an account with ACME " "server") return acme def run(args, config, plugins): """Obtain a certificate and install.""" acc = _account_init(args, config) if acc is None: return None if args.configurator is not None and (args.installer is not None or args.authenticator is not None): return ("Either --configurator or --authenticator/--installer" "pair, but not both, is allowed") if args.authenticator is not None or args.installer is not None: installer = display_ops.pick_installer( config, args.installer, plugins) authenticator = display_ops.pick_authenticator( config, args.authenticator, plugins) else: # TODO: this assume that user doesn't want to pick authenticator # and installer separately... authenticator = installer = display_ops.pick_configurator( config, args.configurator, plugins) if installer is None or authenticator is None: return "Configurator could not be determined" domains = _find_domains(args, installer) # TODO: Handle errors from _init_acme? acme = _init_acme(config, acc, authenticator, installer) lineage = acme.obtain_and_enroll_certificate( domains, authenticator, installer, plugins) if not lineage: return "Certificate could not be obtained" acme.deploy_certificate(domains, lineage.privkey, lineage.cert, lineage.chain) acme.enhance_config(domains, args.redirect) def auth(args, config, plugins): """Authenticate & obtain cert, but do not install it.""" # XXX: Update for renewer / RenewableCert if args.domains is not None and args.csr is not None: # TODO: --csr could have a priority, when --domains is # supplied, check if CSR matches given domains? return "--domains and --csr are mutually exclusive" acc = _account_init(args, config) if acc is None: return None authenticator = display_ops.pick_authenticator( config, args.authenticator, plugins) if authenticator is None: return "Authenticator could not be determined" if args.installer is not None: installer = display_ops.pick_installer(config, args.installer, plugins) else: installer = None # TODO: Handle errors from _init_acme? acme = _init_acme(config, acc, authenticator, installer) if args.csr is not None: certr, chain = acme.obtain_certificate_from_csr(le_util.CSR( file=args.csr[0], data=args.csr[1], form="der")) acme.save_certificate(certr, chain, args.cert_path, args.chain_path) else: domains = _find_domains(args, installer) if not acme.obtain_and_enroll_certificate( domains, authenticator, installer, plugins): return "Certificate could not be obtained" def install(args, config, plugins): """Install a previously obtained cert in a server.""" # XXX: Update for renewer/RenewableCert acc = _account_init(args, config) if acc is None: return None installer = display_ops.pick_installer(config, args.installer, plugins) if installer is None: return "Installer could not be determined" domains = _find_domains(args, installer) acme = _init_acme(config, acc, authenticator=None, installer=installer) assert args.cert_path is not None acme.deploy_certificate(domains, acc.key.file, args.cert_path, args.chain_path) acme.enhance_config(domains, args.redirect) def revoke(args, unused_config, unused_plugins): """Revoke a previously obtained certificate.""" if args.rev_cert is None and args.rev_key is None: return "At least one of --certificate or --key is required" # This depends on the renewal config and cannot be completed yet. zope.component.getUtility(interfaces.IDisplay).notification( "Revocation is not available with the new Boulder server yet.") #client.revoke(args.installer, config, plugins, args.no_confirm, # args.rev_cert, args.rev_key) def rollback(args, config, plugins): """Rollback server configuration changes made during install.""" client.rollback(args.installer, args.checkpoints, config, plugins) def config_changes(unused_args, config, unused_plugins): """Show changes made to server config during installation View checkpoints and associated configuration changes. """ client.view_config_changes(config) def plugins_cmd(args, config, plugins): # TODO: Use IDiplay rathern than print """List server software plugins.""" logger.debug("Expected interfaces: %s", args.ifaces) ifaces = [] if args.ifaces is None else args.ifaces filtered = plugins.ifaces(ifaces) logger.debug("Filtered plugins: %r", filtered) if not args.init and not args.prepare: print str(filtered) return filtered.init(config) verified = filtered.verify(ifaces) logger.debug("Verified plugins: %r", verified) if not args.prepare: print str(verified) return verified.prepare() available = verified.available() logger.debug("Prepared plugins: %s", available) print str(available) def read_file(filename, mode="rb"): """Returns the given file's contents. :param str filename: Filename :param str mode: open mode (see `open`) :returns: A tuple of filename and its contents :rtype: tuple :raises argparse.ArgumentTypeError: File does not exist or is not readable. """ try: return filename, open(filename, mode).read() except IOError as exc: raise argparse.ArgumentTypeError(exc.strerror) def flag_default(name): """Default value for CLI flag.""" return constants.CLI_DEFAULTS[name] def config_help(name, hidden=False): """Help message for `.IConfig` attribute.""" if hidden: return argparse.SUPPRESS else: return interfaces.IConfig[name].__doc__ class SilentParser(object): # pylint: disable=too-few-public-methods """Silent wrapper around argparse. A mini parser wrapper that doesn't print help for its arguments. This is needed for the use of callbacks to define arguments within plugins. """ def __init__(self, parser): self.parser = parser def add_argument(self, *args, **kwargs): """Wrap, but silence help""" kwargs["help"] = argparse.SUPPRESS self.parser.add_argument(*args, **kwargs) HELP_TOPICS = ["all", "security", "paths", "automation", "testing"] class HelpfulArgumentParser(object): """Argparse Wrapper. This class wraps argparse, adding the ability to make --help less verbose, and request help on specific subcategories at a time, eg 'letsencrypt --help security' for security options. """ def __init__(self, args, plugins): self.args = args plugin_names = [name for name, _p in plugins.iteritems()] self.help_topics = HELP_TOPICS + plugin_names self.parser = configargparse.ArgParser( usage=SHORT_USAGE, formatter_class=argparse.ArgumentDefaultsHelpFormatter, args_for_setting_config_path=["-c", "--config"], default_config_files=flag_default("config_files")) # This is the only way to turn off overly verbose config flag documentation self.parser._add_config_file_help = False # pylint: disable=protected-access self.silent_parser = SilentParser(self.parser) help1 = self.prescan_for_flag("-h", self.help_topics) help2 = self.prescan_for_flag("--help", self.help_topics) assert max(True, "a") == "a", "Gravity changed direction" help_arg = max(help1, help2) if help_arg == True: # just --help with no topic; avoid argparse altogether print USAGE sys.exit(0) self.visible_topics = self.determine_help_topics(help_arg) #print self.visible_topics self.groups = {} # elements are added by .add_group() self.add_plugin_args(plugins) def prescan_for_flag(self, flag, possible_arguments): """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. """ if flag not in self.args: return False pos = self.args.index(flag) try: nxt = self.args[pos + 1] if nxt in possible_arguments: return nxt except IndexError: pass return True def add(self, topic, *args, **kwargs): """Add a new command line argument. @topic is required, to indicate which part of the help will document it, but can be None for `always documented'. """ if topic and self.visible_topics[topic]: group = self.groups[topic] group.add_argument(*args, **kwargs) else: kwargs["help"] = argparse.SUPPRESS self.parser.add_argument(*args, **kwargs) def add_group(self, topic, **kwargs): """ This has to be called once for every topic; but we leave those calls next to the argument definitions for clarity. Return something arguments can be added to if necessary, either the parser or an argument group. """ if self.visible_topics[topic]: #print "Adding visible group " + topic group = self.parser.add_argument_group(topic, **kwargs) self.groups[topic] = group return group else: #print "Invisible group " + topic return self.silent_parser def add_plugin_args(self, plugins): """ Let each of the plugins add its own command line arguments, which may or may not be displayed as help topics. """ # TODO: plugin_parser should be called for every detected plugin for name, plugin_ep in plugins.iteritems(): parser_or_group = self.add_group(name, description=plugin_ep.description) #print parser_or_group plugin_ep.plugin_cls.inject_parser_options(parser_or_group, name) def determine_help_topics(self, chosen_topic): """ 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 """ # topics maps each topic to whether it should be documented by # argparse on the command line if chosen_topic == "all": return dict([(t, True) for t in self.help_topics]) elif not chosen_topic: return dict([(t, False) for t in self.help_topics]) else: return dict([(t, t == chosen_topic) for t in self.help_topics]) def create_parser(plugins, args): """Create parser.""" helpful = HelpfulArgumentParser(args, plugins) helpful.add( None, "-v", "--verbose", dest="verbose_count", action="count", default=flag_default("verbose_count"), help="This flag can be used " "multiple times to incrementally increase the verbosity of output, " "e.g. -vvv.") # --help is automatically provided by argparse helpful.add_group( "automation", description="Arguments for automating execution & other tweaks") helpful.add( "automation", "--version", action="version", version="%(prog)s {0}".format(letsencrypt.__version__), help="show program's version number and exit") helpful.add( "automation", "--no-confirm", dest="no_confirm", action="store_true", help="Turn off confirmation screens, currently used for --revoke") helpful.add( "automation", "--agree-eula", "-e", dest="tos", action="store_true", help="Agree to the Let's Encrypt Subscriber Agreement") helpful.add( None, "-t", "--text", dest="text_mode", action="store_true", help="Use the text output instead of the curses UI.") helpful.add_group( "testing", description="The following flags are meant for " "testing purposes only! Do NOT change them, unless you " "really know what you're doing!") helpful.add( "testing", "--debug", action="store_true", help="Show tracebacks if the program exits abnormally") helpful.add( "testing", "--no-verify-ssl", action="store_true", help=config_help("no_verify_ssl"), default=flag_default("no_verify_ssl")) # TODO: apache and nginx plugins do NOT respect it helpful.add( "testing", "--dvsni-port", type=int, default=flag_default("dvsni_port"), help=config_help("dvsni_port")) helpful.add("testing", "--no-simple-http-tls", action="store_true", help=config_help("no_simple_http_tls")) subparsers = helpful.parser.add_subparsers(metavar="SUBCOMMAND") def add_subparser(name, func): # pylint: disable=missing-docstring subparser = subparsers.add_parser( name, help=func.__doc__.splitlines()[0], description=func.__doc__) subparser.set_defaults(func=func) return subparser add_subparser("run", run) parser_auth = add_subparser("auth", auth) add_subparser("install", install) parser_revoke = add_subparser("revoke", revoke) parser_rollback = add_subparser("rollback", rollback) add_subparser("config_changes", config_changes) parser_auth.add_argument( "--csr", type=read_file, help="Path to a Certificate Signing " "Request (CSR) in DER format.") parser_auth.add_argument( "--cert-path", default=flag_default("cert_path"), help="When using --csr this is where certificate is saved.") parser_auth.add_argument( "--chain-path", default=flag_default("chain_path"), help="When using --csr this is where certificate chain is saved.") parser_plugins = add_subparser("plugins", plugins_cmd) parser_plugins.add_argument("--init", action="store_true") parser_plugins.add_argument("--prepare", action="store_true") parser_plugins.add_argument( "--authenticators", action="append_const", dest="ifaces", const=interfaces.IAuthenticator) parser_plugins.add_argument( "--installers", action="append_const", dest="ifaces", const=interfaces.IInstaller) helpful.add(None, "--configurator") helpful.add(None, "-a", "--authenticator") helpful.add(None, "-i", "--installer") # positional arg shadows --domains, instead of appending, and # --domains is useful, because it can be stored in config #for subparser in parser_run, parser_auth, parser_install: # subparser.add_argument("domains", nargs="*", metavar="domain") helpful.add(None, "-d", "--domains", metavar="DOMAIN", action="append") helpful.add(None, "-k", "--accountkey", type=read_file, help="Path to the account key file") helpful.add(None, "-m", "--email", help=config_help("email")) helpful.add_group( "security", description="Security parameters & server settings") helpful.add( "security", "-B", "--rsa-key-size", type=int, metavar="N", default=flag_default("rsa_key_size"), help=config_help("rsa_key_size")) # TODO: resolve - assumes binary logic while client.py assumes ternary. helpful.add( "security", "-r", "--redirect", action="store_true", help="Automatically redirect all HTTP traffic to HTTPS for the newly " "authenticated vhost.") parser_revoke.add_argument( "--certificate", dest="rev_cert", type=read_file, metavar="CERT_PATH", help="Revoke a specific certificate.") parser_revoke.add_argument( "--key", dest="rev_key", type=read_file, metavar="KEY_PATH", help="Revoke all certs generated by the provided authorized key.") parser_rollback.add_argument( "--checkpoints", type=int, metavar="N", default=flag_default("rollback_checkpoints"), help="Revert configuration N number of checkpoints.") _paths_parser(helpful) return helpful.parser def _paths_parser(helpful): add = helpful.add helpful.add_group("paths", description="Arguments changing execution paths & servers") add("paths", "--config-dir", default=flag_default("config_dir"), help=config_help("config_dir")) add("paths", "--work-dir", default=flag_default("work_dir"), help=config_help("work_dir")) add("paths", "--logs-dir", default=flag_default("logs_dir"), help="Path to a directory where logs are stored.") add("paths", "--backup-dir", default=flag_default("backup_dir"), help=config_help("backup_dir")) add("paths", "--key-dir", default=flag_default("key_dir"), help=config_help("key_dir")) add("paths", "--cert-dir", default=flag_default("certs_dir"), help=config_help("cert_dir")) add("paths", "--le-vhost-ext", default="-le-ssl.conf", help=config_help("le_vhost_ext")) add("paths", "--renewer-config-file", default=flag_default("renewer_config_file"), help=config_help("renewer_config_file")) add("paths", "-s", "--server", default=flag_default("server"), help=config_help("server")) def _setup_logging(args): level = -args.verbose_count * 10 fmt = "%(asctime)s:%(levelname)s:%(name)s:%(message)s" if args.text_mode: handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(fmt)) else: handler = log.DialogHandler() # dialog box is small, display as less as possible handler.setFormatter(logging.Formatter("%(message)s")) handler.setLevel(level) # TODO: use fileConfig? # unconditionally log to file for debugging purposes # TODO: change before release? log_file_name = os.path.join(args.logs_dir, 'letsencrypt.log') file_handler = logging.handlers.RotatingFileHandler( log_file_name, maxBytes=2**20, backupCount=10) # rotate on each invocation, rollover only possible when maxBytes # is nonzero and backupCount is nonzero, so we set maxBytes as big # as possible not to overrun in single CLI invocation (1MB). file_handler.doRollover() # TODO: creates empty letsencrypt.log.1 file file_handler.setLevel(logging.DEBUG) file_handler_formatter = logging.Formatter(fmt=fmt) file_handler_formatter.converter = time.gmtime # don't use localtime file_handler.setFormatter(file_handler_formatter) root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) # send all records to handlers root_logger.addHandler(handler) root_logger.addHandler(file_handler) logger.debug("Root logging level set at %d", level) logger.info("Saving debug log to %s", log_file_name) def main2(cli_args, args, config, plugins): """Continued main script execution.""" # Displayer if args.text_mode: displayer = display_util.FileDisplay(sys.stdout) else: displayer = display_util.NcursesDisplay() zope.component.provideUtility(displayer) for directory in config.config_dir, config.work_dir: le_util.make_or_verify_dir( directory, constants.CONFIG_DIRS_MODE, os.geteuid()) # TODO: logs might contain sensitive data such as contents of the # private key! #525 le_util.make_or_verify_dir(args.logs_dir, 0o700, os.geteuid()) _setup_logging(args) # do not log `args`, as it contains sensitive data (e.g. revoke --key)! logger.debug("Arguments: %r", cli_args) logger.debug("Discovered plugins: %r", plugins) # Reporter report = reporter.Reporter() zope.component.provideUtility(report) atexit.register(report.atexit_print_messages) if not os.geteuid() == 0: logger.warning( "Root (sudo) is required to run most of letsencrypt functionality.") # check must be done after arg parsing as --help should work # w/o root; on the other hand, e.g. "letsencrypt run # --authenticator dns" or "letsencrypt plugins" does not # require root as well #return ( # "{0}Root is required to run letsencrypt. Please use sudo.{0}" # .format(os.linesep)) return args.func(args, config, plugins) def main(cli_args=sys.argv[1:]): """Command line argument parsing and main script execution.""" # note: arg parser internally handles --help (and exits afterwards) plugins = plugins_disco.PluginsRegistry.find_all() args = create_parser(plugins, cli_args).parse_args(cli_args) config = configuration.NamespaceConfig(args) def handle_exception_common(): """Logs the exception and reraises it if in debug mode.""" logger.debug("Exiting abnormally", exc_info=True) if args.debug: raise try: return main2(cli_args, args, config, plugins) except errors.Error as error: handle_exception_common() return error except KeyboardInterrupt: handle_exception_common() # Ensures a new line is printed return "" except: # pylint: disable=bare-except handle_exception_common() return ("An unexpected error occured. Please see the logfiles in {0} " "for more details.".format(args.logs_dir)) if __name__ == "__main__": sys.exit(main()) # pragma: no cover