response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Write the specified values to a config file. :param dict values: A map of values to write. :param str path: Where to write the values.
def write(values: Mapping[str, Any], path: str) -> None: """Write the specified values to a config file. :param dict values: A map of values to write. :param str path: Where to write the values. """ config = configobj.ConfigObj() for key in values: config[key] = values[key] with open(path, "wb") as f: config.write(outfile=f) filesystem.chmod(path, 0o600)
Generator to yield the enabled new style enhancements. :param config: Configuration. :type config: certbot.configuration.NamespaceConfig
def enabled_enhancements( config: configuration.NamespaceConfig) -> Generator[Dict[str, Any], None, None]: """ Generator to yield the enabled new style enhancements. :param config: Configuration. :type config: certbot.configuration.NamespaceConfig """ for enh in _INDEX: if getattr(config, enh["cli_dest"]): yield enh
Checks if one or more of the requested enhancements are those of the new enhancement interfaces. :param config: Configuration. :type config: certbot.configuration.NamespaceConfig
def are_requested(config: configuration.NamespaceConfig) -> bool: """ Checks if one or more of the requested enhancements are those of the new enhancement interfaces. :param config: Configuration. :type config: certbot.configuration.NamespaceConfig """ return any(enabled_enhancements(config))
Checks that all of the requested enhancements are supported by the installer. :param config: Configuration. :type config: certbot.configuration.NamespaceConfig :param installer: Installer object :type installer: interfaces.Installer :returns: If all the requested enhancements are supported by the installer :rtype: bool
def are_supported(config: configuration.NamespaceConfig, installer: Optional[interfaces.Installer]) -> bool: """ Checks that all of the requested enhancements are supported by the installer. :param config: Configuration. :type config: certbot.configuration.NamespaceConfig :param installer: Installer object :type installer: interfaces.Installer :returns: If all the requested enhancements are supported by the installer :rtype: bool """ for enh in enabled_enhancements(config): if not isinstance(installer, enh["class"]): return False return True
Run enable method for each requested enhancement that is supported. :param lineage: Certificate lineage object :type lineage: certbot.interfaces.RenewableCert :param domains: List of domains in certificate to enhance :type domains: str :param installer: Installer object :type installer: interfaces.Installer :param config: Configuration. :type config: certbot.configuration.NamespaceConfig
def enable(lineage: Optional[interfaces.RenewableCert], domains: Iterable[str], installer: Optional[interfaces.Installer], config: configuration.NamespaceConfig) -> None: """ Run enable method for each requested enhancement that is supported. :param lineage: Certificate lineage object :type lineage: certbot.interfaces.RenewableCert :param domains: List of domains in certificate to enhance :type domains: str :param installer: Installer object :type installer: interfaces.Installer :param config: Configuration. :type config: certbot.configuration.NamespaceConfig """ if installer: for enh in enabled_enhancements(config): getattr(installer, enh["enable_function"])(lineage, domains)
Populates the command line flags for certbot._internal.cli.HelpfulParser :param add: Add function of certbot._internal.cli.HelpfulParser :type add: func
def populate_cli(add: Callable[..., None]) -> None: """ Populates the command line flags for certbot._internal.cli.HelpfulParser :param add: Add function of certbot._internal.cli.HelpfulParser :type add: func """ for enh in _INDEX: add(enh["cli_groups"], enh["cli_flag"], action=enh["cli_action"], dest=enh["cli_dest"], default=enh["cli_flag_default"], help=enh["cli_help"])
Retrieves all possible path prefixes of a path, in descending order of length. For instance: * (Linux) `/a/b/c` returns `['/a/b/c', '/a/b', '/a', '/']` * (Windows) `C:\a\b\c` returns `['C:\a\b\c', 'C:\a\b', 'C:\a', 'C:']` :param str path: the path to break into prefixes :returns: all possible path prefixes of given path in descending order :rtype: `list` of `str`
def get_prefixes(path: str) -> List[str]: """Retrieves all possible path prefixes of a path, in descending order of length. For instance: * (Linux) `/a/b/c` returns `['/a/b/c', '/a/b', '/a', '/']` * (Windows) `C:\\a\\b\\c` returns `['C:\\a\\b\\c', 'C:\\a\\b', 'C:\\a', 'C:']` :param str path: the path to break into prefixes :returns: all possible path prefixes of given path in descending order :rtype: `list` of `str` """ prefix = os.path.normpath(path) prefixes: List[str] = [] while prefix: prefixes.append(prefix) prefix, _ = os.path.split(prefix) # break once we hit the root path if prefix == prefixes[-1]: break return prefixes
Attempt to perform PATH surgery to find cmd Mitigates https://github.com/certbot/certbot/issues/1833 :param str cmd: the command that is being searched for in the PATH :returns: True if the operation succeeded, False otherwise
def path_surgery(cmd: str) -> bool: """Attempt to perform PATH surgery to find cmd Mitigates https://github.com/certbot/certbot/issues/1833 :param str cmd: the command that is being searched for in the PATH :returns: True if the operation succeeded, False otherwise """ path = os.environ["PATH"] added = [] for d in STANDARD_BINARY_DIRS: if d not in path: path += os.pathsep + d added.append(d) if any(added): logger.debug("Can't find %s, attempting PATH mitigation by adding %s", cmd, os.pathsep.join(added)) os.environ["PATH"] = path if util.exe_exists(cmd): return True expanded = " expanded" if any(added) else "" logger.debug("Failed to find executable %s in%s PATH: %s", cmd, expanded, path) return False
Return ChallengeBody from Challenge.
def chall_to_challb(chall: challenges.Challenge, status: messages.Status) -> messages.ChallengeBody: """Return ChallengeBody from Challenge.""" kwargs = { "chall": chall, "uri": chall.typ + "_uri", "status": status, } if status == messages.STATUS_VALID: kwargs.update({"validated": datetime.datetime.now()}) return messages.ChallengeBody(**kwargs)
Generate an authorization resource. :param authz_status: Status object :type authz_status: :class:`acme.messages.Status` :param list challs: Challenge objects :param list statuses: status of each challenge object
def gen_authzr(authz_status: messages.Status, domain: str, challs: Iterable[challenges.Challenge], statuses: Iterable[messages.Status]) -> messages.AuthorizationResource: """Generate an authorization resource. :param authz_status: Status object :type authz_status: :class:`acme.messages.Status` :param list challs: Challenge objects :param list statuses: status of each challenge object """ challbs = tuple( chall_to_challb(chall, status) for chall, status in zip(challs, statuses) ) authz_kwargs: Dict[str, Any] = { "identifier": messages.Identifier( typ=messages.IDENTIFIER_FQDN, value=domain), "challenges": challbs, } if authz_status == messages.STATUS_VALID: authz_kwargs.update({ "status": authz_status, "expires": datetime.datetime.now() + datetime.timedelta(days=31), }) else: authz_kwargs.update({ "status": authz_status, }) return messages.AuthorizationResource( uri="https://trusted.ca/new-authz-resource", body=messages.Authorization(**authz_kwargs) )
Path to a test vector.
def vector_path(*names: str) -> str: """Path to a test vector.""" _file_manager = ExitStack() atexit.register(_file_manager.close) vector_ref = importlib_resources.files(__package__).joinpath('testdata', *names) path = _file_manager.enter_context(importlib_resources.as_file(vector_ref)) return str(path)
Load contents of a test vector.
def load_vector(*names: str) -> bytes: """Load contents of a test vector.""" vector_ref = importlib_resources.files(__package__).joinpath('testdata', *names) data = vector_ref.read_bytes() # Try at most to convert CRLF to LF when data is text try: return data.decode().replace('\r\n', '\n').encode() except ValueError: # Failed to process the file with standard encoding. # Most likely not a text file, return its bytes untouched. return data
Load certificate.
def load_cert(*names: str) -> crypto.X509: """Load certificate.""" loader = _guess_loader( names[-1], crypto.FILETYPE_PEM, crypto.FILETYPE_ASN1) return crypto.load_certificate(loader, load_vector(*names))
Load certificate request.
def load_csr(*names: str) -> crypto.X509Req: """Load certificate request.""" loader = _guess_loader( names[-1], crypto.FILETYPE_PEM, crypto.FILETYPE_ASN1) return crypto.load_certificate_request(loader, load_vector(*names))
Load ComparableX509 certificate request.
def load_comparable_csr(*names: str) -> jose.ComparableX509: """Load ComparableX509 certificate request.""" return jose.ComparableX509(load_csr(*names))
Load RSA private key.
def load_rsa_private_key(*names: str) -> jose.ComparableRSAKey: """Load RSA private key.""" loader = _guess_loader(names[-1], crypto.FILETYPE_PEM, crypto.FILETYPE_ASN1) loader_fn: Callable[..., Any] if loader == crypto.FILETYPE_PEM: loader_fn = serialization.load_pem_private_key else: loader_fn = serialization.load_der_private_key return jose.ComparableRSAKey( cast(RSAPrivateKey, loader_fn(load_vector(*names), password=None, backend=default_backend())))
Load pyOpenSSL private key.
def load_pyopenssl_private_key(*names: str) -> crypto.PKey: """Load pyOpenSSL private key.""" loader = _guess_loader( names[-1], crypto.FILETYPE_PEM, crypto.FILETYPE_ASN1) return crypto.load_privatekey(loader, load_vector(*names))
Creates a lineage defined by testfile. This creates the archive, live, and renewal directories if necessary and creates a simple lineage. :param str config_dir: path to the configuration directory :param str testfile: configuration file to base the lineage on :param bool ec: True if we generate the lineage with an ECDSA key :returns: path to the renewal conf file for the created lineage :rtype: str
def make_lineage(config_dir: str, testfile: str, ec: bool = True) -> str: """Creates a lineage defined by testfile. This creates the archive, live, and renewal directories if necessary and creates a simple lineage. :param str config_dir: path to the configuration directory :param str testfile: configuration file to base the lineage on :param bool ec: True if we generate the lineage with an ECDSA key :returns: path to the renewal conf file for the created lineage :rtype: str """ lineage_name = testfile[:-len('.conf')] conf_dir = os.path.join( config_dir, constants.RENEWAL_CONFIGS_DIR) archive_dir = os.path.join( config_dir, constants.ARCHIVE_DIR, lineage_name) live_dir = os.path.join( config_dir, constants.LIVE_DIR, lineage_name) for directory in (archive_dir, conf_dir, live_dir,): if not os.path.exists(directory): filesystem.makedirs(directory) sample_archive = vector_path('sample-archive{}'.format('-ec' if ec else '')) for kind in os.listdir(sample_archive): shutil.copyfile(os.path.join(sample_archive, kind), os.path.join(archive_dir, kind)) for kind in storage.ALL_FOUR: os.symlink(os.path.join(archive_dir, '{0}1.pem'.format(kind)), os.path.join(live_dir, '{0}.pem'.format(kind))) conf_path = os.path.join(config_dir, conf_dir, testfile) with open(vector_path(testfile)) as src: with open(conf_path, 'w') as dst: dst.writelines( line.replace('MAGICDIR', config_dir) for line in src) return conf_path
Patch certbot.display.util to use a special mock display utility. The mock display utility works like a regular mock object, except it also also asserts that methods are called with valid arguments. The mock created by this patch mocks out Certbot internals. That is, the mock object will be called by the certbot.display.util functions and the mock returned by that call will be used as the display utility. This was done to simplify the transition from zope.component and mocking certbot.display.util functions directly in test code should be preferred over using this function in the future. See https://github.com/certbot/certbot/issues/8948 :returns: patch on the function used internally by certbot.display.util to get a display utility instance :rtype: mock.MagicMock
def patch_display_util() -> mock.MagicMock: """Patch certbot.display.util to use a special mock display utility. The mock display utility works like a regular mock object, except it also also asserts that methods are called with valid arguments. The mock created by this patch mocks out Certbot internals. That is, the mock object will be called by the certbot.display.util functions and the mock returned by that call will be used as the display utility. This was done to simplify the transition from zope.component and mocking certbot.display.util functions directly in test code should be preferred over using this function in the future. See https://github.com/certbot/certbot/issues/8948 :returns: patch on the function used internally by certbot.display.util to get a display utility instance :rtype: mock.MagicMock """ return cast(mock.MagicMock, mock.patch('certbot._internal.display.obj.get_display', new_callable=_create_display_util_mock))
Patch certbot.display.util to use a special mock display utility. The mock display utility works like a regular mock object, except it also asserts that methods are called with valid arguments. The mock created by this patch mocks out Certbot internals. That is, the mock object will be called by the certbot.display.util functions and the mock returned by that call will be used as the display utility. This was done to simplify the transition from zope.component and mocking certbot.display.util functions directly in test code should be preferred over using this function in the future. See https://github.com/certbot/certbot/issues/8948 The `message` argument passed to the display utility methods is passed to stdout's write method. :param object stdout: object to write standard output to; it is expected to have a `write` method :returns: patch on the function used internally by certbot.display.util to get a display utility instance :rtype: mock.MagicMock
def patch_display_util_with_stdout( stdout: Optional[IO] = None) -> mock.MagicMock: """Patch certbot.display.util to use a special mock display utility. The mock display utility works like a regular mock object, except it also asserts that methods are called with valid arguments. The mock created by this patch mocks out Certbot internals. That is, the mock object will be called by the certbot.display.util functions and the mock returned by that call will be used as the display utility. This was done to simplify the transition from zope.component and mocking certbot.display.util functions directly in test code should be preferred over using this function in the future. See https://github.com/certbot/certbot/issues/8948 The `message` argument passed to the display utility methods is passed to stdout's write method. :param object stdout: object to write standard output to; it is expected to have a `write` method :returns: patch on the function used internally by certbot.display.util to get a display utility instance :rtype: mock.MagicMock """ stdout = stdout if stdout else io.StringIO() return cast(mock.MagicMock, mock.patch('certbot._internal.display.obj.get_display', new=_create_display_util_mock_with_stdout(stdout)))
Acquire a file lock on given path, then wait to release it. This worker is coordinated using events to signal when the lock should be acquired and released. :param multiprocessing.Event event_in: event object to signal when to release the lock :param multiprocessing.Event event_out: event object to signal when the lock is acquired :param path: the path to lock
def _handle_lock(event_in: synchronize.Event, event_out: synchronize.Event, path: str) -> None: """ Acquire a file lock on given path, then wait to release it. This worker is coordinated using events to signal when the lock should be acquired and released. :param multiprocessing.Event event_in: event object to signal when to release the lock :param multiprocessing.Event event_out: event object to signal when the lock is acquired :param path: the path to lock """ if os.path.isdir(path): my_lock = lock.lock_dir(path) else: my_lock = lock.LockFile(path) try: event_out.set() assert event_in.wait(timeout=20), 'Timeout while waiting to release the lock.' finally: my_lock.release()
Grab a lock on path_to_lock from a foreign process then execute the callback. :param callable callback: object to call after acquiring the lock :param str path_to_lock: path to file or directory to lock
def lock_and_call(callback: Callable[[], Any], path_to_lock: str) -> None: """ Grab a lock on path_to_lock from a foreign process then execute the callback. :param callable callback: object to call after acquiring the lock :param str path_to_lock: path to file or directory to lock """ # Reload certbot.util module to reset internal _LOCKS dictionary. reload_module(util) emit_event = multiprocessing.Event() receive_event = multiprocessing.Event() process = multiprocessing.Process(target=_handle_lock, args=(emit_event, receive_event, path_to_lock)) process.start() # Wait confirmation that lock is acquired assert receive_event.wait(timeout=10), 'Timeout while waiting to acquire the lock.' # Execute the callback callback() # Trigger unlock from foreign process emit_event.set() # Wait for process termination process.join(timeout=10) assert process.exitcode == 0
Decorator to skip permanently a test on Windows. A reason is required.
def skip_on_windows(reason: str) -> Callable[[Callable[..., Any]], Callable[..., Any]]: """Decorator to skip permanently a test on Windows. A reason is required.""" def wrapper(function: Callable[..., Any]) -> Callable[..., Any]: """Wrapped version""" return unittest.skipIf(sys.platform == 'win32', reason)(function) return wrapper
Return the given path joined to the tempdir path for the current platform Eg.: 'cert' => /tmp/cert (Linux) or 'C:\Users\currentuser\AppData\Temp\cert' (Windows)
def temp_join(path: str) -> str: """ Return the given path joined to the tempdir path for the current platform Eg.: 'cert' => /tmp/cert (Linux) or 'C:\\Users\\currentuser\\AppData\\Temp\\cert' (Windows) """ return os.path.join(tempfile.gettempdir(), path)
Converts a ChallengeBody object to an AnnotatedChallenge. :param .ChallengeBody challb: ChallengeBody :param .JWK account_key: Authorized Account Key :param str domain: Domain of the challb :returns: Appropriate AnnotatedChallenge :rtype: :class:`certbot.achallenges.AnnotatedChallenge`
def challb_to_achall(challb: messages.ChallengeBody, account_key: josepy.JWK, domain: str) -> achallenges.AnnotatedChallenge: """Converts a ChallengeBody object to an AnnotatedChallenge. :param .ChallengeBody challb: ChallengeBody :param .JWK account_key: Authorized Account Key :param str domain: Domain of the challb :returns: Appropriate AnnotatedChallenge :rtype: :class:`certbot.achallenges.AnnotatedChallenge` """ chall = challb.chall logger.info("%s challenge for %s", chall.typ, domain) if isinstance(chall, challenges.KeyAuthorizationChallenge): return achallenges.KeyAuthorizationAnnotatedChallenge( challb=challb, domain=domain, account_key=account_key) elif isinstance(chall, challenges.DNS): return achallenges.DNS(challb=challb, domain=domain) else: return achallenges.Other(challb=challb, domain=domain)
Generate a plan to get authority over the identity. :param tuple challbs: A tuple of challenges (:class:`acme.messages.Challenge`) from :class:`acme.messages.AuthorizationResource` to be fulfilled by the client in order to prove possession of the identifier. :param list preferences: List of challenge preferences for domain (:class:`acme.challenges.Challenge` subclasses) :returns: list of indices from ``challenges``. :rtype: list :raises certbot.errors.AuthorizationError: If a path cannot be created that satisfies the CA given the preferences and combinations.
def gen_challenge_path(challbs: List[messages.ChallengeBody], preferences: List[Type[challenges.Challenge]]) -> Tuple[int, ...]: """Generate a plan to get authority over the identity. :param tuple challbs: A tuple of challenges (:class:`acme.messages.Challenge`) from :class:`acme.messages.AuthorizationResource` to be fulfilled by the client in order to prove possession of the identifier. :param list preferences: List of challenge preferences for domain (:class:`acme.challenges.Challenge` subclasses) :returns: list of indices from ``challenges``. :rtype: list :raises certbot.errors.AuthorizationError: If a path cannot be created that satisfies the CA given the preferences and combinations. """ chall_cost = {} max_cost = 1 for i, chall_cls in enumerate(preferences): chall_cost[chall_cls] = i max_cost += i # max_cost is now equal to sum(indices) + 1 best_combo: Optional[Tuple[int, ...]] = None # Set above completing all of the available challenges best_combo_cost = max_cost combinations = tuple((i,) for i in range(len(challbs))) combo_total = 0 for combo in combinations: for challenge_index in combo: combo_total += chall_cost.get(challbs[ challenge_index].chall.__class__, max_cost) if combo_total < best_combo_cost: best_combo = combo best_combo_cost = combo_total combo_total = 0 if not best_combo: raise _report_no_chall_path(challbs) return best_combo
Logs and return a raisable error reporting that no satisfiable chall path exists. :param challbs: challenges from the authorization that can't be satisfied :returns: An authorization error :rtype: certbot.errors.AuthorizationError
def _report_no_chall_path(challbs: List[messages.ChallengeBody]) -> errors.AuthorizationError: """Logs and return a raisable error reporting that no satisfiable chall path exists. :param challbs: challenges from the authorization that can't be satisfied :returns: An authorization error :rtype: certbot.errors.AuthorizationError """ msg = ("Client with the currently selected authenticator does not support " "any combination of challenges that will satisfy the CA.") if len(challbs) == 1 and isinstance(challbs[0].chall, challenges.DNS01): msg += ( " You may need to use an authenticator " "plugin that can do challenges over DNS.") logger.critical(msg) return errors.AuthorizationError(msg)
Creates a user friendly error message about failed challenges. :param list failed_achalls: A list of failed :class:`certbot.achallenges.AnnotatedChallenge` with the same error type. :returns: A formatted error message for the client. :rtype: str
def _generate_failed_chall_msg(failed_achalls: List[achallenges.AnnotatedChallenge]) -> str: """Creates a user friendly error message about failed challenges. :param list failed_achalls: A list of failed :class:`certbot.achallenges.AnnotatedChallenge` with the same error type. :returns: A formatted error message for the client. :rtype: str """ error = failed_achalls[0].error typ = error.typ if messages.is_acme_error(error): typ = error.code msg = [] for achall in failed_achalls: msg.append("\n Domain: %s\n Type: %s\n Detail: %s\n" % ( achall.domain, typ, achall.error.detail)) return "".join(msg)
Update the certificate file family symlinks to use archive_dir. Use the information in the config file to make symlinks point to the correct archive directory. .. note:: This assumes that the installation is using a Reverter object. :param config: Configuration. :type config: :class:`certbot._internal.configuration.NamespaceConfig`
def update_live_symlinks(config: configuration.NamespaceConfig) -> None: """Update the certificate file family symlinks to use archive_dir. Use the information in the config file to make symlinks point to the correct archive directory. .. note:: This assumes that the installation is using a Reverter object. :param config: Configuration. :type config: :class:`certbot._internal.configuration.NamespaceConfig` """ for renewal_file in storage.renewal_conf_files(config): storage.RenewableCert(renewal_file, config, update_symlinks=True)
Rename the specified lineage to the new name. :param config: Configuration. :type config: :class:`certbot._internal.configuration.NamespaceConfig`
def rename_lineage(config: configuration.NamespaceConfig) -> None: """Rename the specified lineage to the new name. :param config: Configuration. :type config: :class:`certbot._internal.configuration.NamespaceConfig` """ certname = get_certnames(config, "rename")[0] new_certname = config.new_certname if not new_certname: code, new_certname = display_util.input_text( "Enter the new name for certificate {0}".format(certname), force_interactive=True) if code != display_util.OK or not new_certname: raise errors.Error("User ended interaction.") lineage = lineage_for_certname(config, certname) if not lineage: raise errors.ConfigurationError("No existing certificate with name " "{0} found.".format(certname)) storage.rename_renewal_config(certname, new_certname, config) display_util.notification("Successfully renamed {0} to {1}." .format(certname, new_certname), pause=False)
Display information about certs configured with Certbot :param config: Configuration. :type config: :class:`certbot._internal.configuration.NamespaceConfig`
def certificates(config: configuration.NamespaceConfig) -> None: """Display information about certs configured with Certbot :param config: Configuration. :type config: :class:`certbot._internal.configuration.NamespaceConfig` """ parsed_certs = [] parse_failures = [] for renewal_file in storage.renewal_conf_files(config): try: renewal_candidate = storage.RenewableCert(renewal_file, config) crypto_util.verify_renewable_cert(renewal_candidate) parsed_certs.append(renewal_candidate) except Exception as e: # pylint: disable=broad-except logger.warning("Renewal configuration file %s produced an " "unexpected error: %s. Skipping.", renewal_file, e) logger.debug("Traceback was:\n%s", traceback.format_exc()) parse_failures.append(renewal_file) # Describe all the certs _describe_certs(config, parsed_certs, parse_failures)
Delete Certbot files associated with a certificate lineage.
def delete(config: configuration.NamespaceConfig) -> None: """Delete Certbot files associated with a certificate lineage.""" certnames = get_certnames(config, "delete", allow_multiple=True) msg = ["The following certificate(s) are selected for deletion:\n"] for certname in certnames: msg.append(" * " + certname) msg.append( "\nWARNING: Before continuing, ensure that the listed certificates are not being used " "by any installed server software (e.g. Apache, nginx, mail servers). Deleting a " "certificate that is still being used will cause the server software to stop working. " "See https://certbot.org/deleting-certs for information on deleting certificates safely." ) msg.append("\nAre you sure you want to delete the above certificate(s)?") if not display_util.yesno("\n".join(msg), default=True): logger.info("Deletion of certificate(s) canceled.") return for certname in certnames: storage.delete_files(config, certname) display_util.notify("Deleted all files relating to certificate {0}." .format(certname))
Find a lineage object with name certname.
def lineage_for_certname(cli_config: configuration.NamespaceConfig, certname: str) -> Optional[storage.RenewableCert]: """Find a lineage object with name certname.""" configs_dir = cli_config.renewal_configs_dir # Verify the directory is there util.make_or_verify_dir(configs_dir, mode=0o755) try: renewal_file = storage.renewal_file_for_certname(cli_config, certname) except errors.CertStorageError: return None try: return storage.RenewableCert(renewal_file, cli_config) except (errors.CertStorageError, IOError): logger.debug("Renewal conf file %s is broken.", renewal_file) logger.debug("Traceback was:\n%s", traceback.format_exc()) return None
Find the domains in the cert with name certname.
def domains_for_certname(config: configuration.NamespaceConfig, certname: str) -> Optional[List[str]]: """Find the domains in the cert with name certname.""" lineage = lineage_for_certname(config, certname) return lineage.names() if lineage else None
Find existing certs that match the given domain names. This function searches for certificates whose domains are equal to the `domains` parameter and certificates whose domains are a subset of the domains in the `domains` parameter. If multiple certificates are found whose names are a subset of `domains`, the one whose names are the largest subset of `domains` is returned. If multiple certificates' domains are an exact match or equally sized subsets, which matching certificates are returned is undefined. :param config: Configuration. :type config: :class:`certbot._internal.configuration.NamespaceConfig` :param domains: List of domain names :type domains: `list` of `str` :returns: lineages representing the identically matching cert and the largest subset if they exist :rtype: `tuple` of `storage.RenewableCert` or `None`
def find_duplicative_certs(config: configuration.NamespaceConfig, domains: List[str]) -> Tuple[Optional[storage.RenewableCert], Optional[storage.RenewableCert]]: """Find existing certs that match the given domain names. This function searches for certificates whose domains are equal to the `domains` parameter and certificates whose domains are a subset of the domains in the `domains` parameter. If multiple certificates are found whose names are a subset of `domains`, the one whose names are the largest subset of `domains` is returned. If multiple certificates' domains are an exact match or equally sized subsets, which matching certificates are returned is undefined. :param config: Configuration. :type config: :class:`certbot._internal.configuration.NamespaceConfig` :param domains: List of domain names :type domains: `list` of `str` :returns: lineages representing the identically matching cert and the largest subset if they exist :rtype: `tuple` of `storage.RenewableCert` or `None` """ def update_certs_for_domain_matches(candidate_lineage: storage.RenewableCert, rv: Tuple[Optional[storage.RenewableCert], Optional[storage.RenewableCert]] ) -> Tuple[Optional[storage.RenewableCert], Optional[storage.RenewableCert]]: """Return cert as identical_names_cert if it matches, or subset_names_cert if it matches as subset """ # TODO: Handle these differently depending on whether they are # expired or still valid? identical_names_cert, subset_names_cert = rv candidate_names = set(candidate_lineage.names()) if candidate_names == set(domains): identical_names_cert = candidate_lineage elif candidate_names.issubset(set(domains)): # This logic finds and returns the largest subset-names cert # in the case where there are several available. if subset_names_cert is None: subset_names_cert = candidate_lineage elif len(candidate_names) > len(subset_names_cert.names()): subset_names_cert = candidate_lineage return (identical_names_cert, subset_names_cert) init: Tuple[Optional[storage.RenewableCert], Optional[storage.RenewableCert]] = (None, None) return _search_lineages(config, update_certs_for_domain_matches, init)
In order to match things like: /etc/letsencrypt/archive/example.com/chain1.pem. Anonymous functions which call this function are eventually passed (in a list) to `match_and_check_overlaps` to help specify the acceptable_matches. :param `.storage.RenewableCert` candidate_lineage: Lineage whose archive dir is to be searched. :param str filetype: main file name prefix e.g. "fullchain" or "chain". :returns: Files in candidate_lineage's archive dir that match the provided filetype. :rtype: list of str or None
def _archive_files(candidate_lineage: storage.RenewableCert, filetype: str) -> Optional[List[str]]: """ In order to match things like: /etc/letsencrypt/archive/example.com/chain1.pem. Anonymous functions which call this function are eventually passed (in a list) to `match_and_check_overlaps` to help specify the acceptable_matches. :param `.storage.RenewableCert` candidate_lineage: Lineage whose archive dir is to be searched. :param str filetype: main file name prefix e.g. "fullchain" or "chain". :returns: Files in candidate_lineage's archive dir that match the provided filetype. :rtype: list of str or None """ archive_dir = candidate_lineage.archive_dir pattern = [os.path.join(archive_dir, f) for f in os.listdir(archive_dir) if re.match("{0}[0-9]*.pem".format(filetype), f)] if pattern: return pattern return None
Generates the list that's passed to match_and_check_overlaps. Is its own function to make unit testing easier. :returns: list of functions :rtype: list
def _acceptable_matches() -> List[Union[Callable[[storage.RenewableCert], str], Callable[[storage.RenewableCert], Optional[List[str]]]]]: """ Generates the list that's passed to match_and_check_overlaps. Is its own function to make unit testing easier. :returns: list of functions :rtype: list """ return [lambda x: x.fullchain_path, lambda x: x.cert_path, lambda x: _archive_files(x, "cert"), lambda x: _archive_files(x, "fullchain")]
If config.cert_path is defined, try to find an appropriate value for config.certname. :param `configuration.NamespaceConfig` cli_config: parsed command line arguments :returns: a lineage name :rtype: str :raises `errors.Error`: If the specified cert path can't be matched to a lineage name. :raises `errors.OverlappingMatchFound`: If the matched lineage's archive is shared.
def cert_path_to_lineage(cli_config: configuration.NamespaceConfig) -> str: """ If config.cert_path is defined, try to find an appropriate value for config.certname. :param `configuration.NamespaceConfig` cli_config: parsed command line arguments :returns: a lineage name :rtype: str :raises `errors.Error`: If the specified cert path can't be matched to a lineage name. :raises `errors.OverlappingMatchFound`: If the matched lineage's archive is shared. """ acceptable_matches = _acceptable_matches() match = match_and_check_overlaps(cli_config, acceptable_matches, lambda x: cli_config.cert_path, lambda x: x.lineagename) return match[0]
Searches through all lineages for a match, and checks for duplicates. If a duplicate is found, an error is raised, as performing operations on lineages that have their properties incorrectly duplicated elsewhere is probably a bad idea. :param `configuration.NamespaceConfig` cli_config: parsed command line arguments :param list acceptable_matches: a list of functions that specify acceptable matches :param function match_func: specifies what to match :param function rv_func: specifies what to return
def match_and_check_overlaps(cli_config: configuration.NamespaceConfig, acceptable_matches: Iterable[Union[ Callable[[storage.RenewableCert], str], Callable[[storage.RenewableCert], Optional[List[str]]]]], match_func: Callable[[storage.RenewableCert], str], rv_func: Callable[[storage.RenewableCert], str]) -> List[str]: """ Searches through all lineages for a match, and checks for duplicates. If a duplicate is found, an error is raised, as performing operations on lineages that have their properties incorrectly duplicated elsewhere is probably a bad idea. :param `configuration.NamespaceConfig` cli_config: parsed command line arguments :param list acceptable_matches: a list of functions that specify acceptable matches :param function match_func: specifies what to match :param function rv_func: specifies what to return """ def find_matches(candidate_lineage: storage.RenewableCert, return_value: List[str], acceptable_matches: Iterable[Union[ Callable[[storage.RenewableCert], str], Callable[[storage.RenewableCert], Optional[List[str]]]]]) -> List[str]: """Returns a list of matches using _search_lineages.""" acceptable_matches_resolved = [func(candidate_lineage) for func in acceptable_matches] acceptable_matches_rv: List[str] = [] for item in acceptable_matches_resolved: if isinstance(item, list): acceptable_matches_rv += item elif item: acceptable_matches_rv.append(item) match = match_func(candidate_lineage) if match in acceptable_matches_rv: return_value.append(rv_func(candidate_lineage)) return return_value matched: List[str] = _search_lineages(cli_config, find_matches, [], acceptable_matches) if not matched: raise errors.Error(f"No match found for cert-path {cli_config.cert_path}!") elif len(matched) > 1: raise errors.OverlappingMatchFound() return matched
Returns a human readable description of info about a RenewableCert object
def human_readable_cert_info(config: configuration.NamespaceConfig, cert: storage.RenewableCert, skip_filter_checks: bool = False) -> Optional[str]: """ Returns a human readable description of info about a RenewableCert object""" certinfo = [] checker = ocsp.RevocationChecker() if config.certname and cert.lineagename != config.certname and not skip_filter_checks: return None if config.domains and not set(config.domains).issubset(cert.names()): return None now = datetime.datetime.now(pytz.UTC) reasons = [] if cert.is_test_cert: reasons.append('TEST_CERT') if cert.target_expiry <= now: reasons.append('EXPIRED') elif checker.ocsp_revoked(cert): reasons.append('REVOKED') if reasons: status = "INVALID: " + ", ".join(reasons) else: diff = cert.target_expiry - now if diff.days == 1: status = "VALID: 1 day" elif diff.days < 1: status = f"VALID: {diff.seconds // 3600} hour(s)" else: status = f"VALID: {diff.days} days" valid_string = "{0} ({1})".format(cert.target_expiry, status) serial = format(crypto_util.get_serial_from_cert(cert.cert_path), 'x') certinfo.append(f" Certificate Name: {cert.lineagename}\n" f" Serial Number: {serial}\n" f" Key Type: {cert.private_key_type}\n" f' Domains: {" ".join(cert.names())}\n' f" Expiry Date: {valid_string}\n" f" Certificate Path: {cert.fullchain}\n" f" Private Key Path: {cert.privkey}") return "".join(certinfo)
Get certname from flag, interactively, or error out.
def get_certnames(config: configuration.NamespaceConfig, verb: str, allow_multiple: bool = False, custom_prompt: Optional[str] = None) -> List[str]: """Get certname from flag, interactively, or error out.""" certname = config.certname if certname: certnames = [certname] else: filenames = storage.renewal_conf_files(config) choices = [storage.lineagename_for_filename(name) for name in filenames] if not choices: raise errors.Error("No existing certificates found.") if allow_multiple: if not custom_prompt: prompt = "Which certificate(s) would you like to {0}?".format(verb) else: prompt = custom_prompt code, certnames = display_util.checklist( prompt, choices, cli_flag="--cert-name", force_interactive=True) if code != display_util.OK: raise errors.Error("User ended interaction.") else: if not custom_prompt: prompt = "Which certificate would you like to {0}?".format(verb) else: prompt = custom_prompt code, index = display_util.menu( prompt, choices, cli_flag="--cert-name", force_interactive=True) if code != display_util.OK or index not in range(0, len(choices)): raise errors.Error("User ended interaction.") certnames = [choices[index]] return certnames
Format a results report for a category of single-line renewal outcomes
def _report_lines(msgs: Iterable[str]) -> str: """Format a results report for a category of single-line renewal outcomes""" return " " + "\n ".join(str(msg) for msg in msgs)
Format a results report for a parsed cert
def _report_human_readable(config: configuration.NamespaceConfig, parsed_certs: Iterable[storage.RenewableCert]) -> str: """Format a results report for a parsed cert""" certinfo = [] for cert in parsed_certs: cert_info = human_readable_cert_info(config, cert) if cert_info is not None: certinfo.append(cert_info) return "\n".join(certinfo)
Print information about the certs we know about
def _describe_certs(config: configuration.NamespaceConfig, parsed_certs: Iterable[storage.RenewableCert], parse_failures: Iterable[str]) -> None: """Print information about the certs we know about""" out: List[str] = [] notify = out.append if not parsed_certs and not parse_failures: notify("No certificates found.") else: if parsed_certs: match = "matching " if config.certname or config.domains else "" notify("Found the following {0}certs:".format(match)) notify(_report_human_readable(config, parsed_certs)) if parse_failures: notify("\nThe following renewal configurations " "were invalid:") notify(_report_lines(parse_failures)) display_util.notification("\n".join(out), pause=False, wrap=False)
Iterate func over unbroken lineages, allowing custom return conditions. Allows flexible customization of return values, including multiple return values and complex checks. :param `configuration.NamespaceConfig` cli_config: parsed command line arguments :param function func: function used while searching over lineages :param initial_rv: initial return value of the function (any type) :returns: Whatever was specified by `func` if a match is found.
def _search_lineages(cli_config: configuration.NamespaceConfig, func: Callable[..., T], initial_rv: T, *args: Any) -> T: """Iterate func over unbroken lineages, allowing custom return conditions. Allows flexible customization of return values, including multiple return values and complex checks. :param `configuration.NamespaceConfig` cli_config: parsed command line arguments :param function func: function used while searching over lineages :param initial_rv: initial return value of the function (any type) :returns: Whatever was specified by `func` if a match is found. """ configs_dir = cli_config.renewal_configs_dir # Verify the directory is there util.make_or_verify_dir(configs_dir, mode=0o755) rv = initial_rv for renewal_file in storage.renewal_conf_files(cli_config): try: candidate_lineage = storage.RenewableCert(renewal_file, cli_config) except (errors.CertStorageError, IOError): logger.debug("Renewal conf file %s is broken. Skipping.", renewal_file) logger.debug("Traceback was:\n%s", traceback.format_exc()) continue rv = func(candidate_lineage, rv, *args) return rv
Wrangle ACME client construction
def acme_from_config_key(config: configuration.NamespaceConfig, key: jose.JWK, regr: Optional[messages.RegistrationResource] = None ) -> acme_client.ClientV2: """Wrangle ACME client construction""" if key.typ == 'EC': public_key = key.key if public_key.key_size == 256: alg = ES256 elif public_key.key_size == 384: alg = ES384 elif public_key.key_size == 521: alg = ES512 else: raise errors.NotSupportedError( "No matching signing algorithm can be found for the key" ) else: alg = RS256 net = acme_client.ClientNetwork(key, alg=alg, account=regr, verify_ssl=(not config.no_verify_ssl), user_agent=determine_user_agent(config)) directory = acme_client.ClientV2.get_directory(config.server, net) return acme_client.ClientV2(directory, net)
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`
def determine_user_agent(config: configuration.NamespaceConfig) -> str: """ 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. if config.user_agent is None: ua = ("CertbotACMEClient/{0} ({1}; {2}{8}) Authenticator/{3} Installer/{4} " "({5}; flags: {6}) Py/{7}") if os.environ.get("CERTBOT_DOCS") == "1": cli_command = "certbot" os_info = "OS_NAME OS_VERSION" python_version = "major.minor.patchlevel" else: cli_command = cli.cli_command os_info = util.get_os_info_ua() python_version = platform.python_version() ua = ua.format(certbot.__version__, cli_command, os_info, config.authenticator, config.installer, config.verb, ua_flags(config), python_version, "; " + config.user_agent_comment if config.user_agent_comment else "") else: ua = config.user_agent return ua
Turn some very important CLI flags into clues in the user agent.
def ua_flags(config: configuration.NamespaceConfig) -> str: """Turn some very important CLI flags into clues in the user agent.""" if isinstance(config, DummyConfig): return "FLAGS" flags = [] if config.duplicate: flags.append("dup") if config.renew_by_default: flags.append("frn") if config.allow_subset_of_names: flags.append("asn") if config.noninteractive_mode: flags.append("n") hook_names = ("pre", "post", "renew", "manual_auth", "manual_cleanup") hooks = [getattr(config, h + "_hook") for h in hook_names] if any(hooks): flags.append("hook") return " ".join(flags)
Document what this Certbot's user agent string will be like.
def sample_user_agent() -> str: """Document what this Certbot's user agent string will be like.""" # DummyConfig is designed to mock certbot.configuration.NamespaceConfig. # Let mypy accept that. return determine_user_agent(cast(configuration.NamespaceConfig, DummyConfig()))
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 certbot.configuration.NamespaceConfig 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 a Term of Service URL as a string, and raise an exception if the TOS is not accepted by the client. ``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`
def register(config: configuration.NamespaceConfig, account_storage: AccountStorage, tos_cb: Optional[Callable[[str], None]] = None ) -> Tuple[account.Account, acme_client.ClientV2]: """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 certbot.configuration.NamespaceConfig 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 a Term of Service URL as a string, and raise an exception if the TOS is not accepted by the client. ``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 if account_storage.find_all(): logger.info("There are already existing accounts for %s", config.server) if config.email is None: if not config.register_unsafely_without_email: msg = ("No email was provided and " "--register-unsafely-without-email was not present.") logger.error(msg) raise errors.Error(msg) if not config.dry_run: logger.debug("Registering without email!") # If --dry-run is used, and there is no staging account, create one with no email. if config.dry_run: config.email = None # Each new registration shall use a fresh new key rsa_key = generate_private_key( public_exponent=65537, key_size=config.rsa_key_size, backend=default_backend()) key = jose.JWKRSA(key=jose.ComparableRSAKey(rsa_key)) acme = acme_from_config_key(config, key) # TODO: add phone? regr = perform_registration(acme, config, tos_cb) acc = account.Account(regr, key) account_storage.save(acc, acme) eff.prepare_subscription(config, acc) return acc, acme
Actually register new account, trying repeatedly if there are email problems :param acme.client.Client acme: ACME client object. :param certbot.configuration.NamespaceConfig config: Client configuration. :param Callable tos_cb: a callback to handle Term of Service agreement. :returns: Registration Resource. :rtype: `acme.messages.RegistrationResource`
def perform_registration(acme: acme_client.ClientV2, config: configuration.NamespaceConfig, tos_cb: Optional[Callable[[str], None]]) -> messages.RegistrationResource: """ Actually register new account, trying repeatedly if there are email problems :param acme.client.Client acme: ACME client object. :param certbot.configuration.NamespaceConfig config: Client configuration. :param Callable tos_cb: a callback to handle Term of Service agreement. :returns: Registration Resource. :rtype: `acme.messages.RegistrationResource` """ eab_credentials_supplied = config.eab_kid and config.eab_hmac_key eab: Optional[Dict[str, Any]] if eab_credentials_supplied: account_public_key = acme.net.key.public_key() eab = messages.ExternalAccountBinding.from_data(account_public_key=account_public_key, kid=config.eab_kid, hmac_key=config.eab_hmac_key, directory=acme.directory) else: eab = None if acme.external_account_required(): if not eab_credentials_supplied: msg = ("Server requires external account binding." " Please use --eab-kid and --eab-hmac-key.") raise errors.Error(msg) tos = acme.directory.meta.terms_of_service if tos_cb and tos: tos_cb(tos) try: return acme.new_account(messages.NewRegistration.from_data( email=config.email, terms_of_service_agreed=True, external_account_binding=eab)) except messages.Error as e: if e.code in ("invalidEmail", "invalidContact"): if config.noninteractive_mode: msg = (f"The ACME server believes {config.email} is an invalid email address. " "Please ensure it is a valid email and attempt " "registration again.") raise errors.Error(msg) config.email = display_ops.get_email(invalid=True) return perform_registration(acme, config, tos_cb) raise
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
def validate_key_csr(privkey: util.Key, csr: Optional[util.CSR] = None) -> None: """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 str default_installer: Default installer name to use for the rollback :param int checkpoints: Number of checkpoints to revert. :param config: Configuration. :type config: :class:`certbot.configuration.NamespaceConfiguration` :param plugins: Plugins available :type plugins: :class:`certbot._internal.plugins.disco.PluginsRegistry`
def rollback(default_installer: str, checkpoints: int, config: configuration.NamespaceConfig, plugins: plugin_disco.PluginsRegistry) -> None: """Revert configuration the specified number of checkpoints. :param str default_installer: Default installer name to use for the rollback :param int checkpoints: Number of checkpoints to revert. :param config: Configuration. :type config: :class:`certbot.configuration.NamespaceConfiguration` :param plugins: Plugins available :type plugins: :class:`certbot._internal.plugins.disco.PluginsRegistry` """ # Misconfigurations are only a slight problems... allow the user to rollback installer = plugin_selection.pick_installer( 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 if installer is not None: installer.rollback_checkpoints(checkpoints) installer.restart()
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
def _open_pem_file(config: configuration.NamespaceConfig, cli_arg_path: str, pem_path: str) -> Tuple[IO, str]: """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 """ if config.set_by_user(cli_arg_path): return util.safe_open(pem_path, chmod=0o644, mode="wb"),\ os.path.abspath(pem_path) uniq = util.unique_file(pem_path, 0o644, "wb") return uniq[0], os.path.abspath(uniq[1])
Saves chain_pem at a unique path based on chain_path. :param bytes chain_pem: certificate chain in PEM format :param str chain_file: chain file object
def _save_chain(chain_pem: bytes, chain_file: IO) -> None: """Saves chain_pem at a unique path based on chain_path. :param bytes chain_pem: certificate chain in PEM format :param str chain_file: chain file object """ try: chain_file.write(chain_pem) finally: chain_file.close()
High level function to store potential EFF newsletter subscriptions. The user may be asked if they want to sign up for the newsletter if they have not given their explicit approval or refusal using --eff-mail or --no-eff-mail flag. Decision about EFF subscription will be stored in the account metadata. :param configuration.NamespaceConfig config: Client configuration. :param Account acc: Current client account.
def prepare_subscription(config: configuration.NamespaceConfig, acc: Account) -> None: """High level function to store potential EFF newsletter subscriptions. The user may be asked if they want to sign up for the newsletter if they have not given their explicit approval or refusal using --eff-mail or --no-eff-mail flag. Decision about EFF subscription will be stored in the account metadata. :param configuration.NamespaceConfig config: Client configuration. :param Account acc: Current client account. """ if config.eff_email is False: return if config.eff_email is True: if config.email is None: _report_failure("you didn't provide an e-mail address") else: acc.meta = acc.meta.update(register_to_eff=config.email) elif config.email and _want_subscription(): acc.meta = acc.meta.update(register_to_eff=config.email) if acc.meta.register_to_eff: storage = AccountFileStorage(config) storage.update_meta(acc)
High level function to take care of EFF newsletter subscriptions. Once subscription is handled, it will not be handled again. :param configuration.NamespaceConfig config: Client configuration. :param Account acc: Current client account.
def handle_subscription(config: configuration.NamespaceConfig, acc: Optional[Account]) -> None: """High level function to take care of EFF newsletter subscriptions. Once subscription is handled, it will not be handled again. :param configuration.NamespaceConfig config: Client configuration. :param Account acc: Current client account. """ if config.dry_run or not acc: return if acc.meta.register_to_eff: subscribe(acc.meta.register_to_eff) acc.meta = acc.meta.update(register_to_eff=None) storage = AccountFileStorage(config) storage.update_meta(acc)
Does the user want to be subscribed to the EFF newsletter? :returns: True if we should subscribe the user, otherwise, False :rtype: bool
def _want_subscription() -> bool: """Does the user want to be subscribed to the EFF newsletter? :returns: True if we should subscribe the user, otherwise, False :rtype: bool """ prompt = ( 'Would you be willing, once your first certificate is successfully issued, ' 'to share your email address with the Electronic Frontier Foundation, a ' "founding partner of the Let's Encrypt project and the non-profit organization " "that develops Certbot? We'd like to send you email about our work encrypting " "the web, EFF news, campaigns, and ways to support digital freedom. ") return display_util.yesno(prompt, default=False)
Subscribe the user to the EFF mailing list. :param str email: the e-mail address to subscribe
def subscribe(email: str) -> None: """Subscribe the user to the EFF mailing list. :param str email: the e-mail address to subscribe """ url = constants.EFF_SUBSCRIBE_URI data = {'data_type': 'json', 'email': email, 'form_id': 'eff_supporters_library_subscribe_form'} logger.info('Subscribe to the EFF mailing list (email: %s).', email) logger.debug('Sending POST request to %s:\n%s', url, data) _check_response(requests.post(url, data=data, timeout=60))
Check for errors in the server's response. If an error occurred, it will be reported to the user. :param requests.Response response: the server's response to the subscription request
def _check_response(response: requests.Response) -> None: """Check for errors in the server's response. If an error occurred, it will be reported to the user. :param requests.Response response: the server's response to the subscription request """ logger.debug('Received response:\n%s', response.content) try: response.raise_for_status() if not response.json()['status']: _report_failure('your e-mail address appears to be invalid') except requests.exceptions.HTTPError: _report_failure() except (ValueError, KeyError): _report_failure('there was a problem with the server response')
Notify the user of failing to sign them up for the newsletter. :param reason: a phrase describing what the problem was beginning with a lowercase letter and no closing punctuation :type reason: `str` or `None`
def _report_failure(reason: Optional[str] = None) -> None: """Notify the user of failing to sign them up for the newsletter. :param reason: a phrase describing what the problem was beginning with a lowercase letter and no closing punctuation :type reason: `str` or `None` """ msg = ['We were unable to subscribe you the EFF mailing list'] if reason is not None: msg.append(' because ') msg.append(reason) msg.append('. You can try again later by visiting https://act.eff.org.') display_util.notify(''.join(msg))
Check hook commands are executable.
def validate_hooks(config: configuration.NamespaceConfig) -> None: """Check hook commands are executable.""" validate_hook(config.pre_hook, "pre") validate_hook(config.post_hook, "post") validate_hook(config.deploy_hook, "deploy") validate_hook(config.renew_hook, "renew")
Extract the program run by a shell command. :param str shell_cmd: command to be executed :returns: basename of command or None if the command isn't found :rtype: str or None
def _prog(shell_cmd: str) -> Optional[str]: """Extract the program run by a shell command. :param str shell_cmd: command to be executed :returns: basename of command or None if the command isn't found :rtype: str or None """ if not util.exe_exists(shell_cmd): plug_util.path_surgery(shell_cmd) if not util.exe_exists(shell_cmd): return None return os.path.basename(shell_cmd)
Check that a command provided as a hook is plausibly executable. :raises .errors.HookCommandNotFound: if the command is not found
def validate_hook(shell_cmd: str, hook_name: str) -> None: """Check that a command provided as a hook is plausibly executable. :raises .errors.HookCommandNotFound: if the command is not found """ if shell_cmd: cmd = shell_cmd.split(None, 1)[0] if not _prog(cmd): path = os.environ["PATH"] if os.path.exists(cmd): msg = f"{cmd}-hook command {hook_name} exists, but is not executable." else: msg = ( f"Unable to find {hook_name}-hook command {cmd} in the PATH.\n(PATH is " f"{path})\nSee also the --disable-hook-validation option." ) raise errors.HookCommandNotFound(msg)
Run pre-hooks if they exist and haven't already been run. When Certbot is running with the renew subcommand, this function runs any hooks found in the config.renewal_pre_hooks_dir (if they have not already been run) followed by any pre-hook in the config. If hooks in config.renewal_pre_hooks_dir are run and the pre-hook in the config is a path to one of these scripts, it is not run twice. :param configuration.NamespaceConfig config: Certbot settings
def pre_hook(config: configuration.NamespaceConfig) -> None: """Run pre-hooks if they exist and haven't already been run. When Certbot is running with the renew subcommand, this function runs any hooks found in the config.renewal_pre_hooks_dir (if they have not already been run) followed by any pre-hook in the config. If hooks in config.renewal_pre_hooks_dir are run and the pre-hook in the config is a path to one of these scripts, it is not run twice. :param configuration.NamespaceConfig config: Certbot settings """ if config.verb == "renew" and config.directory_hooks: for hook in list_hooks(config.renewal_pre_hooks_dir): _run_pre_hook_if_necessary(hook) cmd = config.pre_hook if cmd: _run_pre_hook_if_necessary(cmd)
Run the specified pre-hook if we haven't already. If we've already run this exact command before, a message is logged saying the pre-hook was skipped. :param str command: pre-hook to be run
def _run_pre_hook_if_necessary(command: str) -> None: """Run the specified pre-hook if we haven't already. If we've already run this exact command before, a message is logged saying the pre-hook was skipped. :param str command: pre-hook to be run """ if command in executed_pre_hooks: logger.info("Pre-hook command already run, skipping: %s", command) else: _run_hook("pre-hook", command) executed_pre_hooks.add(command)
Run post-hooks if defined. This function also registers any executables found in config.renewal_post_hooks_dir to be run when Certbot is used with the renew subcommand. If the verb is renew, we delay executing any post-hooks until :func:`run_saved_post_hooks` is called. In this case, this function registers all hooks found in config.renewal_post_hooks_dir to be called followed by any post-hook in the config. If the post-hook in the config is a path to an executable in the post-hook directory, it is not scheduled to be run twice. :param configuration.NamespaceConfig config: Certbot settings
def post_hook( config: configuration.NamespaceConfig, renewed_domains: List[str] ) -> None: """Run post-hooks if defined. This function also registers any executables found in config.renewal_post_hooks_dir to be run when Certbot is used with the renew subcommand. If the verb is renew, we delay executing any post-hooks until :func:`run_saved_post_hooks` is called. In this case, this function registers all hooks found in config.renewal_post_hooks_dir to be called followed by any post-hook in the config. If the post-hook in the config is a path to an executable in the post-hook directory, it is not scheduled to be run twice. :param configuration.NamespaceConfig config: Certbot settings """ cmd = config.post_hook # In the "renew" case, we save these up to run at the end if config.verb == "renew": if config.directory_hooks: for hook in list_hooks(config.renewal_post_hooks_dir): _run_eventually(hook) if cmd: _run_eventually(cmd) # certonly / run elif cmd: renewed_domains_str = ' '.join(renewed_domains) # 32k is reasonable on Windows and likely quite conservative on other platforms if len(renewed_domains_str) > 32_000: logger.warning("Limiting RENEWED_DOMAINS environment variable to 32k characters") renewed_domains_str = renewed_domains_str[:32_000] _run_hook( "post-hook", cmd, { 'RENEWED_DOMAINS': renewed_domains_str, # Since other commands stop certbot execution on failure, # it doesn't make sense to have a FAILED_DOMAINS variable 'FAILED_DOMAINS': "" } )
Registers a post-hook to be run eventually. All commands given to this function will be run exactly once in the order they were given when :func:`run_saved_post_hooks` is called. :param str command: post-hook to register to be run
def _run_eventually(command: str) -> None: """Registers a post-hook to be run eventually. All commands given to this function will be run exactly once in the order they were given when :func:`run_saved_post_hooks` is called. :param str command: post-hook to register to be run """ if command not in post_hooks: post_hooks.append(command)
Run any post hooks that were saved up in the course of the 'renew' verb
def run_saved_post_hooks(renewed_domains: List[str], failed_domains: List[str]) -> None: """Run any post hooks that were saved up in the course of the 'renew' verb""" renewed_domains_str = ' '.join(renewed_domains) failed_domains_str = ' '.join(failed_domains) # 32k combined is reasonable on Windows and likely quite conservative on other platforms if len(renewed_domains_str) > 16_000: logger.warning("Limiting RENEWED_DOMAINS environment variable to 16k characters") renewed_domains_str = renewed_domains_str[:16_000] if len(failed_domains_str) > 16_000: logger.warning("Limiting FAILED_DOMAINS environment variable to 16k characters") renewed_domains_str = failed_domains_str[:16_000] for cmd in post_hooks: _run_hook( "post-hook", cmd, { 'RENEWED_DOMAINS': renewed_domains_str, 'FAILED_DOMAINS': failed_domains_str } )
Run post-issuance hook if defined. :param configuration.NamespaceConfig config: Certbot settings :param domains: domains in the obtained certificate :type domains: `list` of `str` :param str lineage_path: live directory path for the new cert
def deploy_hook(config: configuration.NamespaceConfig, domains: List[str], lineage_path: str) -> None: """Run post-issuance hook if defined. :param configuration.NamespaceConfig config: Certbot settings :param domains: domains in the obtained certificate :type domains: `list` of `str` :param str lineage_path: live directory path for the new cert """ if config.deploy_hook: _run_deploy_hook(config.deploy_hook, domains, lineage_path, config.dry_run, config.run_deploy_hooks)
Run post-renewal hooks. This function runs any hooks found in config.renewal_deploy_hooks_dir followed by any renew-hook in the config. If the renew-hook in the config is a path to a script in config.renewal_deploy_hooks_dir, it is not run twice. If Certbot is doing a dry run, no hooks are run and messages are logged saying that they were skipped. :param configuration.NamespaceConfig config: Certbot settings :param domains: domains in the obtained certificate :type domains: `list` of `str` :param str lineage_path: live directory path for the new cert
def renew_hook(config: configuration.NamespaceConfig, domains: List[str], lineage_path: str) -> None: """Run post-renewal hooks. This function runs any hooks found in config.renewal_deploy_hooks_dir followed by any renew-hook in the config. If the renew-hook in the config is a path to a script in config.renewal_deploy_hooks_dir, it is not run twice. If Certbot is doing a dry run, no hooks are run and messages are logged saying that they were skipped. :param configuration.NamespaceConfig config: Certbot settings :param domains: domains in the obtained certificate :type domains: `list` of `str` :param str lineage_path: live directory path for the new cert """ executed_dir_hooks = set() if config.directory_hooks: for hook in list_hooks(config.renewal_deploy_hooks_dir): _run_deploy_hook(hook, domains, lineage_path, config.dry_run, config.run_deploy_hooks) executed_dir_hooks.add(hook) if config.renew_hook: if config.renew_hook in executed_dir_hooks: logger.info("Skipping deploy-hook '%s' as it was already run.", config.renew_hook) else: _run_deploy_hook(config.renew_hook, domains, lineage_path, config.dry_run, config.run_deploy_hooks)
Run the specified deploy-hook (if not doing a dry run). If dry_run is True, command is not run and a message is logged saying that it was skipped. If dry_run is False, the hook is run after setting the appropriate environment variables. :param str command: command to run as a deploy-hook :param domains: domains in the obtained certificate :type domains: `list` of `str` :param str lineage_path: live directory path for the new cert :param bool dry_run: True iff Certbot is doing a dry run :param bool run_deploy_hooks: True if deploy hooks should run despite Certbot doing a dry run
def _run_deploy_hook(command: str, domains: List[str], lineage_path: str, dry_run: bool, run_deploy_hooks: bool) -> None: """Run the specified deploy-hook (if not doing a dry run). If dry_run is True, command is not run and a message is logged saying that it was skipped. If dry_run is False, the hook is run after setting the appropriate environment variables. :param str command: command to run as a deploy-hook :param domains: domains in the obtained certificate :type domains: `list` of `str` :param str lineage_path: live directory path for the new cert :param bool dry_run: True iff Certbot is doing a dry run :param bool run_deploy_hooks: True if deploy hooks should run despite Certbot doing a dry run """ if dry_run and not run_deploy_hooks: logger.info("Dry run: skipping deploy hook command: %s", command) return os.environ["RENEWED_DOMAINS"] = " ".join(domains) os.environ["RENEWED_LINEAGE"] = lineage_path _run_hook("deploy-hook", command)
Run a hook command. :param str cmd_name: the user facing name of the hook being run :param shell_cmd: shell command to execute :type shell_cmd: `list` of `str` or `str` :param dict extra_env: extra environment variables to set :type extra_env: `dict` of `str` to `str` :returns: stderr if there was any
def _run_hook(cmd_name: str, shell_cmd: str, extra_env: Optional[Dict[str, str]] = None) -> str: """Run a hook command. :param str cmd_name: the user facing name of the hook being run :param shell_cmd: shell command to execute :type shell_cmd: `list` of `str` or `str` :param dict extra_env: extra environment variables to set :type extra_env: `dict` of `str` to `str` :returns: stderr if there was any""" env = util.env_no_snap_for_external_calls() env.update(extra_env or {}) returncode, err, out = misc.execute_command_status( cmd_name, shell_cmd, env=env) display_ops.report_executed_command(f"Hook '{cmd_name}'", returncode, out, err) return err
List paths to all hooks found in dir_path in sorted order. :param str dir_path: directory to search :returns: `list` of `str` :rtype: sorted list of absolute paths to executables in dir_path
def list_hooks(dir_path: str) -> List[str]: """List paths to all hooks found in dir_path in sorted order. :param str dir_path: directory to search :returns: `list` of `str` :rtype: sorted list of absolute paths to executables in dir_path """ allpaths = (os.path.join(dir_path, f) for f in os.listdir(dir_path)) hooks = [path for path in allpaths if filesystem.is_executable(path) and not path.endswith('~')] return sorted(hooks)
Place a lock file on the directory at dir_path. The lock file is placed in the root of dir_path with the name .certbot.lock. :param str dir_path: path to directory :returns: the locked LockFile object :rtype: LockFile :raises errors.LockError: if unable to acquire the lock
def lock_dir(dir_path: str) -> LockFile: """Place a lock file on the directory at dir_path. The lock file is placed in the root of dir_path with the name .certbot.lock. :param str dir_path: path to directory :returns: the locked LockFile object :rtype: LockFile :raises errors.LockError: if unable to acquire the lock """ return LockFile(os.path.join(dir_path, '.certbot.lock'))
Setup logging before command line arguments are parsed. Terminal logging is setup using `certbot._internal.constants.QUIET_LOGGING_LEVEL` so Certbot is as quiet as possible. File logging is setup so that logging messages are buffered in memory. If Certbot exits before `post_arg_parse_setup` is called, these buffered messages are written to a temporary file. If Certbot doesn't exit, `post_arg_parse_setup` writes the messages to the normal log files. This function also sets `logging.shutdown` to be called on program exit which automatically flushes logging handlers and `sys.excepthook` to properly log/display fatal exceptions.
def pre_arg_parse_setup() -> None: """Setup logging before command line arguments are parsed. Terminal logging is setup using `certbot._internal.constants.QUIET_LOGGING_LEVEL` so Certbot is as quiet as possible. File logging is setup so that logging messages are buffered in memory. If Certbot exits before `post_arg_parse_setup` is called, these buffered messages are written to a temporary file. If Certbot doesn't exit, `post_arg_parse_setup` writes the messages to the normal log files. This function also sets `logging.shutdown` to be called on program exit which automatically flushes logging handlers and `sys.excepthook` to properly log/display fatal exceptions. """ temp_handler = TempHandler() temp_handler.setFormatter(logging.Formatter(FILE_FMT)) temp_handler.setLevel(logging.DEBUG) memory_handler = MemoryHandler(temp_handler) stream_handler = ColoredStreamHandler() stream_handler.setFormatter(logging.Formatter(CLI_FMT)) # The pre-argparse logging level is set to WARNING here. This is to ensure that # deprecated flags (see DeprecatedArgumentAction) print something to the terminal. # See https://github.com/certbot/certbot/issues/9618. stream_handler.setLevel(logging.WARNING) root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) # send all records to handlers root_logger.addHandler(memory_handler) root_logger.addHandler(stream_handler) # logging.shutdown will flush the memory handler because flush() and # close() are explicitly called util.atexit_register(logging.shutdown) sys.excepthook = functools.partial( pre_arg_parse_except_hook, memory_handler, debug='--debug' in sys.argv, quiet='--quiet' in sys.argv or '-q' in sys.argv, log_path=temp_handler.path)
Setup logging after command line arguments are parsed. This function assumes `pre_arg_parse_setup` was called earlier and the root logging configuration has not been modified. A rotating file logging handler is created and the buffered log messages are sent to that handler. Terminal logging output is set to the level requested by the user. :param certbot.configuration.NamespaceConfig config: Configuration object
def post_arg_parse_setup(config: configuration.NamespaceConfig) -> None: """Setup logging after command line arguments are parsed. This function assumes `pre_arg_parse_setup` was called earlier and the root logging configuration has not been modified. A rotating file logging handler is created and the buffered log messages are sent to that handler. Terminal logging output is set to the level requested by the user. :param certbot.configuration.NamespaceConfig config: Configuration object """ file_handler, file_path = setup_log_file_handler( config, 'letsencrypt.log', FILE_FMT) root_logger = logging.getLogger() memory_handler = stderr_handler = None for handler in root_logger.handlers: if isinstance(handler, ColoredStreamHandler): stderr_handler = handler elif isinstance(handler, MemoryHandler): memory_handler = handler msg = 'Previously configured logging handlers have been removed!' assert memory_handler is not None and stderr_handler is not None, msg root_logger.addHandler(file_handler) root_logger.removeHandler(memory_handler) temp_handler = getattr(memory_handler, 'target', None) memory_handler.setTarget(file_handler) # pylint: disable=no-member memory_handler.flush(force=True) # pylint: disable=unexpected-keyword-arg memory_handler.close() if temp_handler: temp_handler.close() if config.quiet: level = constants.QUIET_LOGGING_LEVEL elif config.verbose_level is not None: level = constants.DEFAULT_LOGGING_LEVEL - int(config.verbose_level) * 10 else: level = constants.DEFAULT_LOGGING_LEVEL - config.verbose_count * 10 stderr_handler.setLevel(level) logger.debug('Root logging level set at %d', level) if not config.quiet: print(f'Saving debug log to {file_path}', file=sys.stderr) sys.excepthook = functools.partial( post_arg_parse_except_hook, debug=config.debug, quiet=config.quiet, log_path=file_path)
Setup file debug logging. :param certbot.configuration.NamespaceConfig config: Configuration object :param str logfile: basename for the log file :param str fmt: logging format string :returns: file handler and absolute path to the log file :rtype: tuple
def setup_log_file_handler(config: configuration.NamespaceConfig, logfile: str, fmt: str) -> Tuple[logging.Handler, str]: """Setup file debug logging. :param certbot.configuration.NamespaceConfig config: Configuration object :param str logfile: basename for the log file :param str fmt: logging format string :returns: file handler and absolute path to the log file :rtype: tuple """ # TODO: logs might contain sensitive data such as contents of the # private key! #525 util.set_up_core_dir(config.logs_dir, 0o700, config.strict_permissions) log_file_path = os.path.join(config.logs_dir, logfile) try: handler = logging.handlers.RotatingFileHandler( log_file_path, maxBytes=2 ** 20, backupCount=config.max_log_backups) except IOError as error: raise errors.Error(util.PERM_ERR_FMT.format(error)) # rotate on each invocation, rollover only possible when maxBytes # is nonzero and backupCount is nonzero, so we set maxBytes as big # as possible not to overrun in single CLI invocation (1MB). handler.doRollover() # TODO: creates empty letsencrypt.log.1 file handler.setLevel(logging.DEBUG) handler_formatter = logging.Formatter(fmt=fmt) handler.setFormatter(handler_formatter) return handler, log_file_path
A simple wrapper around post_arg_parse_except_hook. The additional functionality provided by this wrapper is the memory handler will be flushed before Certbot exits. This allows us to write logging messages to a temporary file if we crashed before logging was fully configured. Since sys.excepthook isn't called on SystemExit exceptions, the memory handler will not be flushed in this case which prevents us from creating temporary log files when argparse exits because a command line argument was invalid or -h, --help, or --version was provided on the command line. :param MemoryHandler memory_handler: memory handler to flush :param tuple args: args for post_arg_parse_except_hook :param dict kwargs: kwargs for post_arg_parse_except_hook
def pre_arg_parse_except_hook(memory_handler: MemoryHandler, *args: Any, **kwargs: Any) -> None: """A simple wrapper around post_arg_parse_except_hook. The additional functionality provided by this wrapper is the memory handler will be flushed before Certbot exits. This allows us to write logging messages to a temporary file if we crashed before logging was fully configured. Since sys.excepthook isn't called on SystemExit exceptions, the memory handler will not be flushed in this case which prevents us from creating temporary log files when argparse exits because a command line argument was invalid or -h, --help, or --version was provided on the command line. :param MemoryHandler memory_handler: memory handler to flush :param tuple args: args for post_arg_parse_except_hook :param dict kwargs: kwargs for post_arg_parse_except_hook """ try: post_arg_parse_except_hook(*args, **kwargs) finally: # flush() is called here so messages logged during # post_arg_parse_except_hook are also flushed. memory_handler.flush(force=True)
Logs fatal exceptions and reports them to the user. If debug is True, the full exception and traceback is shown to the user, otherwise, it is suppressed. sys.exit is always called with a nonzero status. :param type exc_type: type of the raised exception :param BaseException exc_value: raised exception :param traceback trace: traceback of where the exception was raised :param bool debug: True if the traceback should be shown to the user :param bool quiet: True if Certbot is running in quiet mode :param str log_path: path to file or directory containing the log
def post_arg_parse_except_hook(exc_type: Type[BaseException], exc_value: BaseException, trace: TracebackType, debug: bool, quiet: bool, log_path: str) -> None: """Logs fatal exceptions and reports them to the user. If debug is True, the full exception and traceback is shown to the user, otherwise, it is suppressed. sys.exit is always called with a nonzero status. :param type exc_type: type of the raised exception :param BaseException exc_value: raised exception :param traceback trace: traceback of where the exception was raised :param bool debug: True if the traceback should be shown to the user :param bool quiet: True if Certbot is running in quiet mode :param str log_path: path to file or directory containing the log """ exc_info = (exc_type, exc_value, trace) # Only print human advice if not running under --quiet def exit_func() -> None: if quiet: sys.exit(1) else: exit_with_advice(log_path) # constants.QUIET_LOGGING_LEVEL or higher should be used to # display message the user, otherwise, a lower level like # logger.DEBUG should be used if debug or not issubclass(exc_type, Exception): assert constants.QUIET_LOGGING_LEVEL <= logging.ERROR if exc_type is KeyboardInterrupt: logger.error('Exiting due to user request.') sys.exit(1) logger.error('Exiting abnormally:', exc_info=exc_info) else: logger.debug('Exiting abnormally:', exc_info=exc_info) # Use logger to print the error message to take advantage of # our logger printing warnings and errors in red text. if issubclass(exc_type, errors.Error): logger.error(str(exc_value)) exit_func() logger.error('An unexpected error occurred:') if messages.is_acme_error(exc_value): logger.error(display_util.describe_acme_error(cast(messages.Error, exc_value))) else: output = traceback.format_exception_only(exc_type, exc_value) # format_exception_only returns a list of strings each # terminated by a newline. We combine them into one string # and remove the final newline before passing it to # logger.error. logger.error(''.join(output).rstrip()) exit_func()
Print a link to the community forums, the debug log path, and exit The message is printed to stderr and the program will exit with a nonzero status. :param str log_path: path to file or directory containing the log
def exit_with_advice(log_path: str) -> None: """Print a link to the community forums, the debug log path, and exit The message is printed to stderr and the program will exit with a nonzero status. :param str log_path: path to file or directory containing the log """ msg = ("Ask for help or search for solutions at https://community.letsencrypt.org. " "See the ") if os.path.isdir(log_path): msg += f'logfiles in {log_path} ' else: msg += f"logfile {log_path} " msg += 'or re-run Certbot with -v for more details.' sys.exit(msg)
Potentially suggest a donation to support Certbot. :param config: Configuration object :type config: configuration.NamespaceConfig :returns: `None` :rtype: None
def _suggest_donation_if_appropriate(config: configuration.NamespaceConfig) -> None: """Potentially suggest a donation to support Certbot. :param config: Configuration object :type config: configuration.NamespaceConfig :returns: `None` :rtype: None """ # don't prompt for donation if: # - renewing # - using the staging server (--staging or --dry-run) # - running with --quiet (display fd won't be available during atexit calls #8995) assert config.verb != "renew" if config.staging or config.quiet: return util.atexit_register( display_util.notification, "If you like Certbot, please consider supporting our work by:\n" " * Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate\n" " * Donating to EFF: https://eff.org/donate-le", pause=False )
Authenticate and enroll certificate. This method finds the relevant lineage, figures out what to do with it, then performs that action. Includes calls to hooks, various reports, checks, and requests for user input. :param config: Configuration object :type config: configuration.NamespaceConfig :param domains: List of domain names to get a certificate. Defaults to `None` :type domains: `list` of `str` :param certname: Name of new certificate. Defaults to `None` :type certname: str :param lineage: Certificate lineage object. Defaults to `None` :type lineage: storage.RenewableCert :returns: the issued certificate or `None` if doing a dry run :rtype: storage.RenewableCert or None :raises errors.Error: if certificate could not be obtained
def _get_and_save_cert(le_client: client.Client, config: configuration.NamespaceConfig, domains: Optional[List[str]] = None, certname: Optional[str] = None, lineage: Optional[storage.RenewableCert] = None ) -> Optional[storage.RenewableCert]: """Authenticate and enroll certificate. This method finds the relevant lineage, figures out what to do with it, then performs that action. Includes calls to hooks, various reports, checks, and requests for user input. :param config: Configuration object :type config: configuration.NamespaceConfig :param domains: List of domain names to get a certificate. Defaults to `None` :type domains: `list` of `str` :param certname: Name of new certificate. Defaults to `None` :type certname: str :param lineage: Certificate lineage object. Defaults to `None` :type lineage: storage.RenewableCert :returns: the issued certificate or `None` if doing a dry run :rtype: storage.RenewableCert or None :raises errors.Error: if certificate could not be obtained """ hooks.pre_hook(config) renewed_domains: List[str] = [] try: if lineage is not None: # Renewal, where we already know the specific lineage we're # interested in display_util.notify( "{action} for {domains}".format( action="Simulating renewal of an existing certificate" if config.dry_run else "Renewing an existing certificate", domains=internal_display_util.summarize_domain_list(domains or lineage.names()) ) ) renewal.renew_cert(config, domains, le_client, lineage) else: # TREAT AS NEW REQUEST if domains is None: raise errors.Error("Domain list cannot be none if the lineage is not set.") 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(domains) ) ) lineage = le_client.obtain_and_enroll_certificate(domains, certname) if lineage is False: raise errors.Error("Certificate could not be obtained") if lineage is not None: hooks.deploy_hook(config, lineage.names(), lineage.live_dir) renewed_domains.extend(domains) finally: hooks.post_hook(config, renewed_domains) return lineage
This function ensures that the user will not implicitly migrate an existing key from one type to another in the situation where a certificate for that lineage already exist and they have not provided explicitly --key-type and --cert-name. :param config: Current configuration provided by the client :param cert: Matching certificate that could be renewed :returns: Whether a key type migration is going ahead. :rtype: `bool`
def _handle_unexpected_key_type_migration(config: configuration.NamespaceConfig, cert: storage.RenewableCert) -> bool: """ This function ensures that the user will not implicitly migrate an existing key from one type to another in the situation where a certificate for that lineage already exist and they have not provided explicitly --key-type and --cert-name. :param config: Current configuration provided by the client :param cert: Matching certificate that could be renewed :returns: Whether a key type migration is going ahead. :rtype: `bool` """ new_key_type = config.key_type.upper() cur_key_type = cert.private_key_type.upper() if new_key_type == cur_key_type: return False # If both --key-type and --cert-name are provided, we consider the user's intent to # be unambiguous: to change the key type of this lineage. is_confirmed_via_cli = config.set_by_user("key_type") and config.set_by_user("certname") # Failing that, we interactively prompt the user to confirm the change. if is_confirmed_via_cli or display_util.yesno( f'An {cur_key_type} certificate named {cert.lineagename} already exists. Do you want to ' f'update its key type to {new_key_type}?', yes_label='Update key type', no_label='Keep existing key type', default=False, force_interactive=False, ): return True # If --key-type was set on the CLI but the user did not confirm the key type change using # one of the two above methods, their intent is ambiguous. Error out. if config.set_by_user("key_type"): raise errors.Error( 'Are you trying to change the key type of the certificate named ' f'{cert.lineagename} from {cur_key_type} to {new_key_type}? Please provide ' 'both --cert-name and --key-type on the command line to confirm the change ' 'you are trying to make.' ) # The mismatch between the lineage's key type and config.key_type is caused by Certbot's # default value. The user is not asking for a key change: keep the key type of the existing # lineage. config.key_type = cur_key_type.lower() return False
Figure out what to do if a previous cert had a subset of the names now requested :param config: Configuration object :type config: configuration.NamespaceConfig :param domains: List of domain names :type domains: `list` of `str` :param cert: Certificate object :type cert: storage.RenewableCert :returns: Tuple of (str action, cert_or_None) as per _find_lineage_for_domains_and_certname action can be: "newcert" | "renew" | "reinstall" :rtype: `tuple` of `str`
def _handle_subset_cert_request(config: configuration.NamespaceConfig, domains: Iterable[str], cert: storage.RenewableCert ) -> Tuple[str, Optional[storage.RenewableCert]]: """Figure out what to do if a previous cert had a subset of the names now requested :param config: Configuration object :type config: configuration.NamespaceConfig :param domains: List of domain names :type domains: `list` of `str` :param cert: Certificate object :type cert: storage.RenewableCert :returns: Tuple of (str action, cert_or_None) as per _find_lineage_for_domains_and_certname action can be: "newcert" | "renew" | "reinstall" :rtype: `tuple` of `str` """ _handle_unexpected_key_type_migration(config, cert) existing = ", ".join(cert.names()) question = ( "You have an existing certificate that contains a portion of " "the domains you requested (ref: {0}){br}{br}It contains these " "names: {1}{br}{br}You requested these names for the new " "certificate: {2}.{br}{br}Do you want to expand and replace this existing " "certificate with the new certificate?" ).format(cert.configfile.filename, existing, ", ".join(domains), br=os.linesep) if config.expand or config.renew_by_default or display_util.yesno( question, "Expand", "Cancel", cli_flag="--expand", force_interactive=True): return "renew", cert display_util.notify( "To obtain a new certificate that contains these names without " "replacing your existing certificate for {0}, you must use the " "--duplicate option.{br}{br}" "For example:{br}{br}{1} --duplicate {2}".format( existing, cli.cli_command, " ".join(sys.argv[1:]), br=os.linesep )) raise errors.Error(USER_CANCELLED)
Figure out what to do if a lineage has the same names as a previously obtained one :param config: Configuration object :type config: configuration.NamespaceConfig :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :returns: Tuple of (str action, cert_or_None) as per _find_lineage_for_domains_and_certname action can be: "newcert" | "renew" | "reinstall" :rtype: `tuple` of `str`
def _handle_identical_cert_request(config: configuration.NamespaceConfig, lineage: storage.RenewableCert, ) -> Tuple[str, Optional[storage.RenewableCert]]: """Figure out what to do if a lineage has the same names as a previously obtained one :param config: Configuration object :type config: configuration.NamespaceConfig :param lineage: Certificate lineage object :type lineage: storage.RenewableCert :returns: Tuple of (str action, cert_or_None) as per _find_lineage_for_domains_and_certname action can be: "newcert" | "renew" | "reinstall" :rtype: `tuple` of `str` """ is_key_type_changing = _handle_unexpected_key_type_migration(config, lineage) if not lineage.ensure_deployed(): return "reinstall", lineage if is_key_type_changing or renewal.should_renew(config, lineage): return "renew", lineage if config.reinstall: # Set with --reinstall, force an identical certificate to be # reinstalled without further prompting. return "reinstall", lineage question = ( "You have an existing certificate that has exactly the same " "domains or certificate name you requested and isn't close to expiry." "{br}(ref: {0}){br}{br}What would you like to do?" ).format(lineage.configfile.filename, br=os.linesep) if config.verb == "run": keep_opt = "Attempt to reinstall this existing certificate" elif config.verb == "certonly": keep_opt = "Keep the existing certificate for now" choices = [keep_opt, "Renew & replace the certificate (may be subject to CA rate limits)"] response = display_util.menu(question, choices, default=0, force_interactive=True) if response[0] == display_util.CANCEL: # TODO: Add notification related to command-line options for # skipping the menu for this case. raise errors.Error( "Operation canceled. You may re-run the client.") if response[1] == 0: return "reinstall", lineage elif response[1] == 1: return "renew", lineage raise AssertionError('This is impossible')
Determine whether there are duplicated names and how to handle them (renew, reinstall, newcert, or raising an error to stop the client run if the user chooses to cancel the operation when prompted). :param config: Configuration object :type config: configuration.NamespaceConfig :param domains: List of domain names :type domains: `list` of `str` :returns: Two-element tuple containing desired new-certificate behavior as a string token ("reinstall", "renew", or "newcert"), plus either a RenewableCert instance or `None` if renewal shouldn't occur. :rtype: `tuple` of `str` and :class:`storage.RenewableCert` or `None` :raises errors.Error: If the user would like to rerun the client again.
def _find_lineage_for_domains(config: configuration.NamespaceConfig, domains: List[str] ) -> Tuple[Optional[str], Optional[storage.RenewableCert]]: """Determine whether there are duplicated names and how to handle them (renew, reinstall, newcert, or raising an error to stop the client run if the user chooses to cancel the operation when prompted). :param config: Configuration object :type config: configuration.NamespaceConfig :param domains: List of domain names :type domains: `list` of `str` :returns: Two-element tuple containing desired new-certificate behavior as a string token ("reinstall", "renew", or "newcert"), plus either a RenewableCert instance or `None` if renewal shouldn't occur. :rtype: `tuple` of `str` and :class:`storage.RenewableCert` or `None` :raises errors.Error: If the user would like to rerun the client again. """ # Considering the possibility that the requested certificate is # related to an existing certificate. (config.duplicate, which # is set with --duplicate, skips all of this logic and forces any # kind of certificate to be obtained with renewal = False.) if config.duplicate: return "newcert", None # TODO: Also address superset case ident_names_cert, subset_names_cert = cert_manager.find_duplicative_certs(config, domains) # XXX ^ schoen is not sure whether that correctly reads the systemwide # configuration file. if ident_names_cert is None and subset_names_cert is None: return "newcert", None if ident_names_cert is not None: return _handle_identical_cert_request(config, ident_names_cert) elif subset_names_cert is not None: return _handle_subset_cert_request(config, domains, subset_names_cert) return None, None
Finds an existing certificate object given domains and/or a certificate name. :param config: Configuration object :type config: configuration.NamespaceConfig :param domains: List of domain names :type domains: `list` of `str` :param certname: Name of certificate :type certname: str :returns: Two-element tuple of a boolean that indicates if this function should be followed by a call to fetch a certificate from the server, and either a RenewableCert instance or None. :rtype: `tuple` of `bool` and :class:`storage.RenewableCert` or `None`
def _find_cert(config: configuration.NamespaceConfig, domains: List[str], certname: str ) -> Tuple[bool, Optional[storage.RenewableCert]]: """Finds an existing certificate object given domains and/or a certificate name. :param config: Configuration object :type config: configuration.NamespaceConfig :param domains: List of domain names :type domains: `list` of `str` :param certname: Name of certificate :type certname: str :returns: Two-element tuple of a boolean that indicates if this function should be followed by a call to fetch a certificate from the server, and either a RenewableCert instance or None. :rtype: `tuple` of `bool` and :class:`storage.RenewableCert` or `None` """ action, lineage = _find_lineage_for_domains_and_certname(config, domains, certname) if action == "reinstall": logger.info("Keeping the existing certificate") return (action != "reinstall"), lineage
Find appropriate lineage based on given domains and/or certname. :param config: Configuration object :type config: configuration.NamespaceConfig :param domains: List of domain names :type domains: `list` of `str` :param certname: Name of certificate :type certname: str :returns: Two-element tuple containing desired new-certificate behavior as a string token ("reinstall", "renew", or "newcert"), plus either a RenewableCert instance or None if renewal should not occur. :rtype: `tuple` of `str` and :class:`storage.RenewableCert` or `None` :raises errors.Error: If the user would like to rerun the client again.
def _find_lineage_for_domains_and_certname( config: configuration.NamespaceConfig, domains: List[str], certname: str) -> Tuple[Optional[str], Optional[storage.RenewableCert]]: """Find appropriate lineage based on given domains and/or certname. :param config: Configuration object :type config: configuration.NamespaceConfig :param domains: List of domain names :type domains: `list` of `str` :param certname: Name of certificate :type certname: str :returns: Two-element tuple containing desired new-certificate behavior as a string token ("reinstall", "renew", or "newcert"), plus either a RenewableCert instance or None if renewal should not occur. :rtype: `tuple` of `str` and :class:`storage.RenewableCert` or `None` :raises errors.Error: If the user would like to rerun the client again. """ if not certname: return _find_lineage_for_domains(config, domains) lineage = cert_manager.lineage_for_certname(config, certname) if lineage: if domains: computed_domains = cert_manager.domains_for_certname(config, certname) if computed_domains and set(computed_domains) != set(domains): _handle_unexpected_key_type_migration(config, lineage) _ask_user_to_confirm_new_names(config, domains, certname, lineage.names()) # raises if no return "renew", lineage # unnecessarily specified domains or no domains specified return _handle_identical_cert_request(config, lineage) elif domains: return "newcert", None raise errors.ConfigurationError("No certificate with name {0} found. " "Use -d to specify domains, or run certbot certificates to see " "possible certificate names.".format(certname))
Get lists of items removed from `before` and a lists of items added to `after`
def _get_added_removed(after: Iterable[T], before: Iterable[T]) -> Tuple[List[T], List[T]]: """Get lists of items removed from `before` and a lists of items added to `after` """ added = list(set(after) - set(before)) removed = list(set(before) - set(after)) added.sort() removed.sort() return added, removed
Format list with given character
def _format_list(character: str, strings: Iterable[str]) -> str: """Format list with given character """ if not strings: formatted = "{br}(None)" else: formatted = "{br}{ch} " + "{br}{ch} ".join(strings) return formatted.format( ch=character, br=os.linesep )
Ask user to confirm update cert certname to contain new_domains. :param config: Configuration object :type config: configuration.NamespaceConfig :param new_domains: List of new domain names :type new_domains: `list` of `str` :param certname: Name of certificate :type certname: str :param old_domains: List of old domain names :type old_domains: `list` of `str` :returns: None :rtype: None :raises errors.ConfigurationError: if cert name and domains mismatch
def _ask_user_to_confirm_new_names(config: configuration.NamespaceConfig, new_domains: Iterable[str], certname: str, old_domains: Iterable[str]) -> None: """Ask user to confirm update cert certname to contain new_domains. :param config: Configuration object :type config: configuration.NamespaceConfig :param new_domains: List of new domain names :type new_domains: `list` of `str` :param certname: Name of certificate :type certname: str :param old_domains: List of old domain names :type old_domains: `list` of `str` :returns: None :rtype: None :raises errors.ConfigurationError: if cert name and domains mismatch """ if config.renew_with_new_domains: return added, removed = _get_added_removed(new_domains, old_domains) msg = ("You are updating certificate {0} to include new domain(s): {1}{br}{br}" "You are also removing previously included domain(s): {2}{br}{br}" "Did you intend to make this change?".format( certname, _format_list("+", added), _format_list("-", removed), br=os.linesep)) if not display_util.yesno(msg, "Update certificate", "Cancel", default=True): raise errors.ConfigurationError("Specified mismatched certificate name and domains.")
Retrieve domains and certname from config or user input. :param config: Configuration object :type config: configuration.NamespaceConfig :param installer: Installer object :type installer: interfaces.Installer :param `str` question: Overriding default question to ask the user if asked to choose from domain names. :returns: Two-part tuple of domains and certname :rtype: `tuple` of list of `str` and `str` :raises errors.Error: Usage message, if parameters are not used correctly
def _find_domains_or_certname(config: configuration.NamespaceConfig, installer: Optional[interfaces.Installer], question: Optional[str] = None) -> Tuple[List[str], str]: """Retrieve domains and certname from config or user input. :param config: Configuration object :type config: configuration.NamespaceConfig :param installer: Installer object :type installer: interfaces.Installer :param `str` question: Overriding default question to ask the user if asked to choose from domain names. :returns: Two-part tuple of domains and certname :rtype: `tuple` of list of `str` and `str` :raises errors.Error: Usage message, if parameters are not used correctly """ domains = None certname = config.certname # first, try to get domains from the config if config.domains: domains = config.domains # if we can't do that but we have a certname, get the domains # with that certname elif certname: domains = cert_manager.domains_for_certname(config, certname) # that certname might not have existed, or there was a problem. # try to get domains from the user. if not domains: domains = display_ops.choose_names(installer, question) if not domains and not certname: raise errors.Error("Please specify --domains, or --installer that " "will help in domain names autodiscovery, or " "--cert-name for an existing certificate name.") return domains, certname
Displays post-run/certonly advice to the user about renewal and installation. The output varies by runtime configuration and any errors encountered during installation. :param config: Configuration object :type config: configuration.NamespaceConfig :param installer_err: The installer/enhancement error encountered, if any. :type error: Optional[errors.Error] :param lineage: The resulting certificate lineage from the issuance, if any. :type lineage: Optional[storage.RenewableCert] :param bool new_or_renewed_cert: Whether the verb execution resulted in a certificate being saved (created or renewed).
def _report_next_steps(config: configuration.NamespaceConfig, installer_err: Optional[errors.Error], lineage: Optional[storage.RenewableCert], new_or_renewed_cert: bool = True) -> None: """Displays post-run/certonly advice to the user about renewal and installation. The output varies by runtime configuration and any errors encountered during installation. :param config: Configuration object :type config: configuration.NamespaceConfig :param installer_err: The installer/enhancement error encountered, if any. :type error: Optional[errors.Error] :param lineage: The resulting certificate lineage from the issuance, if any. :type lineage: Optional[storage.RenewableCert] :param bool new_or_renewed_cert: Whether the verb execution resulted in a certificate being saved (created or renewed). """ steps: List[str] = [] # If the installation or enhancement raised an error, show advice on trying again if installer_err: # Special case where either --nginx or --apache were used, causing us to # run the "installer" (i.e. reloading the nginx/apache config) if config.verb == 'certonly': steps.append( "The certificate was saved, but was not successfully loaded by the installer " f"({config.installer}) due to the installer failing to reload. " f"After fixing the error shown below, try reloading {config.installer} manually." ) else: steps.append( "The certificate was saved, but could not be installed (installer: " f"{config.installer}). After fixing the error shown below, try installing it again " f"by running:\n {cli.cli_command} install --cert-name " f"{_cert_name_from_config_or_lineage(config, lineage)}" ) # If a certificate was obtained or renewed, show applicable renewal advice if new_or_renewed_cert: if config.csr: steps.append( "Certificates created using --csr will not be renewed automatically by Certbot. " "You will need to renew the certificate before it expires, by running the same " "Certbot command again.") elif _is_interactive_only_auth(config): steps.append( "This certificate will not be renewed automatically. Autorenewal of " "--manual certificates requires the use of an authentication hook script " "(--manual-auth-hook) but one was not provided. To renew this certificate, repeat " f"this same {cli.cli_command} command before the certificate's expiry date." ) elif not config.preconfigured_renewal: steps.append( "The certificate will need to be renewed before it expires. Certbot can " "automatically renew the certificate in the background, but you may need " "to take steps to enable that functionality. " "See https://certbot.org/renewal-setup for instructions.") if not steps: return # TODO: refactor ANSI escapes during https://github.com/certbot/certbot/issues/8848 (bold_on, nl, bold_off) = [c if sys.stdout.isatty() and not config.quiet else '' \ for c in (util.ANSI_SGR_BOLD, '\n', util.ANSI_SGR_RESET)] print(bold_on, end=nl) display_util.notify("NEXT STEPS:") print(bold_off, end='') for step in steps: display_util.notify(f"- {step}") # If there was an installer error, segregate the error output with a trailing newline if installer_err: print()
Reports the creation of a new certificate to the user. :param config: Configuration object :type config: configuration.NamespaceConfig :param cert_path: path to certificate :type cert_path: str :param fullchain_path: path to full chain :type fullchain_path: str :param key_path: path to private key, if available :type key_path: str :returns: `None` :rtype: None
def _report_new_cert(config: configuration.NamespaceConfig, cert_path: Optional[str], fullchain_path: Optional[str], key_path: Optional[str] = None) -> None: """Reports the creation of a new certificate to the user. :param config: Configuration object :type config: configuration.NamespaceConfig :param cert_path: path to certificate :type cert_path: str :param fullchain_path: path to full chain :type fullchain_path: str :param key_path: path to private key, if available :type key_path: str :returns: `None` :rtype: None """ if config.dry_run: display_util.notify("The dry run was successful.") return assert cert_path and fullchain_path, "No certificates saved to report." renewal_msg = "" if config.preconfigured_renewal and not _is_interactive_only_auth(config): renewal_msg = ("\nCertbot has set up a scheduled task to automatically renew this " "certificate in the background.") display_util.notify( ("\nSuccessfully received certificate.\n" "Certificate is saved at: {cert_path}\n{key_msg}" "This certificate expires on {expiry}.\n" "These files will be updated when the certificate renews.{renewal_msg}{nl}").format( cert_path=fullchain_path, expiry=crypto_util.notAfter(cert_path).date(), key_msg="Key is saved at: {}\n".format(key_path) if key_path else "", renewal_msg=renewal_msg, nl="\n" if config.verb == "run" else "" # Normalize spacing across verbs ) )
Whether the current authenticator params only support interactive renewal.
def _is_interactive_only_auth(config: configuration.NamespaceConfig) -> bool: """ Whether the current authenticator params only support interactive renewal. """ # --manual without --manual-auth-hook can never autorenew if config.authenticator == "manual" and config.manual_auth_hook is None: return True return False
--csr variant of _report_new_cert. Until --csr is overhauled (#8332) this is transitional function to report the creation of a new certificate using --csr. TODO: remove this function and just call _report_new_cert when --csr is overhauled. :param config: Configuration object :type config: configuration.NamespaceConfig :param str cert_path: path to cert.pem :param str chain_path: path to chain.pem :param str fullchain_path: path to fullchain.pem
def _csr_report_new_cert(config: configuration.NamespaceConfig, cert_path: Optional[str], chain_path: Optional[str], fullchain_path: Optional[str]) -> None: """ --csr variant of _report_new_cert. Until --csr is overhauled (#8332) this is transitional function to report the creation of a new certificate using --csr. TODO: remove this function and just call _report_new_cert when --csr is overhauled. :param config: Configuration object :type config: configuration.NamespaceConfig :param str cert_path: path to cert.pem :param str chain_path: path to chain.pem :param str fullchain_path: path to fullchain.pem """ if config.dry_run: display_util.notify("The dry run was successful.") return assert cert_path and fullchain_path, "No certificates saved to report." expiry = crypto_util.notAfter(cert_path).date() display_util.notify( ("\nSuccessfully received certificate.\n" "Certificate is saved at: {cert_path}\n" "Intermediate CA chain is saved at: {chain_path}\n" "Full certificate chain is saved at: {fullchain_path}\n" "This certificate expires on {expiry}.").format( cert_path=cert_path, chain_path=chain_path, fullchain_path=fullchain_path, expiry=expiry, ) )
Determine which account to use. If ``config.account`` is ``None``, it will be updated based on the user input. Same for ``config.email``. :param config: Configuration object :type config: configuration.NamespaceConfig :returns: Account and optionally ACME client API (biproduct of new registration). :rtype: tuple of :class:`certbot._internal.account.Account` and :class:`acme.client.Client` :raises errors.Error: If unable to register an account with ACME server
def _determine_account(config: configuration.NamespaceConfig ) -> Tuple[account.Account, Optional[acme_client.ClientV2]]: """Determine which account to use. If ``config.account`` is ``None``, it will be updated based on the user input. Same for ``config.email``. :param config: Configuration object :type config: configuration.NamespaceConfig :returns: Account and optionally ACME client API (biproduct of new registration). :rtype: tuple of :class:`certbot._internal.account.Account` and :class:`acme.client.Client` :raises errors.Error: If unable to register an account with ACME server """ def _tos_cb(terms_of_service: str) -> None: if config.tos: return msg = ("Please read the Terms of Service at {0}. You " "must agree in order to register with the ACME " "server. Do you agree?".format(terms_of_service)) result = display_util.yesno(msg, cli_flag="--agree-tos", force_interactive=True) if not result: raise errors.Error( "Registration cannot proceed without accepting " "Terms of Service.") account_storage = account.AccountFileStorage(config) acme: Optional[acme_client.ClientV2] = None if config.account is not None: acc = account_storage.load(config.account) else: accounts = account_storage.find_all() if len(accounts) > 1: potential_acc = display_ops.choose_account(accounts) if not potential_acc: raise errors.Error("No account has been chosen.") acc = potential_acc elif len(accounts) == 1: acc = accounts[0] else: # no account registered yet if config.email is None and not config.register_unsafely_without_email: config.email = display_ops.get_email() try: acc, acme = client.register( config, account_storage, tos_cb=_tos_cb) display_util.notify("Account registered.") except errors.MissingCommandlineFlag: raise except (errors.Error, acme_messages.Error) as err: logger.debug("", exc_info=True) if acme_messages.is_acme_error(err): err_msg = internal_display_util.describe_acme_error( cast(acme_messages.Error, err)) err_msg = f"Error returned by the ACME server: {err_msg}" else: err_msg = str(err) raise errors.Error( f"Unable to register an account with ACME server. {err_msg}") config.account = acc.id return acc, acme
Does the user want to delete their now-revoked certs? If run in non-interactive mode, deleting happens automatically. :param config: parsed command line arguments :type config: configuration.NamespaceConfig :returns: `None` :rtype: None :raises errors.Error: If anything goes wrong, including bad user input, if an overlapping archive dir is found for the specified lineage, etc ...
def _delete_if_appropriate(config: configuration.NamespaceConfig) -> None: """Does the user want to delete their now-revoked certs? If run in non-interactive mode, deleting happens automatically. :param config: parsed command line arguments :type config: configuration.NamespaceConfig :returns: `None` :rtype: None :raises errors.Error: If anything goes wrong, including bad user input, if an overlapping archive dir is found for the specified lineage, etc ... """ attempt_deletion = config.delete_after_revoke if attempt_deletion is None: msg = ("Would you like to delete the certificate(s) you just revoked, " "along with all earlier and later versions of the certificate?") attempt_deletion = display_util.yesno(msg, yes_label="Yes (recommended)", no_label="No", force_interactive=True, default=True) if not attempt_deletion: return # config.cert_path must have been set # config.certname may have been set assert config.cert_path if not config.certname: config.certname = cert_manager.cert_path_to_lineage(config) # don't delete if the archive_dir is used by some other lineage archive_dir = storage.full_archive_path( configobj.ConfigObj( storage.renewal_file_for_certname(config, config.certname), encoding='utf-8', default_encoding='utf-8'), config, config.certname) try: cert_manager.match_and_check_overlaps(config, [lambda x: archive_dir], lambda x: x.archive_dir, lambda x: x.lineagename) except errors.OverlappingMatchFound: logger.warning("Not deleting revoked certificates due to overlapping archive dirs. " "More than one certificate is using %s", archive_dir) return except Exception as e: msg = ('config.default_archive_dir: {0}, config.live_dir: {1}, archive_dir: {2},' 'original exception: {3}') msg = msg.format(config.default_archive_dir, config.live_dir, archive_dir, e) raise errors.Error(msg) cert_manager.delete(config)
Initialize Let's Encrypt Client :param config: Configuration object :type config: configuration.NamespaceConfig :param authenticator: Acme authentication handler :type authenticator: Optional[interfaces.Authenticator] :param installer: Installer object :type installer: interfaces.Installer :returns: client: Client object :rtype: client.Client
def _init_le_client(config: configuration.NamespaceConfig, authenticator: Optional[interfaces.Authenticator], installer: Optional[interfaces.Installer]) -> client.Client: """Initialize Let's Encrypt Client :param config: Configuration object :type config: configuration.NamespaceConfig :param authenticator: Acme authentication handler :type authenticator: Optional[interfaces.Authenticator] :param installer: Installer object :type installer: interfaces.Installer :returns: client: Client object :rtype: client.Client """ acc: Optional[account.Account] if authenticator is not None: # if authenticator was given, then we will need account... acc, acme = _determine_account(config) logger.debug("Picked account: %r", acc) else: acc, acme = None, None return client.Client(config, acc, authenticator, installer, acme=acme)