Coverage for certbot/main.py : 88%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
"""Certbot main entry point.""" # pylint: disable=too-many-lines
"reinvoke the client.")
"""Potentially suggest a donation to support Certbot.
:param config: Configuration object :type config: interfaces.IConfig
:returns: `None` :rtype: None
""" # --dry-run implies --staging "Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate\n" "Donating to EFF: https://eff.org/donate-le\n\n")
"""Reports on successful dry run
:param config: Configuration object :type config: interfaces.IConfig
:returns: `None` :rtype: None
""" reporter_util.HIGH_PRIORITY, on_crash=False)
"""Authenticate and enroll certificate.
This method finds the relevant lineage, figures out what to do with it, then performs that action. Includes calls to hooks, various reports, checks, and requests for user input.
:param config: Configuration object :type config: interfaces.IConfig
:param domains: List of domain names to get a certificate. Defaults to `None` :type domains: `list` of `str`
:param certname: Name of new certificate. Defaults to `None` :type certname: str
:param lineage: Certificate lineage object. Defaults to `None` :type lineage: storage.RenewableCert
:returns: the issued certificate or `None` if doing a dry run :rtype: storage.RenewableCert or None
:raises errors.Error: if certificate could not be obtained
""" # Renewal, where we already know the specific lineage we're # interested in else: # TREAT AS NEW REQUEST finally:
"""Figure out what to do if a previous cert had a subset of the names now requested
:param config: Configuration object :type config: interfaces.IConfig
:param domains: List of domain names :type domains: `list` of `str`
:param cert: Certificate object :type cert: storage.RenewableCert
:returns: Tuple of (str action, cert_or_None) as per _find_lineage_for_domains_and_certname action can be: "newcert" | "renew" | "reinstall" :rtype: `tuple` of `str`
""" existing = ", ".join(cert.names()) question = ( "You have an existing certificate that contains a portion of " "the domains you requested (ref: {0}){br}{br}It contains these " "names: {1}{br}{br}You requested these names for the new " "certificate: {2}.{br}{br}Do you want to expand and replace this existing " "certificate with the new certificate?" ).format(cert.configfile.filename, existing, ", ".join(domains), br=os.linesep) if config.expand or config.renew_by_default or zope.component.getUtility( interfaces.IDisplay).yesno(question, "Expand", "Cancel", cli_flag="--expand", force_interactive=True): return "renew", cert else: reporter_util = zope.component.getUtility(interfaces.IReporter) reporter_util.add_message( "To obtain a new certificate that contains these names without " "replacing your existing certificate for {0}, you must use the " "--duplicate option.{br}{br}" "For example:{br}{br}{1} --duplicate {2}".format( existing, sys.argv[0], " ".join(sys.argv[1:]), br=os.linesep ), reporter_util.HIGH_PRIORITY) raise errors.Error(USER_CANCELLED)
"""Figure out what to do if a lineage has the same names as a previously obtained one
:param config: Configuration object :type config: interfaces.IConfig
:param lineage: Certificate lineage object :type lineage: storage.RenewableCert
:returns: Tuple of (str action, cert_or_None) as per _find_lineage_for_domains_and_certname action can be: "newcert" | "renew" | "reinstall" :rtype: `tuple` of `str`
""" # Set with --reinstall, force an identical certificate to be # reinstalled without further prompting. question = ( "You have an existing certificate that has exactly the same " "domains or certificate name you requested and isn't close to expiry." "{br}(ref: {0}){br}{br}What would you like to do?" ).format(lineage.configfile.filename, br=os.linesep)
if config.verb == "run": keep_opt = "Attempt to reinstall this existing certificate" elif config.verb == "certonly": keep_opt = "Keep the existing certificate for now" choices = [keep_opt, "Renew & replace the cert (limit ~5 per 7 days)"]
display = zope.component.getUtility(interfaces.IDisplay) response = display.menu(question, choices, default=0, force_interactive=True) if response[0] == display_util.CANCEL: # TODO: Add notification related to command-line options for # skipping the menu for this case. raise errors.Error( "Operation canceled. You may re-run the client.") elif response[1] == 0: return "reinstall", lineage elif response[1] == 1: return "renew", lineage else: assert False, "This is impossible"
"""Determine whether there are duplicated names and how to handle them (renew, reinstall, newcert, or raising an error to stop the client run if the user chooses to cancel the operation when prompted).
:param config: Configuration object :type config: interfaces.IConfig
:param domains: List of domain names :type domains: `list` of `str`
:returns: Two-element tuple containing desired new-certificate behavior as a string token ("reinstall", "renew", or "newcert"), plus either a RenewableCert instance or `None` if renewal shouldn't occur. :rtype: `tuple` of `str` and :class:`storage.RenewableCert` or `None`
:raises errors.Error: If the user would like to rerun the client again.
""" # Considering the possibility that the requested certificate is # related to an existing certificate. (config.duplicate, which # is set with --duplicate, skips all of this logic and forces any # kind of certificate to be obtained with renewal = False.) return "newcert", None # TODO: Also address superset case # XXX ^ schoen is not sure whether that correctly reads the systemwide # configuration file.
elif subset_names_cert is not None: return _handle_subset_cert_request(config, domains, subset_names_cert)
"""Finds an existing certificate object given domains and/or a certificate name.
:param config: Configuration object :type config: interfaces.IConfig
:param domains: List of domain names :type domains: `list` of `str`
:param certname: Name of certificate :type certname: str
:returns: Two-element tuple of a boolean that indicates if this function should be followed by a call to fetch a certificate from the server, and either a RenewableCert instance or None. :rtype: `tuple` of `bool` and :class:`storage.RenewableCert` or `None`
"""
"""Find appropriate lineage based on given domains and/or certname.
:param config: Configuration object :type config: interfaces.IConfig
:param domains: List of domain names :type domains: `list` of `str`
:param certname: Name of certificate :type certname: str
:returns: Two-element tuple containing desired new-certificate behavior as a string token ("reinstall", "renew", or "newcert"), plus either a RenewableCert instance or None if renewal should not occur.
:rtype: `tuple` of `str` and :class:`storage.RenewableCert` or `None`
:raises errors.Error: If the user would like to rerun the client again.
""" else: lineage.names()) # raises if no # unnecessarily specified domains or no domains specified else: else: raise errors.ConfigurationError("No certificate with name {0} found. " "Use -d to specify domains, or run certbot certificates to see " "possible certificate names.".format(certname))
"""Get lists of items removed from `before` and a lists of items added to `after` """
"""Format list with given character """ else: ch=character, br=os.linesep )
"""Ask user to confirm update cert certname to contain new_domains.
:param config: Configuration object :type config: interfaces.IConfig
:param new_domains: List of new domain names :type new_domains: `list` of `str`
:param certname: Name of certificate :type certname: str
:param old_domains: List of old domain names :type old_domains: `list` of `str`
:returns: None :rtype: None
:raises errors.ConfigurationError: if cert name and domains mismatch
""" return
"You are also removing previously included domain(s): {2}{br}{br}" "Did you intend to make this change?".format( certname, _format_list("+", added), _format_list("-", removed), br=os.linesep))
"""Retrieve domains and certname from config or user input.
:param config: Configuration object :type config: interfaces.IConfig
:param installer: Installer object :type installer: interfaces.IInstaller
:param `str` question: Overriding dialog question to ask the user if asked to choose from domain names.
:returns: Two-part tuple of domains and certname :rtype: `tuple` of list of `str` and `str`
:raises errors.Error: Usage message, if parameters are not used correctly
""" # first, try to get domains from the config # if we can't do that but we have a certname, get the domains # with that certname
# that certname might not have existed, or there was a problem. # try to get domains from the user.
"will help in domain names autodiscovery, or " "--cert-name for an existing certificate name.")
"""Reports the creation of a new certificate to the user.
:param cert_path: path to certificate :type cert_path: str
:param fullchain_path: path to full chain :type fullchain_path: str
:param key_path: path to private key, if available :type key_path: str
:returns: `None` :rtype: None
"""
# Print the path to fullchain.pem because that's what modern webservers # (Nginx and Apache2.4) will want.
key_path, br=os.linesep) if key_path else "" # XXX Perhaps one day we could detect the presence of known old webservers # and say something more informative here. '{0}{br}{1}' 'Your cert will expire on {2}. To obtain a new or tweaked version of this ' 'certificate in the future, simply run {3} again{4}. ' 'To non-interactively renew *all* of your certificates, run "{3} renew"' .format(fullchain_path, privkey_statement, expiry, cli.cli_command, verbswitch, br=os.linesep))
"""Determine which account to use.
If ``config.account`` is ``None``, it will be updated based on the user input. Same for ``config.email``.
:param config: Configuration object :type config: interfaces.IConfig
:returns: Account and optionally ACME client API (biproduct of new registration). :rtype: tuple of :class:`certbot.account.Account` and :class:`acme.client.Client`
:raises errors.Error: If unable to register an account with ACME server
""" if config.tos: return True msg = ("Please read the Terms of Service at {0}. You " "must agree in order to register with the ACME " "server at {1}".format( terms_of_service, config.server)) obj = zope.component.getUtility(interfaces.IDisplay) result = obj.yesno(msg, "Agree", "Cancel", cli_flag="--agree-tos", force_interactive=True) if not result: raise errors.Error( "Registration cannot proceed without accepting " "Terms of Service.")
else: else: # no account registered yet config, account_storage, tos_cb=_tos_cb) except errors.MissingCommandlineFlag: raise except errors.Error: logger.debug("", exc_info=True) raise errors.Error( "Unable to register an account with ACME server")
"""Does the user want to delete their now-revoked certs? If run in non-interactive mode, deleting happens automatically.
:param config: parsed command line arguments :type config: interfaces.IConfig
:returns: `None` :rtype: None
:raises errors.Error: If anything goes wrong, including bad user input, if an overlapping archive dir is found for the specified lineage, etc ... """
"later versions of the cert?") force_interactive=True, default=True)
# config.cert_path must have been set # config.certname may have been set
# don't delete if the archive_dir is used by some other lineage configobj.ConfigObj(storage.renewal_file_for_certname(config, config.certname)), config, config.certname) lambda x: x.archive_dir, lambda x: x) 'one lineage is using {0}'.format(archive_dir)) except Exception as e: msg = ('config.default_archive_dir: {0}, config.live_dir: {1}, archive_dir: {2},' 'original exception: {3}') msg = msg.format(config.default_archive_dir, config.live_dir, archive_dir, e) raise errors.Error(msg)
"""Initialize Let's Encrypt Client
:param config: Configuration object :type config: interfaces.IConfig
:param authenticator: Acme authentication handler :type authenticator: interfaces.IAuthenticator :param installer: Installer object :type installer: interfaces.IInstaller
:returns: client: Client object :rtype: client.Client
""" # if authenticator was given, then we will need account... # XXX #crypto_util.validate_key_csr(acc.key) else:
"""Deactivate account on server
:param config: Configuration object :type config: interfaces.IConfig
:param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str`
:returns: `None` :rtype: None
"""
"your account?") default=True)
# delete on boulder # delete local account files
"""Create accounts on the server.
:param config: Configuration object :type config: interfaces.IConfig
:param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str`
:returns: `None` or a string indicating and error :rtype: None or str
""" # TODO: When `certbot register --update-registration` is fully deprecated, # delete the true case of if block "Please use 'cerbot update_account [options]' instead.\n")
# Portion of _determine_account logic to see whether accounts already # exist or not.
# TODO: add a flag to register a duplicate account (this will # also require extending _determine_account's behavior # or else extracting the registration code from there) "duplicate account with this command is currently " "unsupported.") # _determine_account will register an account
"""Modify accounts on the server.
:param config: Configuration object :type config: interfaces.IConfig
:param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str`
:returns: `None` or a string indicating and error :rtype: None or str
""" # Portion of _determine_account logic to see whether accounts already # exist or not.
"new e-mail address must\ncurrently be provided when " "updating a registration.")
# We rely on an exception to interrupt this process if it didn't work. body=acc.regr.body.update(contact=acc_contacts))) # A v1 account being used as a v2 account will result in changing the uri to # the v2 uri. Since it's the same object on disk, put it back to the v1 uri # so that we can also continue to use the account object with acmev1.
"""Install a cert
:param config: Configuration object :type config: interfaces.IConfig
:param le_client: Client object :type le_client: client.Client
:param domains: List of domains :type domains: `list` of `str`
:param lineage: Certificate lineage object. Defaults to `None` :type lineage: storage.RenewableCert
:returns: `None` :rtype: None
"""
path_provider.cert_path, path_provider.chain_path, path_provider.fullchain_path)
"""Install a previously obtained cert in a server.
:param config: Configuration object :type config: interfaces.IConfig
:param plugins: List of plugins :type plugins: `list` of `str`
:returns: `None` :rtype: None
""" # XXX: Update for renewer/RenewableCert # FIXME: be consistent about whether errors are raised or returned from # this function ...
except errors.PluginSelectionError as e: return str(e)
config, "install", allow_multiple=False, custom_prompt=certname_question)[0]
"are not supported by the selected installer") # If cert-path is defined, populate missing (ie. not overridden) values. # Unfortunately this can't be done in argument parser, as certificate # manager needs the access to renewal directory paths # Preflight config check "require --cert-name to be provided")
else: "If your certificate is managed by Certbot, please use --cert-name " "to define which certificate you would like to install.")
# In the case where we don't have certname, we have errored out already lineage = cert_manager.lineage_for_certname(config, config.certname) enhancements.enable(lineage, domains, installer, config)
"""Helper function for install to populate missing config values from lineage defined by --cert-name."""
raise errors.ConfigurationError("Error while reading certificate from path " "{0}".format(config.cert_path)) raise errors.ConfigurationError("Error while reading private key from path " "{0}".format(config.key_path)) """List server software plugins.
:param config: Configuration object :type config: interfaces.IConfig
:param plugins: List of plugins :type plugins: `list` of `str`
:returns: `None` :rtype: None
"""
interfaces.IDisplay).notification, pause=False)
"""Add security enhancements to existing configuration
:param config: Configuration object :type config: interfaces.IConfig
:param plugins: List of plugins :type plugins: `list` of `str`
:returns: `None` :rtype: None
""" # Check that at least one enhancement was requested on command line "the available enhancement types, run:\n\n%s --help enhance\n")
"are not supported by the selected installer")
"your configuration?") config, "enhance", allow_multiple=False, custom_prompt=certname_question)[0] else: "selected enhancements for?") "defined, exiting.")
"""Rollback server configuration changes made during install.
:param config: Configuration object :type config: interfaces.IConfig
:param plugins: List of plugins :type plugins: `list` of `str`
:returns: `None` :rtype: None
"""
"""Show changes made to server config during installation
View checkpoints and associated configuration changes.
:param config: Configuration object :type config: interfaces.IConfig
:param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str`
:returns: `None` :rtype: None
"""
"""Update the certificate file family symlinks
Use the information in the config file to make symlinks point to the correct archive directory.
:param config: Configuration object :type config: interfaces.IConfig
:param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str`
:returns: `None` :rtype: None
"""
"""Rename a certificate
Use the information in the config file to rename an existing lineage.
:param config: Configuration object :type config: interfaces.IConfig
:param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str`
:returns: `None` :rtype: None
""" cert_manager.rename_lineage(config)
"""Delete a certificate
Use the information in the config file to delete an existing lineage.
:param config: Configuration object :type config: interfaces.IConfig
:param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str`
:returns: `None` :rtype: None
"""
"""Display information about certs configured with Certbot
:param config: Configuration object :type config: interfaces.IConfig
:param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str`
:returns: `None` :rtype: None
"""
"""Revoke a previously obtained certificate.
:param config: Configuration object :type config: interfaces.IConfig
:param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str`
:returns: `None` or string indicating error in case of error :rtype: None or str
""" # For user-agent construction
# intentionally not supporting --cert-path & --cert-name together, # to avoid dealing with mismatched values raise errors.Error("Error! Exactly one of --cert-path or --cert-name must be specified!")
config.cert_path[0], config.key_path[0]) else: # revocation by account key except acme_errors.ClientError as e: return str(e)
"""Obtain a certificate and install.
:param config: Configuration object :type config: interfaces.IConfig
:param plugins: List of plugins :type plugins: `list` of `str`
:returns: `None` :rtype: None
""" # TODO: Make run as close to auth + install as possible # Possible difficulties: config.csr was hacked into auth return str(e)
# Preflight check for enhancement support by the selected installer "are not supported by the selected installer")
# TODO: Handle errors from _init_le_client?
certname, lineage)
enhancements.enable(new_lineage, domains, installer, config)
else:
"""Obtain a cert using a user-supplied CSR
This works differently in the CSR case (for now) because we don't have the privkey, and therefore can't construct the files for a lineage. So we just save the cert & chain to disk :/
:param config: Configuration object :type config: interfaces.IConfig
:param client: Client object :type client: client.Client
:returns: `cert_path` and `fullchain_path` as absolute paths to the actual files :rtype: `tuple` of `str`
""" "Dry run: skipping saving certificate to %s", config.cert_path) cert, chain, os.path.normpath(config.cert_path), os.path.normpath(config.chain_path), os.path.normpath(config.fullchain_path))
"""Renew & save an existing cert. Do not install it.
:param config: Configuration object :type config: interfaces.IConfig
:param plugins: List of plugins :type plugins: `list` of `str`
:param lineage: Certificate lineage object :type lineage: storage.RenewableCert
:returns: `None` :rtype: None
:raises errors.PluginSelectionError: MissingCommandlineFlag if supplied parameters do not pass
""" # installers are used in auth mode to determine domain names
lineage.fullchain), pause=False) else: # In case of a renewal, reload server to pick up new certificate. # In principle we could have a configuration option to inhibit this # from happening. # Run deployer config.installer, lineage.fullchain), pause=False)
"""Authenticate & obtain cert, but do not install it.
This implements the 'certonly' subcommand.
:param config: Configuration object :type config: interfaces.IConfig
:param plugins: List of plugins :type plugins: `list` of `str`
:returns: `None` :rtype: None
:raises errors.Error: If specified plugin could not be used
""" # SETUP: Select plugins and construct a client instance # installers are used in auth mode to determine domain names
"""Renew previously-obtained certificates.
:param config: Configuration object :type config: interfaces.IConfig
:param unused_plugins: List of plugins (deprecated) :type unused_plugins: `list` of `str`
:returns: `None` :rtype: None
""" finally:
"""Create or verify existence of config, work, and hook directories.
:param config: Configuration object :type config: interfaces.IConfig
:returns: `None` :rtype: None
""" compat.os_geteuid(), config.strict_permissions) compat.os_geteuid(), config.strict_permissions)
config.renewal_deploy_hooks_dir, config.renewal_post_hooks_dir,) uid=compat.os_geteuid(), strict=config.strict_permissions)
"""Set the displayer
:param config: Configuration object :type config: interfaces.IConfig
:returns: `None` :rtype: None
""" # type: Union[None, display_util.NoninteractiveDisplay, display_util.FileDisplay] else: config.force_interactive)
"""Command line argument parsing and main script execution.
:returns: result of requested command
:raises errors.Error: OS errors triggered by wrong permissions :raises errors.Error: error if plugin command is not supported
"""
# do not log `config`, as it contains sensitive data (e.g. revoke --key)!
# note: arg parser internally handles --help (and exits afterwards)
# On windows, shell without administrative right cannot create symlinks required by certbot. # So we check the rights before continuing.
# Let plugins_cmd be run as un-privileged user. raise
# Reporter
err_string = main() if err_string: logger.warning("Exiting with message %s", err_string) sys.exit(err_string) # pragma: no cover |