Coverage for certbot/client.py : 91%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
"""Certbot client API."""
# https://github.com/python/typeshed/blob/master/third_party/ # 2/cryptography/hazmat/primitives/asymmetric/rsa.pyi
"Wrangle ACME client construction" # TODO: Allow for other alg types besides RS256 user_agent=determine_user_agent(config))
""" Set a user_agent string in the config based on the choice of plugins. (this wasn't knowable at construction time)
:returns: the client's User-Agent string :rtype: `str` """
# WARNING: To ensure changes are in line with Certbot's privacy # policy, talk to a core Certbot team member before making any # changes here. "({5}; flags: {6}) Py/{7}") else: config.authenticator, config.installer, config.verb, ua_flags(config), python_version, "; " + config.user_agent_comment if config.user_agent_comment else "") else:
"Turn some very important CLI flags into clues in the user agent." flags.append("dup") flags.append("frn") flags.append("asn")
"Shim for computing a sample user agent."
"Any config properties we might have are None."
"Document what this Certbot's user agent string will be like."
"""Register new account with an ACME CA.
This function takes care of generating fresh private key, registering the account, optionally accepting CA Terms of Service and finally saving the account. It should be called prior to initialization of `Client`, unless account has already been created.
:param .IConfig config: Client configuration.
:param .AccountStorage account_storage: Account storage where newly registered account will be saved to. Save happens only after TOS acceptance step, so any account private keys or `.RegistrationResource` will not be persisted if `tos_cb` returns ``False``.
:param tos_cb: If ACME CA requires the user to accept a Terms of Service before registering account, client action is necessary. For example, a CLI tool would prompt the user acceptance. `tos_cb` must be a callable that should accept `.RegistrationResource` and return a `bool`: ``True`` iff the Terms of Service present in the contained `.Registration.terms_of_service` is accepted by the client, and ``False`` otherwise. ``tos_cb`` will be called only if the client action is necessary, i.e. when ``terms_of_service is not None``. This argument is optional, if not supplied it will default to automatic acceptance!
:raises certbot.errors.Error: In case of any client problems, in particular registration failure, or unaccepted Terms of Service. :raises acme.errors.Error: In case of any protocol problems.
:returns: Newly registered and saved account, as well as protocol API handle (should be used in `Client` initialization). :rtype: `tuple` of `.Account` and `acme.client.Client`
""" # Log non-standard actions, potentially wrong API calls logger.info("There are already existing accounts for %s", config.server) "--register-unsafely-without-email was not present.")
# If --dry-run is used, and there is no staging account, create one with no email.
# Each new registration shall use a fresh new key public_exponent=65537, key_size=config.rsa_key_size, backend=default_backend()) # TODO: add phone?
""" Actually register new account, trying repeatedly if there are email problems
:param acme.client.Client client: ACME client object. :param .IConfig config: Client configuration. :param Callable tos_cb: a callback to handle Term of Service agreement.
:returns: Registration Resource. :rtype: `acme.messages.RegistrationResource` """
kid=config.eab_kid, hmac_key=config.eab_hmac_key, directory=acme.client.directory) else:
" Please use --eab-kid and --eab-hmac-key.")
external_account_binding=eab) "Please ensure it is a valid email and attempt " "registration again." % config.email) else: else:
"""Certbot's client.
:ivar .IConfig config: Client configuration. :ivar .Account account: Account registered with `register`. :ivar .AuthHandler auth_handler: Authorizations handler that will dispatch DV challenges to appropriate authenticators (providing `.IAuthenticator` interface). :ivar .IAuthenticator auth: Prepared (`.IAuthenticator.prepare`) authenticator that can solve ACME challenges. :ivar .IInstaller installer: Installer. :ivar acme.client.BackwardsCompatibleClientV2 acme: Optional ACME client API handle. You might already have one from `register`.
"""
"""Initialize a client."""
# Initialize ACME if account is provided
auth, self.acme, self.account, self.config.pref_challs) else:
"""Obtain certificate.
:param .util.CSR csr: PEM-encoded Certificate Signing Request. The key used to generate this CSR can be different than `authkey`. :param acme.messages.OrderResource orderr: contains authzrs
:returns: certificate and chain as PEM byte strings :rtype: tuple
""" "not set.") raise errors.Error("Please register with the ACME server first.")
"""Obtains a certificate from the ACME server.
`.register` must be called before `.obtain_certificate`
:param list domains: domains to get a certificate
:returns: certificate as PEM string, chain as PEM string, newly generated private key (`.util.Key`), and DER-encoded Certificate Signing Request (`.util.CSR`). :rtype: tuple
"""
# We need to determine the key path, key PEM data, CSR path, # and CSR PEM data. For a dry run, the paths are None because # they aren't permanently saved to disk. For a lineage with # --reuse-key, the key path and PEM data are derived from an # existing file.
# We've been asked to reuse a specific existing private key. # Therefore, we'll read it now and not generate a new one in # either case below. # # We read in bytes here because the type of `key.pem` # created below is also bytes. with open(old_keypath, "rb") as f: keypath = old_keypath keypem = f.read() key = util.Key(file=keypath, pem=keypem) # type: Optional[util.Key] logger.info("Reusing existing private key from %s.", old_keypath) else: # The key is set to None here but will be created below.
# Create CSR from names pem=crypto_util.make_key(self.config.rsa_key_size)) data=acme_crypto_util.make_csr( key.pem, domains, self.config.must_staple)) else: self.config.key_dir)
# allow_subset_of_names is currently disabled for wildcard # certificates. The reason for this and checking allow_subset_of_names # below is because successful_domains == domains is never true if # domains contains a wildcard because the ACME spec forbids identifiers # in authzs from containing a wildcard character. else:
"""Request a new order and complete its authorizations.
:param str csr_pem: A CSR in PEM format. :param bool best_effort: True if failing to complete all authorizations should not raise an exception
:returns: order resource containing its completed authorizations :rtype: acme.messages.OrderResource
""" except acme_errors.WildcardUnsupportedError: raise errors.Error("The currently selected ACME CA endpoint does" " not support issuing wildcard certificates.")
# pylint: disable=no-member """Obtain and enroll certificate.
Get a new certificate for the specified domains using the specified authenticator and installer, and then create a new renewable lineage containing it.
:param domains: domains to request a certificate for :type domains: `list` of `str` :param certname: requested name of lineage :type certname: `str` or `None`
:returns: A new :class:`certbot.storage.RenewableCert` instance referred to the enrolled cert lineage, False if the cert could not be obtained, or None if doing a successful dry run.
"""
self.config.work_dir != constants.CLI_DEFAULTS["work_dir"]): "Non-standard path(s), might not work with crontab installed " "by your operating system package manager")
new_name) else: new_name, cert, key.pem, chain, self.config)
"""Chooses a name for the new lineage.
:param domains: domains in certificate request :type domains: `list` of `str` :param certname: requested name of lineage :type certname: `str` or `None`
:returns: lineage name that should be used :rtype: str
""" # Don't make files and directories starting with *. else:
cert_path, chain_path, fullchain_path): """Saves the certificate received from the ACME server.
:param str cert_pem: :param str chain_pem: :param str cert_path: Candidate path to a certificate. :param str chain_path: Candidate path to a certificate chain. :param str fullchain_path: Candidate path to a full cert chain.
:returns: cert_path, chain_path, and fullchain_path as absolute paths to the actual files :rtype: `tuple` of `str`
:raises IOError: If unable to find room to write the cert files
""" os.path.dirname(path), 0o755, compat.os_geteuid(), self.config.strict_permissions)
finally: abs_cert_path)
_open_pem_file('chain_path', chain_path) _open_pem_file('fullchain_path', fullchain_path)
cert_path, chain_path, fullchain_path): """Install certificate
:param list domains: list of domains to install the certificate :param str privkey_path: path to certificate private key :param str cert_path: certificate file path (optional) :param str chain_path: chain file path
""" "the certificate")
domain=dom, cert_path=os.path.abspath(cert_path), key_path=os.path.abspath(privkey_path), chain_path=chain_path, fullchain_path=fullchain_path)
"however, we successfully restored your " "server to its prior configuration.") # sites may have been enabled / final cleanup
"""Enhance the configuration.
:param list domains: list of domains to configure :param chain_path: chain file path :type chain_path: `str` or `None`
:raises .errors.Error: if no installer is specified in the client.
""" "configuration to enhance.")
("hsts", "ensure-http-header", "Strict-Transport-Security"), ("redirect", "redirect", None), ("staple", "staple-ocsp", chain_path), ("uir", "ensure-http-header", "Upgrade-Insecure-Requests"),)
"Option %s is not supported by the selected installer. " "Skipping enhancement.", config_name)
"""Applies an enhancement on all domains.
:param list domains: list of ssl_vhosts (as strings) :param str enhancement: name of enhancement, e.g. ensure-http-header :param str options: options to enhancement, e.g. Strict-Transport-Security
.. note:: When more `options` are needed, make options a list.
:raises .errors.PluginError: If Enhancement is not supported, or if there is any other problem with the enhancement.
""" "however, we successfully installed your certificate." % (enhancement)) options) else: enhancement) enhancement, dom)
"""Calls the installer's recovery routine and prints success_msg
:param str success_msg: message to show on successful recovery
"""
"""Rollback the most recent checkpoint and restart the webserver
:param str success_msg: message to show on successful rollback
""" "An error occurred and we failed to restore your config and " "restart your server. Please post to " "https://community.letsencrypt.org/c/server-config " "with details about your configuration and this error you received.", reporter.HIGH_PRIORITY)
"""Validate Key and CSR files.
Verifies that the client key and csr arguments are valid and correspond to one another. This does not currently check the names in the CSR due to the inability to read SANs from CSRs in python crypto libraries.
If csr is left as None, only the key will be validated.
:param privkey: Key associated with CSR :type privkey: :class:`certbot.util.Key`
:param .util.CSR csr: CSR
:raises .errors.Error: when validation fails
""" # TODO: Handle all of these problems appropriately # The client can eventually do things like prompt the user # and allow the user to take more appropriate actions
# Key must be readable and valid. if privkey.pem and not crypto_util.valid_privkey(privkey.pem): raise errors.Error("The provided key is not a valid key")
if csr: if csr.form == "der": csr_obj = OpenSSL.crypto.load_certificate_request( OpenSSL.crypto.FILETYPE_ASN1, csr.data) cert_buffer = OpenSSL.crypto.dump_certificate_request( OpenSSL.crypto.FILETYPE_PEM, csr_obj ) csr = util.CSR(csr.file, cert_buffer, "pem")
# If CSR is provided, it must be readable and valid. if csr.data and not crypto_util.valid_csr(csr.data): raise errors.Error("The provided CSR is not a valid CSR")
# If both CSR and key are provided, the key must be the same key used # in the CSR. if csr.data and privkey.pem: if not crypto_util.csr_matches_pubkey( csr.data, privkey.pem): raise errors.Error("The key and CSR do not match")
"""Revert configuration the specified number of checkpoints.
:param int checkpoints: Number of checkpoints to revert.
:param config: Configuration. :type config: :class:`certbot.interfaces.IConfig`
""" # Misconfigurations are only a slight problems... allow the user to rollback config, default_installer, plugins, question="Which installer " "should be used for rollback?")
# No Errors occurred during init... proceed normally # If installer is None... couldn't find an installer... there shouldn't be # anything to rollback
"""View checkpoints and associated configuration changes.
.. note:: This assumes that the installation is using a Reverter object.
:param config: Configuration. :type config: :class:`certbot.interfaces.IConfig`
""" rev = reverter.Reverter(config) rev.recovery_routine() rev.view_config_changes(num)
"""Open a pem file.
If cli_arg_path was set by the client, open that. Otherwise, uniquify the file path.
:param str cli_arg_path: the cli arg name, e.g. cert_path :param str pem_path: the pem file path to open
:returns: a tuple of file object and its absolute file path
""" return util.safe_open(pem_path, chmod=0o644, mode="wb"),\ os.path.abspath(pem_path) else:
"""Saves chain_pem at a unique path based on chain_path.
:param str chain_pem: certificate chain in PEM format :param str chain_file: chain file object
""" finally:
|