response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Deactivate account on server :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` or a string indicating an error :rtype: None or str
def unregister(config: configuration.NamespaceConfig, unused_plugins: plugins_disco.PluginsRegistry) -> Optional[str]: """Deactivate account on server :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` or a string indicating an error :rtype: None or str """ account_storage = account.AccountFileStorage(config) accounts = account_storage.find_all() if not accounts: return f"Could not find existing account for server {config.server}." prompt = ("Are you sure you would like to irrevocably deactivate " "your account?") wants_deactivate = display_util.yesno(prompt, yes_label='Deactivate', no_label='Abort', default=True) if not wants_deactivate: return "Deactivation aborted." acc, acme = _determine_account(config) cb_client = client.Client(config, acc, None, None, acme=acme) if not cb_client.acme: raise errors.Error("ACME client is not set.") # delete on boulder cb_client.acme.deactivate_registration(acc.regr) account_files = account.AccountFileStorage(config) # delete local account files account_files.delete(config.account) display_util.notify("Account deactivated.") return None
Create accounts on the server. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` or a string indicating an error :rtype: None or str
def register(config: configuration.NamespaceConfig, unused_plugins: plugins_disco.PluginsRegistry) -> Optional[str]: """Create accounts on the server. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` or a string indicating an error :rtype: None or str """ # Portion of _determine_account logic to see whether accounts already # exist or not. account_storage = account.AccountFileStorage(config) accounts = account_storage.find_all() if accounts: # 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) return ("There is an existing account; registration of a " "duplicate account with this command is currently " "unsupported.") # _determine_account will register an account _determine_account(config) return None
Modify accounts on the server. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` or a string indicating an error :rtype: None or str
def update_account(config: configuration.NamespaceConfig, unused_plugins: plugins_disco.PluginsRegistry) -> Optional[str]: """Modify accounts on the server. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` or a string indicating an error :rtype: None or str """ # Portion of _determine_account logic to see whether accounts already # exist or not. account_storage = account.AccountFileStorage(config) accounts = account_storage.find_all() if not accounts: return f"Could not find an existing account for server {config.server}." if config.email is None and not config.register_unsafely_without_email: config.email = display_ops.get_email(optional=False) acc, acme = _determine_account(config) cb_client = client.Client(config, acc, None, None, acme=acme) if not cb_client.acme: raise errors.Error("ACME client is not set.") # Empty list of contacts in case the user is removing all emails acc_contacts: Iterable[str] = () if config.email: acc_contacts = ['mailto:' + email for email in config.email.split(',')] # We rely on an exception to interrupt this process if it didn't work. prev_regr_uri = acc.regr.uri acc.regr = cb_client.acme.update_registration(acc.regr.update( 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. acc.regr = acc.regr.update(uri=prev_regr_uri) account_storage.update_regr(acc) if not config.email: display_util.notify("Any contact information associated " "with this account has been removed.") else: eff.prepare_subscription(config, acc) display_util.notify("Your e-mail address was updated to {0}.".format(config.email)) return None
Fetch account info from the ACME server and show it to the user. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` or a string indicating an error :rtype: None or str
def show_account(config: configuration.NamespaceConfig, unused_plugins: plugins_disco.PluginsRegistry) -> Optional[str]: """Fetch account info from the ACME server and show it to the user. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` or a string indicating an error :rtype: None or str """ # Portion of _determine_account logic to see whether accounts already # exist or not. account_storage = account.AccountFileStorage(config) accounts = account_storage.find_all() if not accounts: return f"Could not find an existing account for server {config.server}." acc, acme = _determine_account(config) cb_client = client.Client(config, acc, None, None, acme=acme) if not cb_client.acme: raise errors.Error("ACME client is not set.") regr = cb_client.acme.query_registration(acc.regr) output = [f"Account details for server {config.server}:", f" Account URL: {regr.uri}"] thumbprint = b64.b64encode(acc.key.thumbprint()).decode() output.append(f" Account Thumbprint: {thumbprint}") emails = [] for contact in regr.body.contact: if contact.startswith('mailto:'): emails.append(contact[7:]) output.append(" Email contact{}: {}".format( "s" if len(emails) > 1 else "", ", ".join(emails) if len(emails) > 0 else "none")) display_util.notify("\n".join(output)) return None
Install a cert :param config: Configuration object :type config: configuration.NamespaceConfig :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
def _install_cert(config: configuration.NamespaceConfig, le_client: client.Client, domains: List[str], lineage: Optional[storage.RenewableCert] = None) -> None: """Install a cert :param config: Configuration object :type config: configuration.NamespaceConfig :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: Union[storage.RenewableCert, configuration.NamespaceConfig] = lineage if lineage else config assert path_provider.cert_path is not None le_client.deploy_certificate(domains, path_provider.key_path, path_provider.cert_path, path_provider.chain_path, path_provider.fullchain_path) le_client.enhance_config(domains, path_provider.chain_path)
Install a previously obtained cert in a server. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` or the error message :rtype: None or str
def install(config: configuration.NamespaceConfig, plugins: plugins_disco.PluginsRegistry) -> Optional[str]: """Install a previously obtained cert in a server. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` or the error message :rtype: None or str """ # XXX: Update for renewer/RenewableCert # FIXME: be consistent about whether errors are raised or returned from # this function ... try: installer, _ = plug_sel.choose_configurator_plugins(config, plugins, "install") except errors.PluginSelectionError as e: return str(e) custom_cert = (config.key_path and config.cert_path) if not config.certname and not custom_cert: certname_question = "Which certificate would you like to install?" config.certname = cert_manager.get_certnames( config, "install", allow_multiple=False, custom_prompt=certname_question)[0] if not enhancements.are_supported(config, installer): raise errors.NotSupportedError("One ore more of the requested enhancements " "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 if config.certname: config = _populate_from_certname(config) elif enhancements.are_requested(config): # Preflight config check raise errors.ConfigurationError("One or more of the requested enhancements " "require --cert-name to be provided") if config.key_path and config.cert_path: _check_certificate_and_key(config) domains, _ = _find_domains_or_certname(config, installer) le_client = _init_le_client(config, authenticator=None, installer=installer) _install_cert(config, le_client, domains) else: raise errors.ConfigurationError("Path to certificate or key was not defined. " "If your certificate is managed by Certbot, please use --cert-name " "to define which certificate you would like to install.") if enhancements.are_requested(config): # 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) return None
Helper function for install to populate missing config values from lineage defined by --cert-name.
def _populate_from_certname(config: configuration.NamespaceConfig) -> configuration.NamespaceConfig: """Helper function for install to populate missing config values from lineage defined by --cert-name.""" lineage = cert_manager.lineage_for_certname(config, config.certname) if not lineage: return config if not config.key_path: config.key_path = lineage.key_path if not config.cert_path: config.cert_path = lineage.cert_path if not config.chain_path: config.chain_path = lineage.chain_path if not config.fullchain_path: config.fullchain_path = lineage.fullchain_path return config
List server software plugins. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None
def plugins_cmd(config: configuration.NamespaceConfig, plugins: plugins_disco.PluginsRegistry) -> None: """List server software plugins. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None """ logger.debug("Expected interfaces: %s", config.ifaces) ifaces = [] if config.ifaces is None else config.ifaces filtered = plugins.visible().ifaces(ifaces) logger.debug("Filtered plugins: %r", filtered) notify = functools.partial(display_util.notification, pause=False) if not config.init and not config.prepare: notify(str(filtered)) return filtered.init(config) logger.debug("Filtered plugins: %r", filtered) if not config.prepare: notify(str(filtered)) return filtered.prepare() available = filtered.available() logger.debug("Prepared plugins: %s", available) notify(str(available))
Add security enhancements to existing configuration :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` or a string indicating an error :rtype: None or str
def enhance(config: configuration.NamespaceConfig, plugins: plugins_disco.PluginsRegistry) -> Optional[str]: """Add security enhancements to existing configuration :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` or a string indicating an error :rtype: None or str """ supported_enhancements = ["hsts", "redirect", "uir", "staple"] # Check that at least one enhancement was requested on command line oldstyle_enh = any(getattr(config, enh) for enh in supported_enhancements) if not enhancements.are_requested(config) and not oldstyle_enh: msg = ("Please specify one or more enhancement types to configure. To list " "the available enhancement types, run:\n\n%s --help enhance\n") logger.error(msg, cli.cli_command) raise errors.MisconfigurationError("No enhancements requested, exiting.") try: installer, _ = plug_sel.choose_configurator_plugins(config, plugins, "enhance") except errors.PluginSelectionError as e: return str(e) if not enhancements.are_supported(config, installer): raise errors.NotSupportedError("One ore more of the requested enhancements " "are not supported by the selected installer") certname_question = ("Which certificate would you like to use to enhance " "your configuration?") config.certname = cert_manager.get_certnames( config, "enhance", allow_multiple=False, custom_prompt=certname_question)[0] cert_domains = cert_manager.domains_for_certname(config, config.certname) if cert_domains is None: raise errors.Error("Could not find the list of domains for the given certificate name.") if config.noninteractive_mode: domains = cert_domains else: domain_question = ("Which domain names would you like to enable the " "selected enhancements for?") domains = display_ops.choose_values(cert_domains, domain_question) if not domains: raise errors.Error("User cancelled the domain selection. No domains " "defined, exiting.") lineage = cert_manager.lineage_for_certname(config, config.certname) if not lineage: raise errors.Error("Could not find the lineage for the given certificate name.") if not config.chain_path: config.chain_path = lineage.chain_path if oldstyle_enh: le_client = _init_le_client(config, authenticator=None, installer=installer) le_client.enhance_config(domains, config.chain_path, redirect_default=False) if enhancements.are_requested(config): enhancements.enable(lineage, domains, installer, config) return None
Rollback server configuration changes made during install. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None
def rollback(config: configuration.NamespaceConfig, plugins: plugins_disco.PluginsRegistry) -> None: """Rollback server configuration changes made during install. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None """ client.rollback(config.installer, config.checkpoints, config, plugins)
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: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None
def update_symlinks(config: configuration.NamespaceConfig, unused_plugins: plugins_disco.PluginsRegistry) -> 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: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None """ warnings.warn("update_symlinks is deprecated and will be removed", PendingDeprecationWarning) cert_manager.update_live_symlinks(config)
Rename a certificate Use the information in the config file to rename an existing lineage. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None
def rename(config: configuration.NamespaceConfig, unused_plugins: plugins_disco.PluginsRegistry) -> None: """Rename a certificate Use the information in the config file to rename an existing lineage. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :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: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None
def delete(config: configuration.NamespaceConfig, unused_plugins: plugins_disco.PluginsRegistry) -> None: """Delete a certificate Use the information in the config file to delete an existing lineage. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None """ cert_manager.delete(config)
Display information about certs configured with Certbot :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None
def certificates(config: configuration.NamespaceConfig, unused_plugins: plugins_disco.PluginsRegistry) -> None: """Display information about certs configured with Certbot :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None """ cert_manager.certificates(config)
Revoke a previously obtained certificate. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` or string indicating error in case of error :rtype: None or str
def revoke(config: configuration.NamespaceConfig, unused_plugins: plugins_disco.PluginsRegistry) -> Optional[str]: """Revoke a previously obtained certificate. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` or string indicating error in case of error :rtype: None or str """ # For user-agent construction config.installer = config.authenticator = None if config.cert_path is None and config.certname: # When revoking via --cert-name, take the cert path and server from renewalparams lineage = storage.RenewableCert( storage.renewal_file_for_certname(config, config.certname), config) config.cert_path = lineage.cert_path # --server takes priority over lineage.server if lineage.server and not config.set_by_user("server"): config.server = lineage.server elif not config.cert_path or (config.cert_path and config.certname): # 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!") if config.key_path is not None: # revocation by cert key logger.debug("Revoking %s using certificate key %s", config.cert_path, config.key_path) crypto_util.verify_cert_matches_priv_key(config.cert_path, config.key_path) with open(config.key_path, 'rb') as f: key = jose.JWK.load(f.read()) acme = client.acme_from_config_key(config, key) else: # revocation by account key logger.debug("Revoking %s using Account Key", config.cert_path) acc, _ = _determine_account(config) acme = client.acme_from_config_key(config, acc.key, acc.regr) with open(config.cert_path, 'rb') as f: cert = crypto_util.pyopenssl_load_certificate(f.read())[0] logger.debug("Reason code for revocation: %s", config.reason) try: acme.revoke(jose.ComparableX509(cert), config.reason) _delete_if_appropriate(config) except acme_errors.ClientError as e: return str(e) display_ops.success_revocation(config.cert_path) return None
Obtain a certificate and install. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None
def run(config: configuration.NamespaceConfig, plugins: plugins_disco.PluginsRegistry) -> Optional[str]: """Obtain a certificate and install. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None """ # TODO: Make run as close to auth + install as possible # Possible difficulties: config.csr was hacked into auth try: installer, authenticator = plug_sel.choose_configurator_plugins(config, plugins, "run") except errors.PluginSelectionError as e: return str(e) if config.must_staple and installer and "staple-ocsp" not in installer.supported_enhancements(): raise errors.NotSupportedError( "Must-Staple extension requested, but OCSP stapling is not supported by the selected " f"installer ({config.installer})\n\n" "You can either:\n" " * remove the --must-staple option from the command line and obtain a certificate " "without the Must-Staple extension, or;\n" " * use the `certonly` subcommand and manually install the certificate into the " "intended service (e.g. webserver). You must also then manually enable OCSP stapling, " "as it is required for certificates with the Must-Staple extension to " "function properly.\n" " * choose a different installer plugin (such as --nginx or --apache), if possible." ) # Preflight check for enhancement support by the selected installer if not enhancements.are_supported(config, installer): raise errors.NotSupportedError("One ore more of the requested enhancements " "are not supported by the selected installer") # TODO: Handle errors from _init_le_client? le_client = _init_le_client(config, authenticator, installer) domains, certname = _find_domains_or_certname(config, installer) should_get_cert, lineage = _find_cert(config, domains, certname) new_lineage = lineage if should_get_cert: new_lineage = _get_and_save_cert(le_client, config, domains, certname, lineage) cert_path = new_lineage.cert_path if new_lineage else None fullchain_path = new_lineage.fullchain_path if new_lineage else None key_path = new_lineage.key_path if new_lineage else None if should_get_cert: _report_new_cert(config, cert_path, fullchain_path, key_path) # The installer error, if any, is being stored as a value here, in order to first print # relevant advice in a nice way, before re-raising the error for normal processing. installer_err: Optional[errors.Error] = None try: _install_cert(config, le_client, domains, new_lineage) if enhancements.are_requested(config) and new_lineage: enhancements.enable(new_lineage, domains, installer, config) if lineage is None or not should_get_cert: display_ops.success_installation(domains) else: display_ops.success_renewal(domains) except errors.Error as e: installer_err = e finally: _report_next_steps(config, installer_err, new_lineage, new_or_renewed_cert=should_get_cert) # If the installer did fail, re-raise the error to bail out if installer_err: raise installer_err _suggest_donation_if_appropriate(config) eff.handle_subscription(config, le_client.account) return None
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: configuration.NamespaceConfig :param client: Client object :type client: client.Client :returns: `cert_path`, `chain_path` and `fullchain_path` as absolute paths to the actual files, or None for each if it's a dry-run. :rtype: `tuple` of `str`
def _csr_get_and_save_cert(config: configuration.NamespaceConfig, le_client: client.Client) -> Tuple[ Optional[str], Optional[str], Optional[str]]: """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: configuration.NamespaceConfig :param client: Client object :type client: client.Client :returns: `cert_path`, `chain_path` and `fullchain_path` as absolute paths to the actual files, or None for each if it's a dry-run. :rtype: `tuple` of `str` """ csr, _ = config.actual_csr csr_names = crypto_util.get_names_from_req(csr.data) display_util.notify( "{action} for {domains}".format( action="Simulating a certificate request" if config.dry_run else "Requesting a certificate", domains=internal_display_util.summarize_domain_list(csr_names) ) ) cert, chain = le_client.obtain_certificate_from_csr(csr) if config.dry_run: logger.debug( "Dry run: skipping saving certificate to %s", config.cert_path) return None, None, None cert_path, chain_path, fullchain_path = le_client.save_certificate( cert, chain, os.path.normpath(config.cert_path), os.path.normpath(config.chain_path), os.path.normpath(config.fullchain_path)) return cert_path, chain_path, fullchain_path
Renew & save an existing cert. Do not install it. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :returns: `None` :rtype: None :raises errors.PluginSelectionError: MissingCommandlineFlag if supplied parameters do not pass
def renew_cert(config: configuration.NamespaceConfig, plugins: plugins_disco.PluginsRegistry, lineage: storage.RenewableCert) -> None: """Renew & save an existing cert. Do not install it. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :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 installer, auth = plug_sel.choose_configurator_plugins(config, plugins, "certonly") le_client = _init_le_client(config, auth, installer) renewed_lineage = _get_and_save_cert(le_client, config, lineage=lineage) if not renewed_lineage: raise errors.Error("An existing certificate for the given name could not be found.") if installer and not config.dry_run: # In case of a renewal, reload server to pick up new certificate. updater.run_renewal_deployer(config, renewed_lineage, installer) display_util.notify(f"Reloading {config.installer} server after certificate renewal") installer.restart()
Authenticate & obtain cert, but do not install it. This implements the 'certonly' subcommand. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None :raises errors.Error: If specified plugin could not be used
def certonly(config: configuration.NamespaceConfig, plugins: plugins_disco.PluginsRegistry) -> None: """Authenticate & obtain cert, but do not install it. This implements the 'certonly' subcommand. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :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 installer, auth = plug_sel.choose_configurator_plugins(config, plugins, "certonly") le_client = _init_le_client(config, auth, installer) if config.csr: cert_path, chain_path, fullchain_path = _csr_get_and_save_cert(config, le_client) _csr_report_new_cert(config, cert_path, chain_path, fullchain_path) _report_next_steps(config, None, None, new_or_renewed_cert=not config.dry_run) _suggest_donation_if_appropriate(config) eff.handle_subscription(config, le_client.account) return domains, certname = _find_domains_or_certname(config, installer) should_get_cert, lineage = _find_cert(config, domains, certname) if not should_get_cert: display_util.notification("Certificate not yet due for renewal; no action taken.", pause=False) return lineage = _get_and_save_cert(le_client, config, domains, certname, lineage) # If a new cert was issued and we were passed an installer, we can safely # run `installer.restart()` to load the newly issued certificate installer_err: Optional[errors.Error] = None if lineage and installer and not config.dry_run: logger.info("Reloading %s server after certificate issuance", config.installer) try: installer.restart() except errors.Error as e: installer_err = e cert_path = lineage.cert_path if lineage else None fullchain_path = lineage.fullchain_path if lineage else None key_path = lineage.key_path if lineage else None _report_new_cert(config, cert_path, fullchain_path, key_path) _report_next_steps(config, installer_err, lineage, new_or_renewed_cert=should_get_cert and not config.dry_run) if installer_err: raise installer_err _suggest_donation_if_appropriate(config) eff.handle_subscription(config, le_client.account)
Renew previously-obtained certificates. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None
def renew(config: configuration.NamespaceConfig, unused_plugins: plugins_disco.PluginsRegistry) -> None: """Renew previously-obtained certificates. :param config: Configuration object :type config: configuration.NamespaceConfig :param unused_plugins: List of plugins (deprecated) :type unused_plugins: plugins_disco.PluginsRegistry :returns: `None` :rtype: None """ renewed_domains: List[str] = [] failed_domains: List[str] = [] try: renewed_domains, failed_domains = renewal.handle_renewal_request(config) finally: hooks.run_saved_post_hooks(renewed_domains, failed_domains)
Create or verify existence of config, work, and hook directories. :param config: Configuration object :type config: configuration.NamespaceConfig :returns: `None` :rtype: None
def make_or_verify_needed_dirs(config: configuration.NamespaceConfig) -> None: """Create or verify existence of config, work, and hook directories. :param config: Configuration object :type config: configuration.NamespaceConfig :returns: `None` :rtype: None """ util.set_up_core_dir(config.config_dir, constants.CONFIG_DIRS_MODE, config.strict_permissions) # Ensure the working directory has the expected mode, even under stricter umask settings with filesystem.temp_umask(0o022): util.set_up_core_dir(config.work_dir, constants.CONFIG_DIRS_MODE, config.strict_permissions) hook_dirs = (config.renewal_pre_hooks_dir, config.renewal_deploy_hooks_dir, config.renewal_post_hooks_dir,) for hook_dir in hook_dirs: util.make_or_verify_dir(hook_dir, strict=config.strict_permissions)
Reports the outcome of certificate renewal reconfiguration to the user. :param renewal_file: Path to the cert's renewal file :type renewal_file: str :param orig_renewal_conf: Loaded original renewal configuration :type orig_renewal_conf: configobj.ConfigObj :returns: `None` :rtype: None
def _report_reconfigure_results(renewal_file: str, orig_renewal_conf: configobj.ConfigObj) -> None: """Reports the outcome of certificate renewal reconfiguration to the user. :param renewal_file: Path to the cert's renewal file :type renewal_file: str :param orig_renewal_conf: Loaded original renewal configuration :type orig_renewal_conf: configobj.ConfigObj :returns: `None` :rtype: None """ try: final_renewal_conf = configobj.ConfigObj( renewal_file, encoding='utf-8', default_encoding='utf-8') except configobj.ConfigObjError: raise errors.CertStorageError( f'error parsing {renewal_file}') orig_renewal_params = orig_renewal_conf['renewalparams'] final_renewal_params = final_renewal_conf['renewalparams'] if final_renewal_params == orig_renewal_params: success_message = '\nNo changes were made to the renewal configuration.' else: success_message = '\nSuccessfully updated configuration.' + \ '\nChanges will apply when the certificate renews.' display_util.notify(success_message)
Allow the user to set new configuration options for an existing certificate without forcing renewal. This can be used for things like authenticator, installer, and hooks, but not for the domains on the cert, since those are only saved in the cert. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :raises errors.Error: if the dry run fails :raises errors.ConfigurationError: if certificate could not be loaded
def reconfigure(config: configuration.NamespaceConfig, plugins: plugins_disco.PluginsRegistry) -> None: """Allow the user to set new configuration options for an existing certificate without forcing renewal. This can be used for things like authenticator, installer, and hooks, but not for the domains on the cert, since those are only saved in the cert. :param config: Configuration object :type config: configuration.NamespaceConfig :param plugins: List of plugins :type plugins: plugins_disco.PluginsRegistry :raises errors.Error: if the dry run fails :raises errors.ConfigurationError: if certificate could not be loaded """ if config.domains: raise errors.ConfigurationError("You have specified domains, but this function cannot " "be used to modify the domains in a certificate. If you would like to do so, follow " "the instructions at https://certbot.org/change-cert-domain. Otherwise, remove the " "domains from the command to continue reconfiguring. You can specify which certificate " "you want on the command line with flag --cert-name instead.") # While we could technically allow domains to be used to specify the certificate in addition to # --cert-name, there's enough complexity with matching certs to domains that it's not worth it, # to say nothing of the difficulty in explaining what exactly this subcommand can modify # To make sure that the requested changes work, we're going to do a dry run, and only save # upon success. First, modify the config as the user requested. if not config.certname: certname_question = "Which certificate would you like to reconfigure?" config.certname = cert_manager.get_certnames( config, "reconfigure", allow_multiple=False, custom_prompt=certname_question)[0] certname = config.certname try: renewal_file = storage.renewal_file_for_certname(config, certname) except errors.CertStorageError: raise errors.ConfigurationError(f"An existing certificate with name {certname} could not " "be found. Run `certbot certificates` to list available certificates.") # figure this out before we modify config if config.deploy_hook and not config.run_deploy_hooks: msg = ("You are attempting to set a --deploy-hook. Would you like Certbot to run deploy " "hooks when it performs a dry run with the new settings? This will run all " "relevant deploy hooks, including directory hooks, unless --no-directory-hooks " "is set. This will use the current active certificate, and not the temporary test " "certificate acquired during the dry run.") config.run_deploy_hooks = display_util.yesno(msg,"Run deploy hooks", "Do not run deploy hooks", default=False) # cache previous version for later comparison try: orig_renewal_conf = configobj.ConfigObj( renewal_file, encoding='utf-8', default_encoding='utf-8') except configobj.ConfigObjError: raise errors.CertStorageError( f"error parsing {renewal_file}") lineage_config = copy.deepcopy(config) try: renewal_candidate = renewal.reconstitute(lineage_config, renewal_file) except Exception as e: # pylint: disable=broad-except raise errors.ConfigurationError(f"Renewal configuration file {renewal_file} " f"(cert: {certname}) produced an unexpected error: {e}.") if not renewal_candidate: raise errors.ConfigurationError("Could not load certificate. See logs for errors.") renewalparams = orig_renewal_conf['renewalparams'] # If server was set but hasn't changed and no account is loaded, # load the old account because reconstitute won't have if lineage_config.set_by_user('server') and lineage_config.server == renewalparams['server']\ and lineage_config.account is None: lineage_config.account = renewalparams['account'] for param in ('account', 'server',): if getattr(lineage_config, param) != renewalparams.get(param): msg = ("Using reconfigure to change the ACME account or server is not supported. " "If you would like to do so, use renew with the --force-renewal flag instead " "of reconfigure. Note that doing so will count against any rate limits. For " "more information on this method, see " "https://certbot.org/renew-reconfiguration") raise errors.ConfigurationError(msg) # this is where lineage_config gets fully filled out (e.g. --apache will set auth and installer) installer, auth = plug_sel.choose_configurator_plugins(lineage_config, plugins, "certonly") # make a deep copy of lineage_config because we're about to modify it for a test dry run dry_run_lineage_config = copy.deepcopy(lineage_config) # we also set noninteractive_mode to more accurately simulate renewal (since `certbot renew` # implies noninteractive mode) and to avoid prompting the user as changes made to # dry_run_lineage_config beyond this point will not be applied to the original lineage_config dry_run_lineage_config.noninteractive_mode = True dry_run_lineage_config.dry_run = True cli.set_test_server_options("reconfigure", dry_run_lineage_config) le_client = _init_le_client(dry_run_lineage_config, auth, installer) # renews cert as dry run to test that the new values are ok # at this point, renewal_candidate.configuration has the old values, but will use # the values from lineage_config when doing the dry run _get_and_save_cert(le_client, dry_run_lineage_config, certname=certname, lineage=renewal_candidate) # this function will update lineage.configuration with the new values, and save it to disk # use the pre-dry-run version renewal_candidate.save_new_config_values(lineage_config) _report_reconfigure_results(renewal_file, orig_renewal_conf)
Creates a display object appropriate to the flags in the supplied config. :param config: Configuration object :returns: Display object
def make_displayer(config: configuration.NamespaceConfig ) -> Generator[Union[display_obj.NoninteractiveDisplay, display_obj.FileDisplay], None, None]: """Creates a display object appropriate to the flags in the supplied config. :param config: Configuration object :returns: Display object """ displayer: Union[None, display_obj.NoninteractiveDisplay, display_obj.FileDisplay] = None devnull: Optional[IO] = None if config.quiet: config.noninteractive_mode = True devnull = open(os.devnull, "w") # pylint: disable=consider-using-with displayer = display_obj.NoninteractiveDisplay(devnull) elif config.noninteractive_mode: displayer = display_obj.NoninteractiveDisplay(sys.stdout) else: displayer = display_obj.FileDisplay( sys.stdout, config.force_interactive) try: yield displayer finally: if devnull: devnull.close()
Run Certbot. :param cli_args: command line to Certbot, defaults to ``sys.argv[1:]`` :type cli_args: `list` of `str` :returns: value for `sys.exit` about the exit status of Certbot :rtype: `str` or `int` or `None`
def main(cli_args: Optional[List[str]] = None) -> Optional[Union[str, int]]: """Run Certbot. :param cli_args: command line to Certbot, defaults to ``sys.argv[1:]`` :type cli_args: `list` of `str` :returns: value for `sys.exit` about the exit status of Certbot :rtype: `str` or `int` or `None` """ if not cli_args: cli_args = sys.argv[1:] log.pre_arg_parse_setup() if os.environ.get('CERTBOT_SNAPPED') == 'True': cli_args = snap_config.prepare_env(cli_args) plugins = plugins_disco.PluginsRegistry.find_all() logger.debug("certbot version: %s", certbot.__version__) logger.debug("Location of certbot entry point: %s", sys.argv[0]) # do not log `config`, as it contains sensitive data (e.g. revoke --key)! logger.debug("Arguments: %r", cli_args) logger.debug("Discovered plugins: %r", plugins) # Some releases of Windows require escape sequences to be enable explicitly misc.prepare_virtual_console() # note: arg parser internally handles --help (and exits afterwards) config = cli.prepare_and_parse_args(plugins, cli_args) # On windows, shell without administrative right cannot create symlinks required by certbot. # So we check the rights before continuing. misc.raise_for_non_administrative_windows_rights() try: log.post_arg_parse_setup(config) make_or_verify_needed_dirs(config) except errors.Error: # Let plugins_cmd be run as un-privileged user. if config.func != plugins_cmd: # pylint: disable=comparison-with-callable raise with make_displayer(config) as displayer: display_obj.set_display(displayer) return config.func(config, plugins)
Try to instantiate a RenewableCert, updating config with relevant items. This is specifically for use in renewal and enforces several checks and policies to ensure that we can try to proceed with the renewal request. The config argument is modified by including relevant options read from the renewal configuration file. :param configuration.NamespaceConfig config: configuration for the current lineage :param str full_path: Absolute path to the configuration file that defines this lineage :returns: the RenewableCert object or None if a fatal error occurred :rtype: `storage.RenewableCert` or NoneType
def reconstitute(config: configuration.NamespaceConfig, full_path: str) -> Optional[storage.RenewableCert]: """Try to instantiate a RenewableCert, updating config with relevant items. This is specifically for use in renewal and enforces several checks and policies to ensure that we can try to proceed with the renewal request. The config argument is modified by including relevant options read from the renewal configuration file. :param configuration.NamespaceConfig config: configuration for the current lineage :param str full_path: Absolute path to the configuration file that defines this lineage :returns: the RenewableCert object or None if a fatal error occurred :rtype: `storage.RenewableCert` or NoneType """ try: renewal_candidate = storage.RenewableCert(full_path, config) except (errors.CertStorageError, IOError) as error: logger.error("Renewal configuration file %s is broken.", full_path) logger.error("The error was: %s\nSkipping.", str(error)) logger.debug("Traceback was:\n%s", traceback.format_exc()) return None if "renewalparams" not in renewal_candidate.configuration: logger.error("Renewal configuration file %s lacks " "renewalparams. Skipping.", full_path) return None renewalparams = renewal_candidate.configuration["renewalparams"] if "authenticator" not in renewalparams: logger.error("Renewal configuration file %s does not specify " "an authenticator. Skipping.", full_path) return None # Prior to Certbot v1.25.0, the default value of key_type (rsa) was not persisted to the # renewal params. If the option is absent, it means the certificate was an RSA key. # Restoring the option here is necessary to preserve the certificate key_type if # the user has upgraded directly from Certbot <v1.25.0 to >=v2.0.0, where the default # key_type was changed to ECDSA. See https://github.com/certbot/certbot/issues/9635. renewalparams["key_type"] = renewalparams.get("key_type", "rsa") # Now restore specific values along with their data types, if # those elements are present. renewalparams = _remove_deprecated_config_elements(renewalparams) try: restore_required_config_elements(config, renewalparams) _restore_plugin_configs(config, renewalparams) except (ValueError, errors.Error) as error: logger.error( "An error occurred while parsing %s. The error was %s. " "Skipping the file.", full_path, str(error)) logger.debug("Traceback was:\n%s", traceback.format_exc()) return None try: config.domains = [util.enforce_domain_sanity(d) for d in renewal_candidate.names()] except errors.ConfigurationError as error: logger.error("Renewal configuration file %s references a certificate " "that contains an invalid domain name. The problem " "was: %s. Skipping.", full_path, error) return None return renewal_candidate
webroot_map is, uniquely, a dict, and the general-purpose configuration restoring logic is not able to correctly parse it from the serialized form.
def _restore_webroot_config(config: configuration.NamespaceConfig, renewalparams: Mapping[str, Any]) -> None: """ webroot_map is, uniquely, a dict, and the general-purpose configuration restoring logic is not able to correctly parse it from the serialized form. """ if "webroot_map" in renewalparams and not config.set_by_user("webroot_map"): config.webroot_map = renewalparams["webroot_map"] # To understand why webroot_path and webroot_map processing are not mutually exclusive, # see https://github.com/certbot/certbot/pull/7095 if "webroot_path" in renewalparams and not config.set_by_user("webroot_path"): wp = renewalparams["webroot_path"] if isinstance(wp, str): # prior to 0.1.0, webroot_path was a string wp = [wp] config.webroot_path = wp
Sets plugin specific values in config from renewalparams :param configuration.NamespaceConfig config: configuration for the current lineage :param configobj.Section renewalparams: Parameters from the renewal configuration file that defines this lineage
def _restore_plugin_configs(config: configuration.NamespaceConfig, renewalparams: Mapping[str, Any]) -> None: """Sets plugin specific values in config from renewalparams :param configuration.NamespaceConfig config: configuration for the current lineage :param configobj.Section renewalparams: Parameters from the renewal configuration file that defines this lineage """ # Now use parser to get plugin-prefixed items with correct types # XXX: the current approach of extracting only prefixed items # related to the actually-used installer and authenticator # works as long as plugins don't need to read plugin-specific # variables set by someone else (e.g., assuming Apache # configurator doesn't need to read webroot_ variables). # Note: if a parameter that used to be defined in the parser is no # longer defined, stored copies of that parameter will be # deserialized as strings by this logic even if they were # originally meant to be some other type. plugin_prefixes: List[str] = [] if renewalparams["authenticator"] == "webroot": _restore_webroot_config(config, renewalparams) else: plugin_prefixes.append(renewalparams["authenticator"]) if renewalparams.get("installer") is not None: plugin_prefixes.append(renewalparams["installer"]) for plugin_prefix in set(plugin_prefixes): plugin_prefix = plugin_prefix.replace('-', '_') for config_item, config_value in renewalparams.items(): if config_item.startswith(plugin_prefix + "_") and not config.set_by_user(config_item): # Values None, True, and False need to be treated specially, # As their types aren't handled correctly by configobj if config_value in ("None", "True", "False"): # bool("False") == True # pylint: disable=eval-used setattr(config, config_item, eval(config_value)) else: cast = cli.argparse_type(config_item) setattr(config, config_item, cast(config_value))
Sets non-plugin specific values in config from renewalparams :param configuration.NamespaceConfig config: configuration for the current lineage :param configobj.Section renewalparams: parameters from the renewal configuration file that defines this lineage
def restore_required_config_elements(config: configuration.NamespaceConfig, renewalparams: Mapping[str, Any]) -> None: """Sets non-plugin specific values in config from renewalparams :param configuration.NamespaceConfig config: configuration for the current lineage :param configobj.Section renewalparams: parameters from the renewal configuration file that defines this lineage """ updated_values = {} required_items = itertools.chain( (("pref_challs", _restore_pref_challs),), zip(BOOL_CONFIG_ITEMS, itertools.repeat(_restore_bool)), zip(INT_CONFIG_ITEMS, itertools.repeat(_restore_int)), zip(STR_CONFIG_ITEMS, itertools.repeat(_restore_str))) for item_name, restore_func in required_items: if item_name in renewalparams and not config.set_by_user(item_name): value = restore_func(item_name, renewalparams[item_name]) updated_values[item_name] = value for key, value in updated_values.items(): setattr(config, key, value)
Removes deprecated config options from the parsed renewalparams. :param dict renewalparams: list of parsed renewalparams :returns: list of renewalparams with deprecated config options removed :rtype: dict
def _remove_deprecated_config_elements(renewalparams: Mapping[str, Any]) -> Dict[str, Any]: """Removes deprecated config options from the parsed renewalparams. :param dict renewalparams: list of parsed renewalparams :returns: list of renewalparams with deprecated config options removed :rtype: dict """ return {option_name: v for (option_name, v) in renewalparams.items() if option_name not in cli.DEPRECATED_OPTIONS}
Restores preferred challenges from a renewal config file. If value is a `str`, it should be a single challenge type. :param str unused_name: option name :param value: option value :type value: `list` of `str` or `str` :returns: converted option value to be stored in the runtime config :rtype: `list` of `str` :raises errors.Error: if value can't be converted to a bool
def _restore_pref_challs(unused_name: str, value: Union[List[str], str]) -> List[str]: """Restores preferred challenges from a renewal config file. If value is a `str`, it should be a single challenge type. :param str unused_name: option name :param value: option value :type value: `list` of `str` or `str` :returns: converted option value to be stored in the runtime config :rtype: `list` of `str` :raises errors.Error: if value can't be converted to a bool """ # If pref_challs has only one element, configobj saves the value # with a trailing comma so it's parsed as a list. If this comma is # removed by the user, the value is parsed as a str. value = [value] if isinstance(value, str) else value return cli.parse_preferred_challenges(value)
Restores a boolean key-value pair from a renewal config file. :param str name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: bool :raises errors.Error: if value can't be converted to a bool
def _restore_bool(name: str, value: str) -> bool: """Restores a boolean key-value pair from a renewal config file. :param str name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: bool :raises errors.Error: if value can't be converted to a bool """ lowercase_value = value.lower() if lowercase_value not in ("true", "false"): raise errors.Error(f"Expected True or False for {name} but found {value}") return lowercase_value == "true"
Restores an integer key-value pair from a renewal config file. :param str name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: int :raises errors.Error: if value can't be converted to an int
def _restore_int(name: str, value: str) -> int: """Restores an integer key-value pair from a renewal config file. :param str name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: int :raises errors.Error: if value can't be converted to an int """ if name == "http01_port" and value == "None": logger.info("updating legacy http01_port value") return cli.flag_default("http01_port") try: return int(value) except ValueError: raise errors.Error(f"Expected a numeric value for {name}")
Restores a string key-value pair from a renewal config file. :param str name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: str or None
def _restore_str(name: str, value: str) -> Optional[str]: """Restores a string key-value pair from a renewal config file. :param str name: option name :param str value: option value :returns: converted option value to be stored in the runtime config :rtype: str or None """ # Previous to v0.5.0, Certbot always stored the `server` URL in the renewal config, # resulting in configs which explicitly use the deprecated ACMEv1 URL, today # preventing an automatic transition to the default modern ACME URL. # (https://github.com/certbot/certbot/issues/7978#issuecomment-625442870) # As a mitigation, this function reinterprets the value of the `server` parameter if # necessary, replacing the ACMEv1 URL with the default ACME URL. It is still possible # to override this choice with the explicit `--server` CLI flag. if name == "server" and value == constants.V1_URI: logger.info("Using server %s instead of legacy %s", constants.CLI_DEFAULTS["server"], value) return constants.CLI_DEFAULTS["server"] return None if value == "None" else value
Return true if any of the circumstances for automatic renewal apply.
def should_renew(config: configuration.NamespaceConfig, lineage: storage.RenewableCert) -> bool: """Return true if any of the circumstances for automatic renewal apply.""" if config.renew_by_default: logger.debug("Auto-renewal forced with --force-renewal...") return True if lineage.should_autorenew(): logger.info("Certificate is due for renewal, auto-renewing...") return True if config.dry_run: logger.info("Certificate not due for renewal, but simulating renewal for dry run") return True display_util.notify("Certificate not yet due for renewal") return False
Do not renew a valid cert with one from a staging server!
def _avoid_invalidating_lineage(config: configuration.NamespaceConfig, lineage: storage.RenewableCert, original_server: str) -> None: """Do not renew a valid cert with one from a staging server!""" if util.is_staging(config.server): if not util.is_staging(original_server): if not config.break_my_certs: names = ", ".join(lineage.names()) raise errors.Error( "You've asked to renew/replace a seemingly valid certificate with " f"a test certificate (domains: {names}). We will not do that " "unless you use the --break-my-certs flag!")
Don't allow combining --reuse-key with any flags that would conflict with key reuse (--key-type, --rsa-key-size, --elliptic-curve), unless --new-key is also set.
def _avoid_reuse_key_conflicts(config: configuration.NamespaceConfig, lineage: storage.RenewableCert) -> None: """Don't allow combining --reuse-key with any flags that would conflict with key reuse (--key-type, --rsa-key-size, --elliptic-curve), unless --new-key is also set. """ # If --no-reuse-key is set, no conflict if config.set_by_user("reuse_key") and not config.reuse_key: return # If reuse_key is not set on the lineage and --reuse-key is not # set on the CLI, no conflict. if not lineage.reuse_key and not config.reuse_key: return # If --new-key is set, no conflict if config.new_key: return kt = config.key_type.lower() # The remaining cases where conflicts are present: # - --key-type is set on the CLI and doesn't match the stored private key # - It's an RSA key and --rsa-key-size is set and doesn't match # - It's an ECDSA key and --eliptic-curve is set and doesn't match potential_conflicts = [ ("--key-type", lambda: kt != lineage.private_key_type.lower()), ("--rsa-key-size", lambda: kt == "rsa" and config.rsa_key_size != lineage.rsa_key_size), ("--elliptic-curve", lambda: kt == "ecdsa" and lineage.elliptic_curve and \ config.elliptic_curve.lower() != lineage.elliptic_curve.lower()) ] for conflict in potential_conflicts: if conflict[1](): raise errors.Error( f"Unable to change the {conflict[0]} of this certificate because --reuse-key " "is set. To stop reusing the private key, specify --no-reuse-key. " "To change the private key this one time and then reuse it in future, " "add --new-key.")
Renew a certificate lineage.
def renew_cert(config: configuration.NamespaceConfig, domains: Optional[List[str]], le_client: client.Client, lineage: storage.RenewableCert) -> None: """Renew a certificate lineage.""" renewal_params = lineage.configuration["renewalparams"] original_server = renewal_params.get("server", cli.flag_default("server")) _avoid_invalidating_lineage(config, lineage, original_server) _avoid_reuse_key_conflicts(config, lineage) if not domains: domains = lineage.names() # The private key is the existing lineage private key if reuse_key is set. # Otherwise, generate a fresh private key by passing None. if config.reuse_key and not config.new_key: new_key = os.path.normpath(lineage.privkey) _update_renewal_params_from_key(new_key, config) else: new_key = None new_cert, new_chain, new_key, _ = le_client.obtain_certificate(domains, new_key) if config.dry_run: logger.debug("Dry run: skipping updating lineage at %s", os.path.dirname(lineage.cert)) else: prior_version = lineage.latest_common_version() # TODO: Check return value of save_successor lineage.save_successor(prior_version, new_cert, new_key.pem, new_chain, config) lineage.update_all_links_to(lineage.latest_common_version()) lineage.truncate() hooks.renew_hook(config, domains, lineage.live_dir)
Format a results report for a category of renewal outcomes
def report(msgs: Iterable[str], category: str) -> str: """Format a results report for a category of renewal outcomes""" lines = ("%s (%s)" % (m, category) for m in msgs) return " " + "\n ".join(lines)
Print a report to the terminal about the results of the renewal process. :param configuration.NamespaceConfiguration config: Configuration :param list renew_successes: list of fullchain paths which were renewed :param list renew_failures: list of fullchain paths which failed to be renewed :param list renew_skipped: list of messages to print about skipped certificates :param list parse_failures: list of renewal parameter paths which had errors
def _renew_describe_results(config: configuration.NamespaceConfig, renew_successes: List[str], renew_failures: List[str], renew_skipped: List[str], parse_failures: List[str]) -> None: """ Print a report to the terminal about the results of the renewal process. :param configuration.NamespaceConfiguration config: Configuration :param list renew_successes: list of fullchain paths which were renewed :param list renew_failures: list of fullchain paths which failed to be renewed :param list renew_skipped: list of messages to print about skipped certificates :param list parse_failures: list of renewal parameter paths which had errors """ notify = display_util.notify notify_error = logger.error notify(f'\n{display_obj.SIDE_FRAME}') renewal_noun = "simulated renewal" if config.dry_run else "renewal" if renew_skipped: notify("The following certificates are not due for renewal yet:") notify(report(renew_skipped, "skipped")) if not renew_successes and not renew_failures: notify(f"No {renewal_noun}s were attempted.") if (config.pre_hook is not None or config.renew_hook is not None or config.post_hook is not None): notify("No hooks were run.") elif renew_successes and not renew_failures: notify(f"Congratulations, all {renewal_noun}s succeeded: ") notify(report(renew_successes, "success")) elif renew_failures and not renew_successes: notify_error("All %ss failed. The following certificates could " "not be renewed:", renewal_noun) notify_error(report(renew_failures, "failure")) elif renew_failures and renew_successes: notify(f"The following {renewal_noun}s succeeded:") notify(report(renew_successes, "success") + "\n") notify_error("The following %ss failed:", renewal_noun) notify_error(report(renew_failures, "failure")) if parse_failures: notify("\nAdditionally, the following renewal configurations " "were invalid: ") notify(report(parse_failures, "parsefail")) notify(display_obj.SIDE_FRAME)
Examine each lineage; renew if due and report results
def handle_renewal_request(config: configuration.NamespaceConfig) -> Tuple[list, list]: """Examine each lineage; renew if due and report results""" # This is trivially False if config.domains is empty if any(domain not in config.webroot_map for domain in config.domains): # If more plugins start using cli.add_domains, # we may want to only log a warning here raise errors.Error("Currently, the renew verb is capable of either " "renewing all installed certificates that are due " "to be renewed or renewing a single certificate specified " "by its name. If you would like to renew specific " "certificates by their domains, use the certonly command " "instead. The renew verb may provide other options " "for selecting certificates to renew in the future.") if config.certname: conf_files = [storage.renewal_file_for_certname(config, config.certname)] else: conf_files = storage.renewal_conf_files(config) renew_successes = [] renew_failures = [] renew_skipped = [] parse_failures = [] renewed_domains = [] failed_domains = [] # Noninteractive renewals include a random delay in order to spread # out the load on the certificate authority servers, even if many # users all pick the same time for renewals. This delay precedes # running any hooks, so that side effects of the hooks (such as # shutting down a web service) aren't prolonged unnecessarily. apply_random_sleep = not sys.stdin.isatty() and config.random_sleep_on_renew for renewal_file in conf_files: display_util.notification("Processing " + renewal_file, pause=False) lineage_config = copy.deepcopy(config) lineagename = storage.lineagename_for_filename(renewal_file) # Note that this modifies config (to add back the configuration # elements from within the renewal configuration file). try: renewal_candidate = reconstitute(lineage_config, renewal_file) except Exception as e: # pylint: disable=broad-except logger.error("Renewal configuration file %s (cert: %s) " "produced an unexpected error: %s. Skipping.", renewal_file, lineagename, e) logger.debug("Traceback was:\n%s", traceback.format_exc()) parse_failures.append(renewal_file) continue try: if not renewal_candidate: parse_failures.append(renewal_file) else: renewal_candidate.ensure_deployed() from certbot._internal import main plugins = plugins_disco.PluginsRegistry.find_all() if should_renew(lineage_config, renewal_candidate): # Apply random sleep upon first renewal if needed if apply_random_sleep: sleep_time = random.uniform(1, 60 * 8) logger.info("Non-interactive renewal: random delay of %s seconds", sleep_time) time.sleep(sleep_time) # We will sleep only once this day, folks. apply_random_sleep = False # domains have been restored into lineage_config by reconstitute # but they're unnecessary anyway because renew_cert here # will just grab them from the certificate # we already know it's time to renew based on should_renew # and we have a lineage in renewal_candidate main.renew_cert(lineage_config, plugins, renewal_candidate) renew_successes.append(renewal_candidate.fullchain) renewed_domains.extend(renewal_candidate.names()) else: expiry = crypto_util.notAfter(renewal_candidate.version( "cert", renewal_candidate.latest_common_version())) renew_skipped.append("%s expires on %s" % (renewal_candidate.fullchain, expiry.strftime("%Y-%m-%d"))) # Run updater interface methods updater.run_generic_updaters(lineage_config, renewal_candidate, plugins) except Exception as e: # pylint: disable=broad-except # obtain_cert (presumably) encountered an unanticipated problem. logger.error( "Failed to renew certificate %s with error: %s", lineagename, e ) logger.debug("Traceback was:\n%s", traceback.format_exc()) if renewal_candidate: renew_failures.append(renewal_candidate.fullchain) failed_domains.extend(renewal_candidate.names()) # Describe all the results _renew_describe_results(config, renew_successes, renew_failures, renew_skipped, parse_failures) if renew_failures or parse_failures: raise errors.Error( f"{len(renew_failures)} renew failure(s), {len(parse_failures)} parse failure(s)") # Windows installer integration tests rely on handle_renewal_request behavior here. # If the text below changes, these tests will need to be updated accordingly. logger.debug("no renewal failures") return (renewed_domains, failed_domains)
Prepare runtime environment for a certbot execution in snap. :param list cli_args: List of command line arguments :return: Update list of command line arguments :rtype: list
def prepare_env(cli_args: List[str]) -> List[str]: """ Prepare runtime environment for a certbot execution in snap. :param list cli_args: List of command line arguments :return: Update list of command line arguments :rtype: list """ snap_arch = os.environ.get('SNAP_ARCH') if snap_arch not in _ARCH_TRIPLET_MAP: raise Error('Unrecognized value of SNAP_ARCH: {0}'.format(snap_arch)) os.environ['CERTBOT_AUGEAS_PATH'] = '{0}/usr/lib/{1}/libaugeas.so.0'.format( os.environ.get('SNAP'), _ARCH_TRIPLET_MAP[snap_arch]) with Session() as session: session.mount('http://snapd/', _SnapdAdapter()) try: response = session.get('http://snapd/v2/connections?snap=certbot&interface=content', timeout=30.0) response.raise_for_status() except RequestException as e: if isinstance(e, HTTPError) and e.response.status_code == 404: LOGGER.error('An error occurred while fetching Certbot snap plugins: ' 'your version of snapd is outdated.') LOGGER.error('Please run "sudo snap install core; sudo snap refresh core" ' 'in your terminal and try again.') else: LOGGER.error('An error occurred while fetching Certbot snap plugins: ' 'make sure the snapd service is running.') raise e data = response.json() connections = ['/snap/{0}/current/lib/python3.8/site-packages/'.format(item['slot']['snap']) for item in data.get('result', {}).get('established', []) if item.get('plug', {}).get('plug') == 'plugin' and item.get('plug-attrs', {}).get('content') == 'certbot-1'] os.environ['CERTBOT_PLUGIN_PATH'] = ':'.join(connections) cli_args.append('--preconfigured-renewal') return cli_args
Build a list of all renewal configuration files. :param configuration.NamespaceConfig config: Configuration object :returns: list of renewal configuration files :rtype: `list` of `str`
def renewal_conf_files(config: configuration.NamespaceConfig) -> List[str]: """Build a list of all renewal configuration files. :param configuration.NamespaceConfig config: Configuration object :returns: list of renewal configuration files :rtype: `list` of `str` """ result = glob.glob(os.path.join(config.renewal_configs_dir, "*.conf")) result.sort() return result
Return /path/to/certname.conf in the renewal conf directory
def renewal_file_for_certname(config: configuration.NamespaceConfig, certname: str) -> str: """Return /path/to/certname.conf in the renewal conf directory""" path = os.path.join(config.renewal_configs_dir, f"{certname}.conf") if not os.path.exists(path): raise errors.CertStorageError( f"No certificate found with name {certname} (expected {path}).") return path
If `--cert-name` was specified, but you need a value for `--cert-path`. :param configuration.NamespaceConfig config: parsed command line arguments :param str cert_name: cert name.
def cert_path_for_cert_name(config: configuration.NamespaceConfig, cert_name: str) -> str: """ If `--cert-name` was specified, but you need a value for `--cert-path`. :param configuration.NamespaceConfig config: parsed command line arguments :param str cert_name: cert name. """ cert_name_implied_conf = renewal_file_for_certname(config, cert_name) return configobj.ConfigObj( cert_name_implied_conf, encoding='utf-8', default_encoding='utf-8')["fullchain"]
Merge supplied config, if provided, on top of builtin defaults.
def config_with_defaults(config: Optional[configuration.NamespaceConfig] = None ) -> configobj.ConfigObj: """Merge supplied config, if provided, on top of builtin defaults.""" defaults_copy = configobj.ConfigObj( constants.RENEWER_DEFAULTS, encoding='utf-8', default_encoding='utf-8') defaults_copy.merge(config if config is not None else configobj.ConfigObj( encoding='utf-8', default_encoding='utf-8')) return defaults_copy
Parse the time specified time interval, and add it to the base_time The interval can be in the English-language format understood by parsedatetime, e.g., '10 days', '3 weeks', '6 months', '9 hours', or a sequence of such intervals like '6 months 1 week' or '3 days 12 hours'. If an integer is found with no associated unit, it is interpreted by default as a number of days. :param datetime.datetime base_time: The time to be added with the interval. :param str interval: The time interval to parse. :returns: The base_time plus the interpretation of the time interval. :rtype: :class:`datetime.datetime`
def add_time_interval(base_time: datetime.datetime, interval: str, textparser: parsedatetime.Calendar = parsedatetime.Calendar() ) -> datetime.datetime: """Parse the time specified time interval, and add it to the base_time The interval can be in the English-language format understood by parsedatetime, e.g., '10 days', '3 weeks', '6 months', '9 hours', or a sequence of such intervals like '6 months 1 week' or '3 days 12 hours'. If an integer is found with no associated unit, it is interpreted by default as a number of days. :param datetime.datetime base_time: The time to be added with the interval. :param str interval: The time interval to parse. :returns: The base_time plus the interpretation of the time interval. :rtype: :class:`datetime.datetime`""" if interval.strip().isdigit(): interval += " days" # try to use the same timezone, but fallback to UTC tzinfo = base_time.tzinfo or pytz.UTC return textparser.parseDT(interval, base_time, tzinfo=tzinfo)[0]
Writes a renewal config file with the specified name and values. :param str o_filename: Absolute path to the previous version of config file :param str n_filename: Absolute path to the new destination of config file :param str archive_dir: Absolute path to the archive directory :param dict target: Maps ALL_FOUR to their symlink paths :param dict relevant_data: Renewal configuration options to save :returns: Configuration object for the new config file :rtype: configobj.ConfigObj
def write_renewal_config(o_filename: str, n_filename: str, archive_dir: str, target: Mapping[str, str], relevant_data: Mapping[str, Any]) -> configobj.ConfigObj: """Writes a renewal config file with the specified name and values. :param str o_filename: Absolute path to the previous version of config file :param str n_filename: Absolute path to the new destination of config file :param str archive_dir: Absolute path to the archive directory :param dict target: Maps ALL_FOUR to their symlink paths :param dict relevant_data: Renewal configuration options to save :returns: Configuration object for the new config file :rtype: configobj.ConfigObj """ config = configobj.ConfigObj(o_filename, encoding='utf-8', default_encoding='utf-8') config["version"] = certbot.__version__ config["archive_dir"] = archive_dir for kind in ALL_FOUR: config[kind] = target[kind] if "renewalparams" not in config: config["renewalparams"] = {} config.comments["renewalparams"] = ["", "Options used in " "the renewal process"] config["renewalparams"].update(relevant_data) for k in config["renewalparams"]: if k not in relevant_data: del config["renewalparams"][k] if "renew_before_expiry" not in config: default_interval = constants.RENEWER_DEFAULTS["renew_before_expiry"] config.initial_comment = ["renew_before_expiry = " + default_interval] # TODO: add human-readable comments explaining other available # parameters logger.debug("Writing new config %s.", n_filename) # Ensure that the file exists with open(n_filename, 'a'): pass # Copy permissions from the old version of the file, if it exists. if os.path.exists(o_filename): current_permissions = stat.S_IMODE(os.lstat(o_filename).st_mode) filesystem.chmod(n_filename, current_permissions) with open(n_filename, "wb") as f: config.write(outfile=f) return config
Renames cli_config.certname's config to cli_config.new_certname. :param .NamespaceConfig cli_config: parsed command line arguments
def rename_renewal_config(prev_name: str, new_name: str, cli_config: configuration.NamespaceConfig) -> None: """Renames cli_config.certname's config to cli_config.new_certname. :param .NamespaceConfig cli_config: parsed command line arguments """ prev_filename = renewal_filename_for_lineagename(cli_config, prev_name) new_filename = renewal_filename_for_lineagename(cli_config, new_name) if os.path.exists(new_filename): raise errors.ConfigurationError("The new certificate name " "is already in use.") try: filesystem.replace(prev_filename, new_filename) except OSError: raise errors.ConfigurationError("Please specify a valid filename " "for the new certificate name.")
Modifies lineagename's config to contain the specified values. :param str lineagename: Name of the lineage being modified :param str archive_dir: Absolute path to the archive directory :param dict target: Maps ALL_FOUR to their symlink paths :param .NamespaceConfig cli_config: parsed command line arguments :returns: Configuration object for the updated config file :rtype: configobj.ConfigObj
def update_configuration(lineagename: str, archive_dir: str, target: Mapping[str, str], cli_config: configuration.NamespaceConfig) -> configobj.ConfigObj: """Modifies lineagename's config to contain the specified values. :param str lineagename: Name of the lineage being modified :param str archive_dir: Absolute path to the archive directory :param dict target: Maps ALL_FOUR to their symlink paths :param .NamespaceConfig cli_config: parsed command line arguments :returns: Configuration object for the updated config file :rtype: configobj.ConfigObj """ config_filename = renewal_filename_for_lineagename(cli_config, lineagename) temp_filename = config_filename + ".new" # If an existing tempfile exists, delete it if os.path.exists(temp_filename): os.unlink(temp_filename) # Save only the config items that are relevant to renewal values = relevant_values(cli_config) write_renewal_config(config_filename, temp_filename, archive_dir, target, values) filesystem.replace(temp_filename, config_filename) return configobj.ConfigObj(config_filename, encoding='utf-8', default_encoding='utf-8')
Get an absolute path to the target of link. :param str link: Path to a symbolic link :returns: Absolute path to the target of link :rtype: str :raises .CertStorageError: If link does not exists.
def get_link_target(link: str) -> str: """Get an absolute path to the target of link. :param str link: Path to a symbolic link :returns: Absolute path to the target of link :rtype: str :raises .CertStorageError: If link does not exists. """ try: target = filesystem.readlink(link) except OSError: raise errors.CertStorageError( "Expected {0} to be a symlink".format(link)) if not os.path.isabs(target): target = os.path.join(os.path.dirname(link), target) return os.path.abspath(target)
Is this option one that could be restored for future renewal purposes? :param namespaces: plugin namespaces for configuration options :type namespaces: `list` of `str` :param str option: the name of the option :rtype: bool
def _relevant(namespaces: Iterable[str], option: str) -> bool: """ Is this option one that could be restored for future renewal purposes? :param namespaces: plugin namespaces for configuration options :type namespaces: `list` of `str` :param str option: the name of the option :rtype: bool """ from certbot._internal import renewal return (option in renewal.CONFIG_ITEMS or any(option.startswith(namespace) for namespace in namespaces))
Return a new dict containing only items relevant for renewal. :param .NamespaceConfig config: parsed command line :returns: A new dictionary containing items that can be used in renewal. :rtype dict:
def relevant_values(config: configuration.NamespaceConfig) -> Dict[str, Any]: """Return a new dict containing only items relevant for renewal. :param .NamespaceConfig config: parsed command line :returns: A new dictionary containing items that can be used in renewal. :rtype dict: """ all_values = config.to_dict() plugins = plugins_disco.PluginsRegistry.find_all() namespaces = [plugins_common.dest_namespace(plugin) for plugin in plugins] rv = { option: value for option, value in all_values.items() if _relevant(namespaces, option) and config.set_by_user(option) } # We always save the server value to help with forward compatibility # and behavioral consistency when versions of Certbot with different # server defaults are used. rv["server"] = all_values["server"] # Save key type to help with forward compatibility on Certbot's transition # from RSA to ECDSA certificates by default. rv["key_type"] = all_values["key_type"] return rv
Returns the lineagename for a configuration filename.
def lineagename_for_filename(config_filename: str) -> str: """Returns the lineagename for a configuration filename. """ if not config_filename.endswith(".conf"): raise errors.CertStorageError( "renewal config file name must end in .conf") return os.path.basename(config_filename[:-len(".conf")])
Returns the lineagename for a configuration filename.
def renewal_filename_for_lineagename(config: configuration.NamespaceConfig, lineagename: str) -> str: """Returns the lineagename for a configuration filename. """ return os.path.join(config.renewal_configs_dir, lineagename) + ".conf"
Path to a directory from a file
def _relpath_from_file(archive_dir: str, from_file: str) -> str: """Path to a directory from a file""" return os.path.relpath(archive_dir, os.path.dirname(from_file))
Returns the full archive path for a lineagename Uses cli_config to determine archive path if not available from config_obj. :param configobj.ConfigObj config_obj: Renewal conf file contents (can be None) :param configuration.NamespaceConfig cli_config: Main config file :param str lineagename: Certificate name
def full_archive_path(config_obj: configobj.ConfigObj, cli_config: configuration.NamespaceConfig, lineagename: str) -> str: """Returns the full archive path for a lineagename Uses cli_config to determine archive path if not available from config_obj. :param configobj.ConfigObj config_obj: Renewal conf file contents (can be None) :param configuration.NamespaceConfig cli_config: Main config file :param str lineagename: Certificate name """ if config_obj and "archive_dir" in config_obj: return config_obj["archive_dir"] return os.path.join(cli_config.default_archive_dir, lineagename)
Returns the full default live path for a lineagename
def _full_live_path(cli_config: configuration.NamespaceConfig, lineagename: str) -> str: """Returns the full default live path for a lineagename""" return os.path.join(cli_config.live_dir, lineagename)
Delete all files related to the certificate. If some files are not found, ignore them and continue.
def delete_files(config: configuration.NamespaceConfig, certname: str) -> None: """Delete all files related to the certificate. If some files are not found, ignore them and continue. """ renewal_filename = renewal_file_for_certname(config, certname) # file exists full_default_archive_dir = full_archive_path(None, config, certname) full_default_live_dir = _full_live_path(config, certname) try: renewal_config = configobj.ConfigObj( renewal_filename, encoding='utf-8', default_encoding='utf-8') except configobj.ConfigObjError: # config is corrupted logger.error("Could not parse %s. You may wish to manually " "delete the contents of %s and %s.", renewal_filename, full_default_live_dir, full_default_archive_dir) raise errors.CertStorageError( "error parsing {0}".format(renewal_filename)) finally: # we couldn't read it, but let's at least delete it # if this was going to fail, it already would have. os.remove(renewal_filename) logger.info("Removed %s", renewal_filename) # cert files and (hopefully) live directory # it's not guaranteed that the files are in our default storage # structure. so, first delete the cert files. directory_names = set() for kind in ALL_FOUR: link = renewal_config.get(kind) try: os.remove(link) logger.debug("Removed %s", link) except OSError: logger.debug("Unable to delete %s", link) directory = os.path.dirname(link) directory_names.add(directory) # if all four were in the same directory, and the only thing left # is the README file (or nothing), delete that directory. # this will be wrong in very few but some cases. if len(directory_names) == 1: # delete the README file directory = directory_names.pop() readme_path = os.path.join(directory, README) try: os.remove(readme_path) logger.debug("Removed %s", readme_path) except OSError: logger.debug("Unable to delete %s", readme_path) # if it's now empty, delete the directory try: os.rmdir(directory) # only removes empty directories logger.debug("Removed %s", directory) except OSError: logger.debug("Unable to remove %s; may not be empty.", directory) # archive directory try: archive_path = full_archive_path(renewal_config, config, certname) shutil.rmtree(archive_path) logger.debug("Removed %s", archive_path) except OSError: logger.debug("Unable to remove %s", archive_path)
Run updaters that the plugin supports :param config: Configuration object :type config: certbot.configuration.NamespaceConfig :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param plugins: List of plugins :type plugins: certbot._internal.plugins.disco.PluginsRegistry :returns: `None` :rtype: None
def run_generic_updaters(config: configuration.NamespaceConfig, lineage: storage.RenewableCert, plugins: plugin_disco.PluginsRegistry) -> None: """Run updaters that the plugin supports :param config: Configuration object :type config: certbot.configuration.NamespaceConfig :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param plugins: List of plugins :type plugins: certbot._internal.plugins.disco.PluginsRegistry :returns: `None` :rtype: None """ if config.dry_run: logger.debug("Skipping updaters in dry-run mode.") return try: installer = plug_sel.get_unprepared_installer(config, plugins) except errors.Error as e: logger.error("Could not choose appropriate plugin for updaters: %s", e) return if installer: _run_updaters(lineage, installer, config) _run_enhancement_updaters(lineage, installer, config)
Helper function to run deployer interface method if supported by the used installer plugin. :param config: Configuration object :type config: certbot.configuration.NamespaceConfig :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.Installer :returns: `None` :rtype: None
def run_renewal_deployer(config: configuration.NamespaceConfig, lineage: storage.RenewableCert, installer: interfaces.Installer) -> None: """Helper function to run deployer interface method if supported by the used installer plugin. :param config: Configuration object :type config: certbot.configuration.NamespaceConfig :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.Installer :returns: `None` :rtype: None """ if config.dry_run: logger.debug("Skipping renewal deployer in dry-run mode.") return if not config.disable_renew_updates and isinstance(installer, interfaces.RenewDeployer): installer.renew_deploy(lineage) _run_enhancement_deployers(lineage, installer, config)
Helper function to run the updater interface methods if supported by the used installer plugin. :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.Installer :returns: `None` :rtype: None
def _run_updaters(lineage: storage.RenewableCert, installer: interfaces.Installer, config: configuration.NamespaceConfig) -> None: """Helper function to run the updater interface methods if supported by the used installer plugin. :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.Installer :returns: `None` :rtype: None """ if not config.disable_renew_updates: if isinstance(installer, interfaces.GenericUpdater): installer.generic_updates(lineage)
Iterates through known enhancement interfaces. If the installer implements an enhancement interface and the enhance interface has an updater method, the updater method gets run. :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.Installer :param config: Configuration object :type config: certbot.configuration.NamespaceConfig
def _run_enhancement_updaters(lineage: storage.RenewableCert, installer: interfaces.Installer, config: configuration.NamespaceConfig) -> None: """Iterates through known enhancement interfaces. If the installer implements an enhancement interface and the enhance interface has an updater method, the updater method gets run. :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.Installer :param config: Configuration object :type config: certbot.configuration.NamespaceConfig """ if config.disable_renew_updates: return for enh in enhancements._INDEX: # pylint: disable=protected-access if isinstance(installer, enh["class"]) and enh["updater_function"]: getattr(installer, enh["updater_function"])(lineage)
Iterates through known enhancement interfaces. If the installer implements an enhancement interface and the enhance interface has an deployer method, the deployer method gets run. :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.Installer :param config: Configuration object :type config: certbot.configuration.NamespaceConfig
def _run_enhancement_deployers(lineage: storage.RenewableCert, installer: interfaces.Installer, config: configuration.NamespaceConfig) -> None: """Iterates through known enhancement interfaces. If the installer implements an enhancement interface and the enhance interface has an deployer method, the deployer method gets run. :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :param installer: Installer object :type installer: interfaces.Installer :param config: Configuration object :type config: certbot.configuration.NamespaceConfig """ if config.disable_renew_updates: return for enh in enhancements._INDEX: # pylint: disable=protected-access if isinstance(installer, enh["class"]) and enh["deployer_function"]: getattr(installer, enh["deployer_function"])(lineage)
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.
def read_file(filename: str, mode: str = "rb") -> Tuple[str, Any]: """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. """ try: filename = os.path.abspath(filename) with open(filename, mode) as the_file: contents = the_file.read() return filename, contents except IOError as exc: raise argparse.ArgumentTypeError(exc.strerror)
Default value for CLI flag.
def flag_default(name: str) -> Any: """Default value for CLI flag.""" # XXX: this is an internal housekeeping notion of defaults before # argparse has been set up; it is not accurate for all flags. Call it # with caution. Plugin defaults are missing, and some things are using # defaults defined in this file, not in constants.py :( return copy.deepcopy(constants.CLI_DEFAULTS[name])
Extract the help message for a `configuration.NamespaceConfig` property docstring.
def config_help(name: str, hidden: bool = False) -> Optional[str]: """Extract the help message for a `configuration.NamespaceConfig` property docstring.""" if hidden: return argparse.SUPPRESS return inspect.getdoc(getattr(configuration.NamespaceConfig, name))
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`
def add_domains(args_or_config: Union[argparse.Namespace, configuration.NamespaceConfig], domains: Optional[str]) -> List[str]: """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` """ validated_domains: List[str] = [] if not domains: return validated_domains for domain in domains.split(","): domain = util.enforce_domain_sanity(domain.strip()) validated_domains.append(domain) if domain not in args_or_config.domains: args_or_config.domains.append(domain) return validated_domains
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
def parse_preferred_challenges(pref_challs: Iterable[str]) -> List[str]: """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 """ aliases = {"dns": "dns-01", "http": "http-01"} challs = [c.strip() for c in pref_challs] challs = [aliases.get(c, c) for c in challs] unrecognized = ", ".join(name for name in challs if name not in challenges.Challenge.TYPES) if unrecognized: raise errors.Error( "Unrecognized challenges: {0}".format(unrecognized)) return challs
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
def nonnegative_int(value: str) -> int: """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 """ try: int_value = int(value) except ValueError: raise argparse.ArgumentTypeError("value must be an integer") if int_value < 0: raise argparse.ArgumentTypeError("value must be non-negative") return int_value
Updates server, break_my_certs, staging, tos, and register_unsafely_without_email in config as necessary to prepare to use the test server. We have --staging/--dry-run; perform sanity check and set config.server :param str verb: subcommand called :param config: parsed command line arguments :type config: configuration.NamespaceConfig :raises errors.Error: if non-default server is used and --staging is set :raises errors.Error: if inapplicable verb is used and --dry-run is set
def set_test_server_options(verb: str, config: configuration.NamespaceConfig) -> None: """Updates server, break_my_certs, staging, tos, and register_unsafely_without_email in config as necessary to prepare to use the test server. We have --staging/--dry-run; perform sanity check and set config.server :param str verb: subcommand called :param config: parsed command line arguments :type config: configuration.NamespaceConfig :raises errors.Error: if non-default server is used and --staging is set :raises errors.Error: if inapplicable verb is used and --dry-run is set """ # Flag combinations should produce these results: # | --staging | --dry-run | # ------------------------------------------------------------ # | --server acme-v02 | Use staging | Use staging | # | --server acme-staging-v02 | Use staging | Use staging | # | --server <other> | Conflict error | Use <other> | default_servers = (flag_default("server"), constants.STAGING_URI) if config.staging and config.server not in default_servers: raise errors.Error("--server value conflicts with --staging") if config.server == flag_default("server"): config.server = constants.STAGING_URI # If the account has already been loaded (such as by calling reconstitute before this), # clear it so that we don't try to use the prod account on the staging server. config.account = None if config.dry_run: if verb not in ["certonly", "renew", "reconfigure"]: raise errors.Error("--dry-run currently only works with the " "'certonly' or 'renew' subcommands (%r)" % verb) config.break_my_certs = config.staging = True if glob.glob(os.path.join(config.config_dir, constants.ACCOUNTS_DIR, "*")): # The user has a prod account, but might not have a staging # one; we don't want to start trying to perform interactive registration config.tos = True config.register_unsafely_without_email = True
Returns 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: configuration.NamespaceConfig
def prepare_and_parse_args(plugins: plugins_disco.PluginsRegistry, args: List[str] ) -> NamespaceConfig: """Returns 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: configuration.NamespaceConfig """ helpful = HelpfulArgumentParser(args, plugins) _add_all_groups(helpful) # --help is automatically provided by argparse 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.") # This is for developers to set the level in the cli.ini, and overrides # the --verbose flag helpful.add( None, "--verbose-level", dest="verbose_level", default=flag_default("verbose_level"), help=argparse.SUPPRESS) helpful.add( None, "-t", "--text", dest="text_mode", action="store_true", default=flag_default("text_mode"), help=argparse.SUPPRESS) helpful.add( None, "--max-log-backups", type=nonnegative_int, default=flag_default("max_log_backups"), help="Specifies 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.") helpful.add( None, "--preconfigured-renewal", dest="preconfigured_renewal", action="store_true", default=flag_default("preconfigured_renewal"), help=argparse.SUPPRESS ) helpful.add( [None, "automation", "run", "certonly", "enhance"], "-n", "--non-interactive", "--noninteractive", dest="noninteractive_mode", action="store_true", default=flag_default("noninteractive_mode"), help="Run 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 missing") helpful.add( [None, "register", "run", "certonly", "enhance"], constants.FORCE_INTERACTIVE_FLAG, action="store_true", default=flag_default("force_interactive"), help="Force 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.") helpful.add( [None, "run", "certonly", "certificates", "enhance"], "-d", "--domains", "--domain", dest="domains", metavar="DOMAIN", action=_DomainsAction, default=flag_default("domains"), help="Domain names to include. For multiple domains you can use multiple -d flags " "or enter a comma separated list of domains as a parameter. All domains will " "be included as Subject Alternative Names on the certificate. The first domain " "will be used as the certificate name, unless otherwise specified or if you " "already have a certificate with the same name. In the case of a name conflict, " "a number like -0001 will be appended to the certificate name. (default: Ask)") helpful.add( [None, "run", "certonly", "register"], "--eab-kid", dest="eab_kid", metavar="EAB_KID", help="Key Identifier for External Account Binding" ) helpful.add( [None, "run", "certonly", "register"], "--eab-hmac-key", dest="eab_hmac_key", metavar="EAB_HMAC_KEY", help="HMAC key for External Account Binding" ) helpful.add( [None, "run", "certonly", "manage", "delete", "certificates", "renew", "enhance", "reconfigure"], "--cert-name", dest="certname", metavar="CERTNAME", default=flag_default("certname"), help="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. " "Certificate name cannot contain filepath separators (i.e. '/' or '\\', depending " "on the platform). " "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)") helpful.add( [None, "testing", "renew", "certonly"], "--dry-run", action="store_true", dest="dry_run", default=flag_default("dry_run"), help="Perform a test run against the Let's Encrypt staging server, obtaining test" " (invalid) certificates but not saving them to disk. This can only be used with the" " 'certonly' and 'renew' subcommands. It may trigger webserver reloads to " " temporarily modify & roll back configuration files." " --pre-hook and --post-hook commands run by default." " --deploy-hook commands do not run, unless enabled by --run-deploy-hooks." " The test server may be overridden with --server.") helpful.add( ["testing", "renew", "certonly", "reconfigure"], "--run-deploy-hooks", action="store_true", dest="run_deploy_hooks", default=flag_default("run_deploy_hooks"), help="When performing a test run using `--dry-run` or `reconfigure`, run any applicable" " deploy hooks. This includes hooks set on the command line, saved in the" " certificate's renewal configuration file, or present in the renewal-hooks directory." " To exclude directory hooks, use --no-directory-hooks. The hook(s) will only" " be run if the dry run succeeds, and will use the current active certificate, not" " the temporary test certificate acquired during the dry run. This flag is recommended" " when modifying the deploy hook using `reconfigure`.") helpful.add( ["register", "automation"], "--register-unsafely-without-email", action="store_true", default=flag_default("register_unsafely_without_email"), help="Specifying this flag enables registering an account with no " "email address. This is strongly discouraged, because you will be " "unable to receive notice about impending expiration or " "revocation of your certificates or problems with your Certbot " "installation that will lead to failure to renew.") helpful.add( ["register", "update_account", "unregister", "automation"], "-m", "--email", default=flag_default("email"), help=config_help("email")) helpful.add(["register", "update_account", "automation"], "--eff-email", action="store_true", default=flag_default("eff_email"), dest="eff_email", help="Share your e-mail address with EFF") helpful.add(["register", "update_account", "automation"], "--no-eff-email", action="store_false", default=flag_default("eff_email"), dest="eff_email", help="Don't share your e-mail address with EFF") helpful.add( ["automation", "certonly", "run"], "--keep-until-expiring", "--keep", "--reinstall", dest="reinstall", action="store_true", default=flag_default("reinstall"), help="If 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)") helpful.add( "automation", "--expand", action="store_true", default=flag_default("expand"), help="If an existing certificate is a strict subset of the requested names, " "always expand and replace it with the additional names. (default: Ask)") helpful.add( "automation", "--version", action="version", version="%(prog)s {0}".format(certbot.__version__), help="show program's version number and exit") helpful.add( ["automation", "renew"], "--force-renewal", "--renew-by-default", dest="renew_by_default", action="store_true", default=flag_default("renew_by_default"), help="If 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.") helpful.add( "automation", "--renew-with-new-domains", dest="renew_with_new_domains", action="store_true", default=flag_default("renew_with_new_domains"), help="If 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.") helpful.add( "automation", "--reuse-key", dest="reuse_key", action="store_true", default=flag_default("reuse_key"), help="When renewing, use the same private key as the existing " "certificate.") helpful.add( "automation", "--no-reuse-key", dest="reuse_key", action="store_false", default=flag_default("reuse_key"), help="When renewing, do not use the same private key as the existing " "certificate. Not reusing private keys is the default behavior of " "Certbot. This option may be used to unset --reuse-key on an " "existing certificate.") helpful.add( "automation", "--new-key", dest="new_key", action="store_true", default=flag_default("new_key"), help="When renewing or replacing a certificate, generate a new private key, " "even if --reuse-key is set on the existing certificate. Combining " "--new-key and --reuse-key will result in the private key being replaced and " "then reused in future renewals.") helpful.add( ["automation", "renew", "certonly"], "--allow-subset-of-names", action="store_true", default=flag_default("allow_subset_of_names"), help="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.") helpful.add( "automation", "--agree-tos", dest="tos", action="store_true", default=flag_default("tos"), help="Agree to the ACME Subscriber Agreement (default: Ask)") helpful.add( ["unregister", "automation"], "--account", metavar="ACCOUNT_ID", default=flag_default("account"), help="Account ID to use") helpful.add( "automation", "--duplicate", dest="duplicate", action="store_true", default=flag_default("duplicate"), help="Allow making a certificate lineage that duplicates an existing one " "(both can be renewed in parallel)") helpful.add( ["automation", "renew", "certonly", "run"], "-q", "--quiet", dest="quiet", action="store_true", default=flag_default("quiet"), help="Silence all output except errors. Useful for automation via cron." " Implies --non-interactive.") # overwrites server, handled in HelpfulArgumentParser.parse_args() helpful.add(["testing", "revoke", "run"], "--test-cert", "--staging", dest="staging", action="store_true", default=flag_default("staging"), help="Use the Let's Encrypt staging server to obtain or revoke test (invalid) " "certificates; equivalent to --server " + constants.STAGING_URI) helpful.add( "testing", "--debug", action="store_true", default=flag_default("debug"), help="Show tracebacks in case of errors") helpful.add( [None, "certonly", "run"], "--debug-challenges", action="store_true", default=flag_default("debug_challenges"), help="After setting up challenges, wait for user input before " "submitting to CA. When used in combination with the `-v` " "option, the challenge URLs or FQDNs and their expected " "return values are shown.") helpful.add( "testing", "--no-verify-ssl", action="store_true", help=config_help("no_verify_ssl"), default=flag_default("no_verify_ssl")) helpful.add( ["testing", "standalone", "manual"], "--http-01-port", type=int, dest="http01_port", default=flag_default("http01_port"), help=config_help("http01_port")) helpful.add( ["testing", "standalone"], "--http-01-address", dest="http01_address", default=flag_default("http01_address"), help=config_help("http01_address")) helpful.add( ["testing", "nginx"], "--https-port", type=int, default=flag_default("https_port"), help=config_help("https_port")) helpful.add( "testing", "--break-my-certs", action="store_true", default=flag_default("break_my_certs"), help="Be willing to replace or renew valid certificates with invalid " "(testing/staging) certificates") helpful.add( "security", "--rsa-key-size", type=int, metavar="N", default=flag_default("rsa_key_size"), help=config_help("rsa_key_size")) helpful.add( "security", "--key-type", choices=['rsa', 'ecdsa'], type=str, default=flag_default("key_type"), help=config_help("key_type")) helpful.add( "security", "--elliptic-curve", type=str, choices=[ 'secp256r1', 'secp384r1', 'secp521r1', ], metavar="N", default=flag_default("elliptic_curve"), help=config_help("elliptic_curve")) helpful.add( "security", "--must-staple", action="store_true", dest="must_staple", default=flag_default("must_staple"), help=config_help("must_staple")) helpful.add( ["security", "enhance"], "--redirect", action="store_true", dest="redirect", default=flag_default("redirect"), help="Automatically redirect all HTTP traffic to HTTPS for the newly " "authenticated vhost. (default: redirect enabled for install and run, " "disabled for enhance)") helpful.add( "security", "--no-redirect", action="store_false", dest="redirect", default=flag_default("redirect"), help="Do not automatically redirect all HTTP traffic to HTTPS for the newly " "authenticated vhost. (default: redirect enabled for install and run, " "disabled for enhance)") helpful.add( ["security", "enhance"], "--hsts", action="store_true", dest="hsts", default=flag_default("hsts"), help="Add the Strict-Transport-Security header to every HTTP response." " Forcing browser to always use SSL for the domain." " Defends against SSL Stripping.") helpful.add( "security", "--no-hsts", action="store_false", dest="hsts", default=flag_default("hsts"), help=argparse.SUPPRESS) helpful.add( ["security", "enhance"], "--uir", action="store_true", dest="uir", default=flag_default("uir"), help='Add the "Content-Security-Policy: upgrade-insecure-requests"' ' header to every HTTP response. Forcing the browser to use' ' https:// for every http:// resource.') helpful.add( "security", "--no-uir", action="store_false", dest="uir", default=flag_default("uir"), help=argparse.SUPPRESS) helpful.add( "security", "--staple-ocsp", action="store_true", dest="staple", default=flag_default("staple"), help="Enables OCSP Stapling. A valid OCSP response is stapled to" " the certificate that the server offers during TLS.") helpful.add( "security", "--no-staple-ocsp", action="store_false", dest="staple", default=flag_default("staple"), help=argparse.SUPPRESS) helpful.add( "security", "--strict-permissions", action="store_true", default=flag_default("strict_permissions"), help="Require that all configuration files are owned by the current " "user; only needed if your config is somewhere unsafe like /tmp/") helpful.add( [None, "certonly", "renew", "run"], "--preferred-chain", dest="preferred_chain", default=flag_default("preferred_chain"), help=config_help("preferred_chain") ) helpful.add( ["manual", "standalone", "certonly", "renew"], "--preferred-challenges", dest="pref_challs", action=_PrefChallAction, default=flag_default("pref_challs"), help='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.') helpful.add( [None, "certonly", "run"], "--issuance-timeout", type=nonnegative_int, dest="issuance_timeout", default=flag_default("issuance_timeout"), help=config_help("issuance_timeout")) helpful.add( ["renew", "reconfigure"], "--pre-hook", help="Command to be run in a shell before obtaining any certificates." " Unless --disable-hook-validation is used, the command’s first word" " must be the absolute pathname of an executable or one found via the" " PATH environment variable." " 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.") helpful.add( ["renew", "reconfigure"], "--post-hook", help="Command to be run in a shell after attempting to obtain/renew" " certificates." " Unless --disable-hook-validation is used, the command’s first word" " must be the absolute pathname of an executable or one found via the" " PATH environment variable." " 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.") helpful.add(["renew", "reconfigure"], "--renew-hook", action=_RenewHookAction, help=argparse.SUPPRESS) helpful.add( "renew", "--no-random-sleep-on-renew", action="store_false", default=flag_default("random_sleep_on_renew"), dest="random_sleep_on_renew", help=argparse.SUPPRESS) helpful.add( ["renew", "reconfigure"], "--deploy-hook", action=_DeployHookAction, help='Command to be run in a shell once for each successfully' ' issued certificate.' ' Unless --disable-hook-validation is used, the command’s first word' ' must be the absolute pathname of an executable or one found via the' ' PATH environment variable.' ' 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")') helpful.add( "renew", "--disable-hook-validation", action="store_false", dest="validate_hooks", default=flag_default("validate_hooks"), help="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)") helpful.add( "renew", "--no-directory-hooks", action="store_false", default=flag_default("directory_hooks"), dest="directory_hooks", help="Disable running executables found in Certbot's hook directories" " during renewal. (default: False)") helpful.add( "renew", "--disable-renew-updates", action="store_true", default=flag_default("disable_renew_updates"), dest="disable_renew_updates", help="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.") helpful.add( "renew", "--no-autorenew", action="store_false", default=flag_default("autorenew"), dest="autorenew", help="Disable auto renewal of certificates. (default: False)") # Deprecated arguments helpful.add_deprecated_argument("--os-packages-only", 0) helpful.add_deprecated_argument("--no-self-upgrade", 0) helpful.add_deprecated_argument("--no-bootstrap", 0) helpful.add_deprecated_argument("--no-permissions-check", 0) # Populate the command line parameters for new style enhancements enhancements.populate_cli(helpful.add) _create_subparsers(helpful) _paths_parser(helpful) # _plugins_parsing should be the last thing to act upon the main # parser (--help should display plugin-specific options last) _plugins_parsing(helpful, plugins) global helpful_parser # pylint: disable=global-statement helpful_parser = helpful return helpful.parse_args()
Return our argparse type function for a config variable (default: str)
def argparse_type(variable: Any) -> Type: """Return our argparse type function for a config variable (default: str)""" # pylint: disable=protected-access if helpful_parser is not None: for action in helpful_parser.actions: if action.type is not None and action.dest == variable: return action.type return str
An empty implementation of readline.get_completer.
def get_completer() -> Optional[Callable[[], str]]: """An empty implementation of readline.get_completer."""
An empty implementation of readline.get_completer_delims.
def get_completer_delims() -> List[str]: """An empty implementation of readline.get_completer_delims.""" return []
An empty implementation of readline.parse_and_bind.
def parse_and_bind(unused_command: str) -> None: """An empty implementation of readline.parse_and_bind."""
An empty implementation of readline.set_completer.
def set_completer(unused_function: Optional[Callable[[], str]] = None) -> None: """An empty implementation of readline.set_completer."""
An empty implementation of readline.set_completer_delims.
def set_completer_delims(unused_delims: Iterable[str]) -> None: """An empty implementation of readline.set_completer_delims."""
Get the display utility. :return: the display utility :rtype: Union[FileDisplay, NoninteractiveDisplay] :raise: ValueError if the display utility is not configured yet.
def get_display() -> Union[FileDisplay, NoninteractiveDisplay]: """Get the display utility. :return: the display utility :rtype: Union[FileDisplay, NoninteractiveDisplay] :raise: ValueError if the display utility is not configured yet. """ if not _SERVICE.display: raise ValueError("This function was called too early in Certbot's execution " "as the display utility hasn't been configured yet.") return _SERVICE.display
Set the display service. :param Union[FileDisplay, NoninteractiveDisplay] display: the display service
def set_display(display: Union[FileDisplay, NoninteractiveDisplay]) -> None: """Set the display service. :param Union[FileDisplay, NoninteractiveDisplay] display: the display service """ _SERVICE.display = display
Format lines nicely to 80 chars. :param str msg: Original message :returns: Formatted message respecting newlines in message :rtype: str
def wrap_lines(msg: str) -> str: """Format lines nicely to 80 chars. :param str msg: Original message :returns: Formatted message respecting newlines in message :rtype: str """ lines = msg.splitlines() fixed_l = [] for line in lines: fixed_l.append(textwrap.fill( line, 80, break_long_words=False, break_on_hyphens=False)) return '\n'.join(fixed_l)
Place parens around first character of label. :param str label: Must contain at least one character
def parens_around_char(label: str) -> str: """Place parens around first character of label. :param str label: Must contain at least one character """ return "({first}){rest}".format(first=label[0], rest=label[1:])
Get user input with a timeout. Behaves the same as the builtin input, however, an error is raised if a user doesn't answer after timeout seconds. The default timeout value was chosen to place it just under 12 hours for users following our advice and running Certbot twice a day. :param str prompt: prompt to provide for input :param float timeout: maximum number of seconds to wait for input :returns: user response :rtype: str :raises errors.Error if no answer is given before the timeout
def input_with_timeout(prompt: Optional[str] = None, timeout: float = 36000.0) -> str: """Get user input with a timeout. Behaves the same as the builtin input, however, an error is raised if a user doesn't answer after timeout seconds. The default timeout value was chosen to place it just under 12 hours for users following our advice and running Certbot twice a day. :param str prompt: prompt to provide for input :param float timeout: maximum number of seconds to wait for input :returns: user response :rtype: str :raises errors.Error if no answer is given before the timeout """ # use of sys.stdin and sys.stdout to mimic the builtin input based on # https://github.com/python/cpython/blob/baf7bb30a02aabde260143136bdf5b3738a1d409/Lib/getpass.py#L129 if prompt: sys.stdout.write(prompt) sys.stdout.flush() line = misc.readline_with_timeout(timeout, prompt) if not line: raise EOFError return line.rstrip('\n')
Separate a comma or space separated list. :param str input_: input from the user :returns: strings :rtype: list
def separate_list_input(input_: str) -> List[str]: """Separate a comma or space separated list. :param str input_: input from the user :returns: strings :rtype: list """ no_commas = input_.replace(",", " ") # Each string is naturally unicode, this causes problems with M2Crypto SANs # TODO: check if above is still true when M2Crypto is gone ^ return [str(string) for string in no_commas.split()]
Summarizes a list of domains in the format of: example.com.com and N more domains or if there is are only two domains: example.com and www.example.com or if there is only one domain: example.com :param list domains: `str` list of domains :returns: the domain list summary :rtype: str
def summarize_domain_list(domains: List[str]) -> str: """Summarizes a list of domains in the format of: example.com.com and N more domains or if there is are only two domains: example.com and www.example.com or if there is only one domain: example.com :param list domains: `str` list of domains :returns: the domain list summary :rtype: str """ if not domains: return "" length = len(domains) if length == 1: return domains[0] elif length == 2: return " and ".join(domains) else: return "{0} and {1} more domains".format(domains[0], length-1)
Returns a human-readable description of an RFC7807 error. :param error: The ACME error :returns: a string describing the error, suitable for human consumption. :rtype: str
def describe_acme_error(error: acme_messages.Error) -> str: """Returns a human-readable description of an RFC7807 error. :param error: The ACME error :returns: a string describing the error, suitable for human consumption. :rtype: str """ parts = (error.title, error.detail) if any(parts): return ' :: '.join(part for part in parts if part is not None) if error.description: return error.description return error.typ
Pick configurator plugin.
def pick_configurator(config: configuration.NamespaceConfig, default: Optional[str], plugins: disco.PluginsRegistry, question: str = "How would you like to authenticate and install " "certificates?") -> Optional[interfaces.Plugin]: """Pick configurator plugin.""" return pick_plugin( config, default, plugins, question, (interfaces.Authenticator, interfaces.Installer))
Pick installer plugin.
def pick_installer(config: configuration.NamespaceConfig, default: Optional[str], plugins: disco.PluginsRegistry, question: str = "How would you like to install certificates?" ) -> Optional[interfaces.Installer]: """Pick installer plugin.""" return pick_plugin(config, default, plugins, question, (interfaces.Installer,))
Pick authentication plugin.
def pick_authenticator(config: configuration.NamespaceConfig, default: Optional[str], plugins: disco.PluginsRegistry, question: str = "How would you " "like to authenticate with the ACME CA?" ) -> Optional[interfaces.Authenticator]: """Pick authentication plugin.""" return pick_plugin( config, default, plugins, question, (interfaces.Authenticator,))
Get an unprepared interfaces.Installer object. :param certbot.configuration.NamespaceConfig config: Configuration :param certbot._internal.plugins.disco.PluginsRegistry plugins: All plugins registered as entry points. :returns: Unprepared installer plugin or None :rtype: Plugin or None
def get_unprepared_installer(config: configuration.NamespaceConfig, plugins: disco.PluginsRegistry) -> Optional[interfaces.Installer]: """ Get an unprepared interfaces.Installer object. :param certbot.configuration.NamespaceConfig config: Configuration :param certbot._internal.plugins.disco.PluginsRegistry plugins: All plugins registered as entry points. :returns: Unprepared installer plugin or None :rtype: Plugin or None """ _, req_inst = cli_plugin_requests(config) if not req_inst: return None installers = plugins.filter(lambda p_ep: p_ep.check_name(req_inst)) installers.init(config) if len(installers) > 1: raise errors.PluginSelectionError( "Found multiple installers with the name %s, Certbot is unable to " "determine which one to use. Skipping." % req_inst) if installers: inst = list(installers.values())[0] logger.debug("Selecting plugin: %s", inst) return inst.init(config) raise errors.PluginSelectionError( "Could not select or initialize the requested installer %s." % req_inst)
Pick plugin. :param certbot.configuration.NamespaceConfig config: Configuration :param str default: Plugin name supplied by user or ``None``. :param certbot._internal.plugins.disco.PluginsRegistry plugins: All plugins registered as entry points. :param str question: Question to be presented to the user in case multiple candidates are found. :param list ifaces: Interfaces that plugins must provide. :returns: Initialized plugin. :rtype: Plugin
def pick_plugin(config: configuration.NamespaceConfig, default: Optional[str], plugins: disco.PluginsRegistry, question: str, ifaces: Iterable[Type]) -> Optional[P]: """Pick plugin. :param certbot.configuration.NamespaceConfig config: Configuration :param str default: Plugin name supplied by user or ``None``. :param certbot._internal.plugins.disco.PluginsRegistry plugins: All plugins registered as entry points. :param str question: Question to be presented to the user in case multiple candidates are found. :param list ifaces: Interfaces that plugins must provide. :returns: Initialized plugin. :rtype: Plugin """ if default is not None: # throw more UX-friendly error if default not in plugins filtered = plugins.filter(lambda p_ep: p_ep.check_name(default)) else: if config.noninteractive_mode: # it's really bad to auto-select the single available plugin in # non-interactive mode, because an update could later add a second # available plugin raise errors.MissingCommandlineFlag( "Missing command line flags. For non-interactive execution, " "you will need to specify a plugin on the command line. Run " "with '--help plugins' to see a list of options, and see " "https://eff.org/letsencrypt-plugins for more detail on what " "the plugins do and how to use them.") filtered = plugins.visible() filtered = filtered.ifaces(ifaces) filtered.init(config) filtered.prepare() prepared = filtered.available() if len(prepared) > 1: logger.debug("Multiple candidate plugins: %s", prepared) plugin_ep1 = choose_plugin(list(prepared.values()), question) if plugin_ep1 is None: return None return cast(P, plugin_ep1.init()) elif len(prepared) == 1: plugin_ep2 = list(prepared.values())[0] logger.debug("Single candidate plugin: %s", plugin_ep2) if plugin_ep2.misconfigured: return None return plugin_ep2.init() else: logger.debug("No candidate plugin") return None
Allow the user to choose their plugin. :param list prepared: List of `~.PluginEntryPoint`. :param str question: Question to be presented to the user. :returns: Plugin entry point chosen by the user. :rtype: `~.PluginEntryPoint`
def choose_plugin(prepared: List[disco.PluginEntryPoint], question: str) -> Optional[disco.PluginEntryPoint]: """Allow the user to choose their plugin. :param list prepared: List of `~.PluginEntryPoint`. :param str question: Question to be presented to the user. :returns: Plugin entry point chosen by the user. :rtype: `~.PluginEntryPoint` """ opts = [plugin_ep.description_with_name + (" [Misconfigured]" if plugin_ep.misconfigured else "") for plugin_ep in prepared] while True: code, index = display_util.menu(question, opts, force_interactive=True) if code == display_util.OK: plugin_ep = prepared[index] if plugin_ep.misconfigured: display_util.notification( "The selected plugin encountered an error while parsing " "your server configuration and cannot be used. The error " "was:\n\n{0}".format(plugin_ep.prepare()), pause=False) else: return plugin_ep else: return None
Update the config entries to reflect the plugins we actually selected.
def record_chosen_plugins(config: configuration.NamespaceConfig, plugins: disco.PluginsRegistry, auth: Optional[interfaces.Authenticator], inst: Optional[interfaces.Installer]) -> None: """Update the config entries to reflect the plugins we actually selected.""" config.authenticator = None if auth: auth_ep = plugins.find_init(auth) if auth_ep: config.authenticator = auth_ep.name config.installer = None if inst: inst_ep = plugins.find_init(inst) if inst_ep: config.installer = inst_ep.name logger.info("Plugins selected: Authenticator %s, Installer %s", config.authenticator, config.installer)
Figure out which configurator we're going to use, modifies config.authenticator and config.installer strings to reflect that choice if necessary. :raises errors.PluginSelectionError if there was a problem :returns: tuple of (`Installer` or None, `Authenticator` or None) :rtype: tuple
def choose_configurator_plugins(config: configuration.NamespaceConfig, plugins: disco.PluginsRegistry, verb: str) -> Tuple[Optional[interfaces.Installer], Optional[interfaces.Authenticator]]: """ Figure out which configurator we're going to use, modifies config.authenticator and config.installer strings to reflect that choice if necessary. :raises errors.PluginSelectionError if there was a problem :returns: tuple of (`Installer` or None, `Authenticator` or None) :rtype: tuple """ req_auth, req_inst = cli_plugin_requests(config) installer_question = "" if verb == "enhance": installer_question = ("Which installer would you like to use to " "configure the selected enhancements?") # Which plugins do we need? if verb == "run": need_inst = need_auth = True from certbot._internal.cli import cli_command if req_auth in noninstaller_plugins and not req_inst: msg = ('With the {0} plugin, you probably want to use the "certonly" command, eg:{1}' '{1} {2} certonly --{0}{1}{1}' '(Alternatively, add a --installer flag. See https://eff.org/letsencrypt-plugins' '{1} and "--help plugins" for more information.)'.format( req_auth, os.linesep, cli_command)) raise errors.MissingCommandlineFlag(msg) else: need_inst = need_auth = False if verb == "certonly": need_auth = True elif verb in ("install", "enhance"): need_inst = True if config.authenticator: logger.warning("Specifying an authenticator doesn't make sense when " "running Certbot with verb \"%s\"", verb) # Try to meet the user's request and/or ask them to pick plugins authenticator: Optional[interfaces.Authenticator] = None installer: Optional[interfaces.Installer] = None if verb == "run" and req_auth == req_inst: # Unless the user has explicitly asked for different auth/install, # only consider offering a single choice configurator = pick_configurator(config, req_inst, plugins) authenticator = cast(Optional[interfaces.Authenticator], configurator) installer = cast(Optional[interfaces.Installer], configurator) else: if need_inst or req_inst: installer = pick_installer(config, req_inst, plugins, installer_question) if need_auth: authenticator = pick_authenticator(config, req_auth, plugins) # Report on any failures if need_inst and not installer: diagnose_configurator_problem("installer", req_inst, plugins) if need_auth and not authenticator: diagnose_configurator_problem("authenticator", req_auth, plugins) # As a special case for certonly, if a user selected apache or nginx, set # the relevant installer (unless the user specifically specified no # installer or only specified an authenticator on the command line) if verb == "certonly" and authenticator is not None: # user specified --nginx or --apache on CLI selected_configurator = config.nginx or config.apache # user didn't request an authenticator, and so interactively chose nginx # or apache interactively_selected = req_auth is None and authenticator.name in ("nginx", "apache") if selected_configurator or interactively_selected: installer = cast(Optional[interfaces.Installer], authenticator) logger.debug("Selected authenticator %s and installer %s", authenticator, installer) record_chosen_plugins(config, plugins, authenticator, installer) return installer, authenticator
Setting configurators multiple ways is okay, as long as they all agree :param str previously: previously identified request for the installer/authenticator :param str now: the request currently being processed
def set_configurator(previously: Optional[str], now: Optional[str]) -> Optional[str]: """ Setting configurators multiple ways is okay, as long as they all agree :param str previously: previously identified request for the installer/authenticator :param str now: the request currently being processed """ if not now: # we're not actually setting anything return previously if previously: if previously != now: msg = "Too many flags setting configurators/installers/authenticators {0} -> {1}" raise errors.PluginSelectionError(msg.format(repr(previously), repr(now))) return now
Figure out which plugins the user requested with CLI and config options :returns: (requested authenticator string or None, requested installer string or None) :rtype: tuple
def cli_plugin_requests(config: configuration.NamespaceConfig ) -> Tuple[Optional[str], Optional[str]]: """ Figure out which plugins the user requested with CLI and config options :returns: (requested authenticator string or None, requested installer string or None) :rtype: tuple """ req_inst = req_auth = config.configurator req_inst = set_configurator(req_inst, config.installer) req_auth = set_configurator(req_auth, config.authenticator) if config.nginx: req_inst = set_configurator(req_inst, "nginx") req_auth = set_configurator(req_auth, "nginx") if config.apache: req_inst = set_configurator(req_inst, "apache") req_auth = set_configurator(req_auth, "apache") if config.standalone: req_auth = set_configurator(req_auth, "standalone") if config.webroot: req_auth = set_configurator(req_auth, "webroot") if config.manual: req_auth = set_configurator(req_auth, "manual") if config.dns_cloudflare: req_auth = set_configurator(req_auth, "dns-cloudflare") if config.dns_digitalocean: req_auth = set_configurator(req_auth, "dns-digitalocean") if config.dns_dnsimple: req_auth = set_configurator(req_auth, "dns-dnsimple") if config.dns_dnsmadeeasy: req_auth = set_configurator(req_auth, "dns-dnsmadeeasy") if config.dns_gehirn: req_auth = set_configurator(req_auth, "dns-gehirn") if config.dns_google: req_auth = set_configurator(req_auth, "dns-google") if config.dns_linode: req_auth = set_configurator(req_auth, "dns-linode") if config.dns_luadns: req_auth = set_configurator(req_auth, "dns-luadns") if config.dns_nsone: req_auth = set_configurator(req_auth, "dns-nsone") if config.dns_ovh: req_auth = set_configurator(req_auth, "dns-ovh") if config.dns_rfc2136: req_auth = set_configurator(req_auth, "dns-rfc2136") if config.dns_route53: req_auth = set_configurator(req_auth, "dns-route53") if config.dns_sakuracloud: req_auth = set_configurator(req_auth, "dns-sakuracloud") logger.debug("Requested authenticator %s and installer %s", req_auth, req_inst) return req_auth, req_inst
Raise the most helpful error message about a plugin being unavailable :param str cfg_type: either "installer" or "authenticator" :param str requested: the plugin that was requested :param .PluginsRegistry plugins: available plugins :raises error.PluginSelectionError: if there was a problem
def diagnose_configurator_problem(cfg_type: str, requested: Optional[str], plugins: disco.PluginsRegistry) -> None: """ Raise the most helpful error message about a plugin being unavailable :param str cfg_type: either "installer" or "authenticator" :param str requested: the plugin that was requested :param .PluginsRegistry plugins: available plugins :raises error.PluginSelectionError: if there was a problem """ if requested: if requested not in plugins: msg = "The requested {0} plugin does not appear to be installed".format(requested) else: msg = ("The {0} plugin is not working; there may be problems with " "your existing configuration.\nThe error was: {1!r}" .format(requested, plugins[requested].problem)) elif cfg_type == "installer": from certbot._internal.cli import cli_command msg = ('Certbot doesn\'t know how to automatically configure the web ' 'server on this system. However, it can still get a certificate for ' 'you. Please run "{0} certonly" to do so. You\'ll need to ' 'manually configure your web server to use the resulting ' 'certificate.').format(cli_command) else: msg = "{0} could not be determined or is not installed".format(cfg_type) raise errors.PluginSelectionError(msg)
Validates and returns the absolute path of webroot_path. :param str webroot_path: path to the webroot directory :returns: absolute path of webroot_path :rtype: str
def _validate_webroot(webroot_path: str) -> str: """Validates and returns the absolute path of webroot_path. :param str webroot_path: path to the webroot directory :returns: absolute path of webroot_path :rtype: str """ if not os.path.isdir(webroot_path): raise errors.PluginError(webroot_path + " does not exist or is not a directory") return os.path.abspath(webroot_path)
Generate a dummy authorization response.
def gen_auth_resp(chall_list): """Generate a dummy authorization response.""" return ["%s%s" % (chall.__class__.__name__, chall.domain) for chall in chall_list]
Generates new authzr for domains.
def gen_dom_authzr(domain, challs): """Generates new authzr for domains.""" return acme_util.gen_authzr( messages.STATUS_PENDING, domain, challs, [messages.STATUS_PENDING] * len(challs))