neulab/tldr huggingface dataset:
certbot.compat.os.waitpid(pid, options, /) Wait for completion of a given child process.
Returns a tuple of information regarding the child process: (pid, status)
The options argument is ignored on Windows.
certbot.compat.os.write(fd, data, /) Write a bytes object to a file descriptor.
certbot.compat.os.writev(fd, buffers, /) Iterate over buffers, and write the contents of each to a file descriptor.
Returns the total number of bytes written.  buffers must be a sequence of bytes-like objects.
certbot.compat.os.makedirs(*unused_args, **unused_kwargs) Method os.makedirs() is forbidden
certbot.compat.os.removedirs(name) Super-rmdir; remove a leaf directory and all empty intermediate ones.  Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments will be pruned away until either the whole path is consumed or an error occurs.  Errors during this latter phase are ignored -- they generally mean that a directory was not empty.
certbot.compat.os.renames(old, new) Super-rename; create directories as necessary and delete any left empty.  Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first.  After the rename, directories corresponding to rightmost path segments of the old name will be pruned until either the whole path is consumed or a nonempty directory is found.
Note: this function can fail with the new directory structure made if you lack permissions needed to unlink the leaf directory or file.
certbot.compat.os.walk(top, topdown=True, onerror=None, followlinks=False) Directory tree generator.
For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames
dirpath is a string, the path to the directory.  dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..').  filenames is a list of the names of the non-directory files in dirpath.  Note that the names in the lists are just names, with no path components.  To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).
If optional arg 'topdown' is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down).  If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up).
When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting.  Modifying dirnames when topdown is false has no effect on the behavior of os.walk(), since the directories in dirnames have already been generated by the time dirnames itself is generated. No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.
By default errors from the os.scandir() call are ignored.  If optional arg 'onerror' is specified, it should be a function; it will be called with one argument, an OSError instance.  It can report the error to continue with the walk, or raise the exception to abort the walk.  Note that the filename is available as the filename attribute of the exception object.
By default, os.walk does not follow symbolic links to subdirectories on systems that support them.  In order to get this functionality, set the optional argument 'followlinks' to true.
Caution:  if you pass a relative pathname for top, don't change the current working directory between resumptions of walk.  walk never changes the current directory, and assumes that the client doesn't either.
import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print(root, "consumes", end="") print(sum([getsize(join(root, name)) for name in files]), end="") print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS')  # don't visit CVS directories
certbot.compat.os.fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None) Directory tree generator.
This behaves exactly like walk(), except that it yields a 4-tuple dirpath, dirnames, filenames, dirfd
dirpath, dirnames and filenames are identical to walk() output, and dirfd is a file descriptor referring to the directory dirpath.
The advantage of fwalk() over walk() is that it's safe against symlink races (when follow_symlinks is False).
If dir_fd is not None, it should be a file descriptor open to a directory, and top should be relative; top will then be relative to that directory.  (dir_fd is always supported for fwalk.)
Caution: Since fwalk() yields file descriptors, those are only valid until the next iteration step, so you should dup() them if you want to keep them for a longer period.
import os for root, dirs, files, rootfd in os.fwalk('python/Lib/email'): print(root, "consumes", end="") print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]), end="")
print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS')  # don't visit CVS directories
certbot.compat.os.execl(file, *args) Execute the executable file with argument list args, replacing the current process.
certbot.compat.os.execle(file, *args, env) Execute the executable file with argument list args and environment env, replacing the current process.
certbot.compat.os.execlp(file, *args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process.
certbot.compat.os.execlpe(file, *args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process.
certbot.compat.os.execvp(file, args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process.  args may be a list or tuple of strings.
certbot.compat.os.execvpe(file, args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process.  args may be a list or tuple of strings.
certbot.compat.os.getenv(key, default=None) Get an environment variable, return None if it doesn't exist.  The optional second argument can specify an alternate default.  key, default and the result are str.
certbot.compat.os.getenvb(key, default=None) Get an environment variable, return None if it doesn't exist.  The optional second argument can specify an alternate default.  key, default and the result are bytes.
certbot.compat.os.spawnv(mode, file, args) -> integer Execute file with arguments from args in a subprocess.  If mode == P_NOWAIT return the pid of the process.  If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
certbot.compat.os.spawnve(mode, file, args, env) -> integer Execute file with arguments from args in a subprocess with the specified environment.  If mode == P_NOWAIT return the pid of the process.  If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
certbot.compat.os.spawnvp(mode, file, args) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess.  If mode == P_NOWAIT return the pid of the process.  If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
certbot.compat.os.spawnvpe(mode, file, args, env) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment.  If mode == P_NOWAIT return the pid of the process.  If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
certbot.compat.os.spawnl(mode, file, *args) -> integer Execute file with arguments from args in a subprocess.  If mode == P_NOWAIT return the pid of the process.  If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
certbot.compat.os.spawnle(mode, file, *args, env) -> integer Execute file with arguments from args in a subprocess with the supplied environment.  If mode == P_NOWAIT return the pid of the process.  If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
certbot.compat.os.spawnlp(mode, file, *args) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment.  If mode == P_NOWAIT return the pid of the process.  If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
certbot.compat.os.spawnlpe(mode, file, *args, env) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment.  If mode == P_NOWAIT return the pid of the process.  If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
certbot.display package Certbot display utilities.
Submodules certbot.display.ops module Contains UI methods for LE user operations.
certbot.display.ops.get_email(invalid=False, optional=True) Prompt for valid email address.
• invalid (bool) -- True if an invalid address was provided by the user
• optional (bool) -- True if the user can use --register-unsafely-without-email to avoid providing an e-mail
Returns e-mail address
Raises errors.Error -- if the user cancels
certbot.display.ops.choose_account(accounts) Choose an account.
Parameters accounts (list) -- Containing at least one Account
certbot.display.ops.choose_values(values, question=None) Display screen to let user pick one or multiple values from the provided list.
Parameters values (list) -- Values to select from
Returns List of selected values
Return type list
certbot.display.ops.choose_names(installer, question=None) Display screen to select domains to validate.
• installer (certbot.interfaces.IInstaller) -- An installer object
• question (str) -- Overriding default question to ask the user if asked to choose from domain names.
Returns List of selected names
Return type list of str
certbot.display.ops.get_valid_domains(domains)
Helper method for choose_names that implements basic checks on domain names
Parameters domains (list) -- Domain names to validate
Returns List of valid domains
certbot.display.ops.success_installation(domains) Display a box confirming the installation of HTTPS.
Parameters domains (list) -- domain names which were enabled
certbot.display.ops.success_renewal(domains) Display a box confirming the renewal of an existing certificate.
Parameters domains (list) -- domain names which were renewed
certbot.display.ops.success_revocation(cert_path) Display a message confirming a certificate has been revoked.
Parameters cert_path (list) -- path to certificate which was revoked.
certbot.display.ops.validated_input(validator, *args, **kwargs) Like input, but with validation.
• validator (callable) -- A method which will be called on the supplied input. If the method raises an errors.Error, its text will be displayed and the user will be re-prompted.
• *args (list) -- Arguments to be passed to input.
• **kwargs (dict) -- Arguments to be passed to input.
Returns as input
Return type tuple
certbot.display.ops.validated_directory(validator, *args, **kwargs) Like directory_select, but with validation.
• *args (list) -- Arguments to be passed to directory_select.
• **kwargs (dict) -- Arguments to be passed to directory_select.
Returns as directory_select
certbot.display.util module Certbot display.
This module (certbot.display.util) or its companion certbot.display.ops should be used whenever:
• Displaying status information to the user on the terminal
• Collecting information from the user via prompts
Other messages can use the logging module. See log.py.
certbot.display.util.OK = 'ok' Display exit code indicating user acceptance.
certbot.display.util.CANCEL = 'cancel' Display exit code for a user canceling the display.
certbot.display.util.HELP = 'help' Display exit code when for when the user requests more help. (UNUSED)
certbot.display.util.ESC = 'esc' Display exit code when the user hits Escape (UNUSED)
certbot.display.util.SIDE_FRAME = '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -' Display boundary (alternates spaces, so when copy-pasted, markdown doesn't interpret it as a heading)
certbot.display.util.input_with_timeout(prompt=None, timeout=36000.0) Get user input with a timeout.
Behaves the same as six.moves.input, however, an error is raised if a user doesn't answer after timeout seconds. The default timeout value was chosen to place it just under 12 hours for users following our advice and running Certbot twice a day.
• prompt (str) -- prompt to provide for input
• timeout (float) -- maximum number of seconds to wait for input
Returns user response
:raises errors.Error if no answer is given before the timeout
certbot.display.util.notify(msg) Display a basic status message.
Parameters msg (str) -- message to display
class certbot.display.util.FileDisplay(outfile, force_interactive) Bases: object
File-based display.
notification(message, pause=True, wrap=True, force_interactive=False, decorate=True) Displays a notification and waits for user acceptance.
• message (str) -- Message to display
• pause (bool) -- Whether or not the program should pause for the user's confirmation
• wrap (bool) -- Whether or not the application should wrap text
• force_interactive (bool) -- True if it's safe to prompt the user because it won't cause any workflow regressions
• decorate (bool) -- Whether to surround the message with a decorated frame
menu(message, choices, ok_label=None, cancel_label=None, help_label=None, default=None, cli_flag=None, force_interactive=False, **unused_kwargs) Display a menu.
• message (str) -- title of menu
• choices (list of tuples (tag, item) or list of descriptions (tags will be enumerated)) -- Menu lines, len must be > 0
• default -- default value to return (if one exists)
• cli_flag (str) -- option used to set this value with the CLI
Returns tuple of (code, index) where code - str display exit code index - int index of the user's selection
input(message, default=None, cli_flag=None, force_interactive=False, **unused_kwargs) Accept input from the user.
• message (str) -- message to display to the user
Returns tuple of (code, input) where code - str display exit code input - str of the user's input
yesno(message, yes_label='Yes', no_label='No', default=None, cli_flag=None, force_interactive=False, **unused_kwargs) Query the user with a yes/no question.
Yes and No label must begin with different letters, and must contain at least one letter each.
• message (str) -- question for the user
• yes_label (str) -- Label of the "Yes" parameter
• no_label (str) -- Label of the "No" parameter
Returns True for "Yes", False for "No"
checklist(message, tags, default=None, cli_flag=None, force_interactive=False, **unused_kwargs) Display a checklist.
• message (str) -- Message to display to user
• tags (list) -- str tags to select, len(tags) > 0
Returns tuple of (code, tags) where code - str display exit code tags - list of selected tags
directory_select(message, default=None, cli_flag=None, force_interactive=False, **unused_kwargs) Display a directory selection screen.
• message (str) -- prompt to give the user
Returns tuple of the form (code, string) where code - display exit code string - input entered by the user
certbot.display.util.assert_valid_call(prompt, default, cli_flag, force_interactive) Verify that provided arguments is a valid IDisplay call.
• prompt (str) -- prompt for the user
• default -- default answer to prompt
• cli_flag (str) -- command line option for setting an answer to this question
• force_interactive (bool) -- if interactivity is forced by the IDisplay call
class certbot.display.util.NoninteractiveDisplay(outfile, *unused_args, **unused_kwargs) Bases: object
An iDisplay implementation that never asks for interactive user input
notification(message, pause=False, wrap=True, decorate=True, **unused_kwargs) Displays a notification without waiting for user acceptance.
• message (str) -- Message to display to stdout
• pause (bool) -- The NoninteractiveDisplay waits for no keyboard
• decorate (bool) -- Whether to apply a decorated frame to the message
menu(message, choices, ok_label=None, cancel_label=None, help_label=None, default=None, cli_flag=None, **unused_kwargs) Avoid displaying a menu.
• default (int) -- the default choice
• kwargs (dict) -- absorbs various irrelevant labelling arguments
Raises errors.MissingCommandlineFlag -- if there was no default
input(message, default=None, cli_flag=None, **unused_kwargs) Accept input from the user.
Parameters message (str) -- message to display to the user
yesno(message, yes_label=None, no_label=None, default=None, cli_flag=None, **unused_kwargs) Decide Yes or No, without asking anybody
• kwargs (dict) -- absorbs yes_label, no_label
checklist(message, tags, default=None, cli_flag=None, **unused_kwargs) Display a checklist.
• kwargs (dict) -- absorbs default_status arg
directory_select(message, default=None, cli_flag=None, **unused_kwargs) Simulate prompting the user for a directory.
This function returns default if it is not None, otherwise, an exception is raised explaining the problem. If cli_flag is not None, the error message will include the flag that can be used to set this value with the CLI.
Returns tuple of the form (code, string) where code - int display exit code string - input entered by the user
certbot.display.util.separate_list_input(input_) Separate a comma or space separated list.
Parameters input (str) -- input from the user
Returns strings
certbot.display.util.summarize_domain_list(domains)
Summarizes a list of domains in the format of: example.com.com and N more domains
or if there is are only two domains: example.com and www.example.com
or if there is only one domain: example.com
Parameters domains (list) -- str list of domains
Returns the domain list summary
certbot.plugins package Certbot plugins.
Submodules certbot.plugins.common module Plugin common functions.
certbot.plugins.common.option_namespace(name) ArgumentParser options namespace (prefix of all options).
certbot.plugins.common.dest_namespace(name) ArgumentParser dest namespace (prefix of all destinations).
class certbot.plugins.common.Plugin(config, name) Bases: object
Generic plugin.
abstract classmethod add_parser_arguments(add) Add plugin arguments to the CLI argument parser.
Parameters add (callable) -- Function that proxies calls to argparse.ArgumentParser.add_argument prepending options with unique plugin name prefix.
classmethod inject_parser_options(parser, name) Inject parser options.
See inject_parser_options for docs.
property option_namespace ArgumentParser options namespace (prefix of all options).
option_name(name) Option name (include plugin namespace).
property dest_namespace ArgumentParser dest namespace (prefix of all destinations).
dest(var) Find a destination for given variable var.
conf(var) Find a configuration value for variable var.
class certbot.plugins.common.Installer(*args, **kwargs) Bases: certbot.plugins.common.Plugin
An installer base class with reverter and ssl_dhparam methods defined.
Installer plugins do not have to inherit from this class.
add_to_checkpoint(save_files, save_notes, temporary=False) Add files to a checkpoint.
• save_files (set) -- set of filepaths to save
• save_notes (str) -- notes about changes during the save
• temporary (bool) -- True if the files should be added to a temporary checkpoint rather than a permanent one. This is usually used for changes that will soon be reverted.
Raises errors.PluginError -- when unable to add to checkpoint
finalize_checkpoint(title) Timestamp and save changes made through the reverter.
Parameters title (str) -- Title describing checkpoint
Raises errors.PluginError -- when an error occurs
recovery_routine() Revert all previously modified files.
Reverts all modified files that have not been saved as a checkpoint
Raises errors.PluginError -- If unable to recover the configuration
revert_temporary_config() Rollback temporary checkpoint.
Raises errors.PluginError -- when unable to revert config
rollback_checkpoints(rollback=1) Rollback saved checkpoints.
Parameters rollback (int) -- Number of checkpoints to revert
Raises errors.PluginError -- If there is a problem with the input or the function is unable to correctly revert the configuration
property ssl_dhparams Full absolute path to ssl_dhparams file.
property updated_ssl_dhparams_digest Full absolute path to digest of updated ssl_dhparams file.
install_ssl_dhparams() Copy Certbot's ssl_dhparams file into the system's config dir if required.
class certbot.plugins.common.Addr(tup, ipv6=False) Bases: object
Represents an virtual host address.
• addr (str) -- addr part of vhost address
• port (str) -- port number or *, or ""
classmethod fromstring(str_addr) Initialize Addr from string.
normalized_tuple() Normalized representation of addr/port tuple
get_addr() Return addr part of Addr object.
get_port() Return port.
get_addr_obj(port) Return new address object with same addr and new port.
get_ipv6_exploded() Return IPv6 in normalized form
class certbot.plugins.common.ChallengePerformer(configurator) Bases: object
Abstract base for challenge performers.
• configurator -- Authenticator and installer plugin
• achalls (list of KeyAuthorizationAnnotatedChallenge) -- Annotated challenges
• indices (list of int) -- Holds the indices of challenges from a larger array so the user of the class doesn't have to.
add_chall(achall, idx=None) Store challenge to be performed when perform() is called.
• achall (KeyAuthorizationAnnotatedChallenge) -- Annotated challenge.
• idx (int) -- index to challenge in a larger array
perform() Perform all added challenges.
Returns challenge responses
Return type list of acme.challenges.KeyAuthorizationChallengeResponse
certbot.plugins.common.install_version_controlled_file(dest_path, digest_path, src_path, all_hashes) Copy a file into an active location (likely the system's config dir) if required.
• dest_path (str) -- destination path for version controlled file
• digest_path (str) -- path to save a digest of the file in
• src_path (str) -- path to version controlled file found in distribution
• all_hashes (list) -- hashes of every released version of the file
certbot.plugins.common.dir_setup(test_dir, pkg) Setup the directories necessary for the configurator.
certbot.plugins.dns_common module Common code for DNS Authenticator Plugins.
class certbot.plugins.dns_common.DNSAuthenticator(config, name) Bases: certbot.plugins.common.Plugin
Base class for DNS  Authenticators
classmethod add_parser_arguments(add, default_propagation_seconds=10) Add plugin arguments to the CLI argument parser.
get_chall_pref(unused_domain)
perform(achalls)
cleanup(achalls)
class certbot.plugins.dns_common.CredentialsConfiguration(filename, mapper=<function CredentialsConfiguration.<lambda>>) Bases: object
Represents a user-supplied filed which stores API credentials.
require(required_variables) Ensures that the supplied set of variables are all present in the file.
Parameters required_variables (dict) -- Map of variable which must be present to error to display.
Raises errors.PluginError -- If one or more are missing.
conf(var) Find a configuration value for variable var, as transformed by mapper.
Parameters var (str) -- The variable to get.
Returns The value of the variable.
certbot.plugins.dns_common.validate_file(filename) Ensure that the specified file exists.
certbot.plugins.dns_common.validate_file_permissions(filename) Ensure that the specified file exists and warn about unsafe permissions.
certbot.plugins.dns_common.base_domain_name_guesses(domain) Return a list of progressively less-specific domain names.
One of these will probably be the domain name known to the DNS provider.
>>> base_domain_name_guesses('foo.bar.baz.example.com') ['foo.bar.baz.example.com', 'bar.baz.example.com', 'baz.example.com', 'example.com', 'com']
Parameters domain (str) -- The domain for which to return guesses.
Returns The a list of less specific domain names.
certbot.plugins.dns_common_lexicon module Common code for DNS Authenticator Plugins built on Lexicon.
class certbot.plugins.dns_common_lexicon.LexiconClient Bases: object
Encapsulates all communication with a DNS provider via Lexicon.
add_txt_record(domain, record_name, record_content) Add a TXT record using the supplied information.
• domain (str) -- The domain to use to look up the managed zone.
• record_name (str) -- The record name (typically beginning with '_acme-challenge.').
• record_content (str) -- The record content (typically the challenge validation).
Raises errors.PluginError -- if an error occurs communicating with the DNS Provider API
del_txt_record(domain, record_name, record_content) Delete a TXT record using the supplied information.
Raises errors.PluginError -- if an error occurs communicating with the DNS Provider  API
certbot.plugins.dns_common_lexicon.build_lexicon_config(lexicon_provider_name, lexicon_options, provider_options) Convenient function to build a Lexicon 2.x/3.x config object. :param str lexicon_provider_name: the name of the lexicon provider to use :param dict lexicon_options: options specific to lexicon :param dict provider_options: options specific to provider :return: configuration to apply to the provider :rtype: ConfigurationResolver or dict
certbot.plugins.dns_test_common module Base test class for DNS authenticators.
class certbot.plugins.dns_test_common.BaseAuthenticatorTest Bases: object
A base test class to reduce duplication between test code for DNS Authenticator Plugins.
Assumes:
• That subclasses also subclass unittest.TestCase
• That the authenticator is stored as self.auth
achall = KeyAuthorizationAnnotatedChallenge(challb=DNS01(token=b'17817c66b60ce2e4012dfad92657527a'), domain='example.com', account_key=JWKRSA(key=<ComparableRSAKey(<cryptography.hazmat.backends.openssl.rsa._RSAPrivateKey object>)>))
test_more_info()
test_get_chall_pref()
test_parser_arguments()
certbot.plugins.dns_test_common.write(values, path) Write the specified values to a config file.
• values (dict) -- A map of values to write.
• path (str) -- Where to write the values.
certbot.plugins.dns_test_common_lexicon module Base test class for DNS authenticators built on Lexicon.
class certbot.plugins.dns_test_common_lexicon.BaseLexiconAuthenticatorTest Bases: certbot.plugins.dns_test_common.BaseAuthenticatorTest
test_perform()
test_cleanup()
class certbot.plugins.dns_test_common_lexicon.BaseLexiconClientTest Bases: object
DOMAIN_NOT_FOUND = Exception('No domain found')
GENERIC_ERROR alias of requests.exceptions.RequestException
LOGIN_ERROR = HTTPError('400 Client Error: ...')
UNKNOWN_LOGIN_ERROR = HTTPError('500 Surprise! Error: ...')
record_prefix = '_acme-challenge'
record_name = '_acme-challenge.example.com'
record_content = 'bar'
test_add_txt_record()
test_add_txt_record_try_twice_to_find_domain()
test_add_txt_record_fail_to_find_domain()
test_add_txt_record_fail_to_authenticate()
test_add_txt_record_fail_to_authenticate_with_unknown_error()
test_add_txt_record_error_finding_domain()
test_add_txt_record_error_adding_record()
test_del_txt_record()
test_del_txt_record_fail_to_find_domain()
test_del_txt_record_fail_to_authenticate()
test_del_txt_record_fail_to_authenticate_with_unknown_error()
test_del_txt_record_error_finding_domain()
test_del_txt_record_error_deleting_record()
certbot.plugins.enhancements module New interface style Certbot enhancements
certbot.plugins.enhancements.ENHANCEMENTS = ['redirect', 'ensure-http-header', 'ocsp-stapling'] List of possible certbot.interfaces.IInstaller enhancements.
List of expected options parameters: - redirect: None - ensure-http-header: name of header (i.e. Strict-Transport-Security) - ocsp-stapling: certificate chain file path
certbot.plugins.enhancements.enabled_enhancements(config) Generator to yield the enabled new style enhancements.
Parameters config (certbot.interfaces.IConfig) -- Configuration.
certbot.plugins.enhancements.are_requested(config) Checks if one or more of the requested enhancements are those of the new enhancement interfaces.
certbot.plugins.enhancements.are_supported(config, installer) Checks that all of the requested enhancements are supported by the installer.
• config (certbot.interfaces.IConfig) -- Configuration.
• installer (interfaces.IInstaller) -- Installer object
Returns If all the requested enhancements are supported by the installer
certbot.plugins.enhancements.enable(lineage, domains, installer, config) Run enable method for each requested enhancement that is supported.
• lineage (certbot.interfaces.RenewableCert) -- Certificate lineage object
• domains (str) -- List of domains in certificate to enhance
certbot.plugins.enhancements.populate_cli(add) Populates the command line flags for certbot._internal.cli.HelpfulParser
Parameters add (func) -- Add function of certbot._internal.cli.HelpfulParser
class certbot.plugins.enhancements.AutoHSTSEnhancement Bases: object
Enhancement interface that installer plugins can implement in order to provide functionality that configures the software to have a 'Strict-Transport-Security' with initially low max-age value that will increase over time.
The plugins implementing new style enhancements are responsible of handling the saving of configuration checkpoints as well as calling possible restarts of managed software themselves. For update_autohsts method, the installer may have to call prepare() to finalize the plugin initialization.
Methods: enable_autohsts is called when the header is initially installed using a low max-age value.
update_autohsts is called every time when Certbot is run using 'renew' verb. The max-age value should be increased over time using this method.
deploy_autohsts is called for every lineage that has had its certificate renewed. A long HSTS max-age value should be set here, as we should be confident that the user is able to automatically renew their certificates.
abstract update_autohsts(lineage, *args, **kwargs) Gets called for each lineage every time Certbot is run with 'renew' verb.  Implementation of this method should increase the max-age value.
Parameters lineage (certbot.interfaces.RenewableCert) -- Certificate lineage object
NOTE: prepare() method inherited from interfaces.IPlugin might need to be called manually within implementation of this interface method to finalize the plugin initialization.
abstract deploy_autohsts(lineage, *args, **kwargs) Gets called for a lineage when its certificate is successfully renewed.  Long max-age value should be set in implementation of this method.
abstract enable_autohsts(lineage, domains, *args, **kwargs) Enables the AutoHSTS enhancement, installing Strict-Transport-Security header with a low initial value to be increased over the subsequent runs of Certbot renew.
• domains (list of str) -- List of domains in certificate to enhance
certbot.plugins.storage module Plugin storage class.
class certbot.plugins.storage.PluginStorage(config, classkey) Bases: object
Class implementing storage functionality for plugins
save() Saves PluginStorage content to disk
Raises errors.PluginStorageError -- when unable to serialize the data or write it to the filesystem
put(key, value) Put configuration value to PluginStorage
• key (str) -- Key to store the value to
• value -- Data to store
fetch(key) Get configuration value from PluginStorage
Parameters key (str) -- Key to get value from the storage
Raises KeyError -- If the key doesn't exist in the storage
certbot.plugins.util module Plugin utilities.
certbot.plugins.util.get_prefixes(path) 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:abc returns ['C:abc', 'C:ab', 'C:a', 'C:']
Parameters path (str) -- the path to break into prefixes
Returns all possible path prefixes of given path in descending order
certbot.plugins.util.path_surgery(cmd) Attempt to perform PATH surgery to find cmd
Mitigates https://github.com/certbot/certbot/issues/1833
Parameters cmd (str) -- the command that is being searched for in the PATH
Returns True if the operation succeeded, False otherwise
certbot.tests package Utilities for running Certbot tests
Submodules certbot.tests.acme_util module ACME utilities for testing.
certbot.tests.acme_util.gen_combos(challbs) Generate natural combinations for challbs.
certbot.tests.acme_util.chall_to_challb(chall, status) Return ChallengeBody from Challenge.
certbot.tests.acme_util.gen_authzr(authz_status, domain, challs, statuses, combos=True) Generate an authorization resource.
• authz_status (acme.messages.Status) -- Status object
• challs (list) -- Challenge objects
• statuses (list) -- status of each challenge object
• combos (bool) -- Whether or not to add combinations
certbot.tests.util module Test utilities.
certbot.tests.util.vector_path(*names) Path to a test vector.
certbot.tests.util.load_vector(*names) Load contents of a test vector.
certbot.tests.util.load_cert(*names) Load certificate.
certbot.tests.util.load_csr(*names) Load certificate request.
certbot.tests.util.load_comparable_csr(*names) Load ComparableX509 certificate request.
certbot.tests.util.load_rsa_private_key(*names) Load RSA private key.
certbot.tests.util.load_pyopenssl_private_key(*names) Load pyOpenSSL private key.
certbot.tests.util.make_lineage(config_dir, testfile, ec=False) Creates a lineage defined by testfile.
This creates the archive, live, and renewal directories if necessary and creates a simple lineage.
• config_dir (str) -- path to the configuration directory
• testfile (str) -- configuration file to base the lineage on
Returns path to the renewal conf file for the created lineage
certbot.tests.util.patch_get_utility(target='zope.component.getUtility') Patch zope.component.getUtility to use a special mock IDisplay.
The mock IDisplay works like a regular mock object, except it also also asserts that methods are called with valid arguments.
Parameters target (str) -- path to patch
Returns mock zope.component.getUtility
Return type mock.MagicMock
certbot.tests.util.patch_get_utility_with_stdout(target='zope.component.getUtility', stdout=None) Patch zope.component.getUtility to use a special mock IDisplay.
The message argument passed to the IDisplay methods is passed to stdout's write method.
• target (str) -- path to patch
• stdout (object) -- object to write standard output to; it is expected to have a write method
class certbot.tests.util.FreezableMock(frozen=False, func=None, return_value=sentinel.DEFAULT) Bases: object
Mock object with the ability to freeze attributes.
This class works like a regular mock.MagicMock object, except attributes and behavior set before the object is frozen cannot be changed during tests.
If a func argument is provided to the constructor, this function is called first when an instance of FreezableMock is called, followed by the usual behavior defined by MagicMock. The return value of func is ignored.
freeze() Freeze object preventing further changes.
class certbot.tests.util.TempDirTestCase(methodName='runTest') Bases: unittest.case.TestCase
Base test class which sets up and tears down a temporary directory
setUp() Execute before test
tearDown() Execute after test
class certbot.tests.util.ConfigTestCase(methodName='runTest') Bases: certbot.tests.util.TempDirTestCase
Test class which sets up a NamespaceConfig object.
certbot.tests.util.lock_and_call(callback, path_to_lock) 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
certbot.tests.util.skip_on_windows(reason) Decorator to skip permanently a test on Windows. A reason is required.
certbot.tests.util.temp_join(path) Return the given path joined to the tempdir path for the current platform Eg.: 'cert' => /tmp/cert (Linux) or 'C:UserscurrentuserAppDataTempcert' (Windows)
Submodules certbot.achallenges module Client annotated ACME challenges.
Please use names such as achall to distinguish from variables "of type" acme.challenges.Challenge (denoted by chall) and ChallengeBody (denoted by challb):
from acme import challenges from acme import messages from certbot import achallenges
chall = challenges.DNS(token='foo') challb = messages.ChallengeBody(chall=chall) achall = achallenges.DNS(chall=challb, domain='example.com')
Note, that all annotated challenges act as a proxy objects:
achall.token == challb.token
class certbot.achallenges.AnnotatedChallenge(**kwargs) Bases: josepy.util.ImmutableMap
Client annotated challenge.
Wraps around server provided challenge and annotates with data useful for the client.
Variables challb -- Wrapped ChallengeBody.
acme_type = NotImplemented
challb
class certbot.achallenges.KeyAuthorizationAnnotatedChallenge(**kwargs) Bases: certbot.achallenges.AnnotatedChallenge
Client annotated KeyAuthorizationChallenge challenge.
response_and_validation(*args, **kwargs) Generate response and validation.
account_key
class certbot.achallenges.DNS(**kwargs) Bases: certbot.achallenges.AnnotatedChallenge
Client annotated "dns" ACME challenge.
acme_type alias of acme.challenges.DNS
certbot.crypto_util module Certbot client crypto utility functions.
certbot.crypto_util.init_save_key(key_size, key_dir, key_type='rsa', elliptic_curve='secp256r1', keyname='key-certbot.pem') Initializes and saves a privkey.
Inits key and saves it in PEM format on the filesystem.
NOTE: keyname is the attempted filename, it may be different if a file already exists at the path.
• key_size (int) -- key size in bits if key size is rsa.
• key_dir (str) -- Key save directory.
• key_type (str) -- Key Type [rsa, ecdsa]
• elliptic_curve (str) -- Name of the elliptic curve if key type is ecdsa.
• keyname (str) -- Filename of key
Returns Key
Return type certbot.util.Key
Raises ValueError -- If unable to generate the key given key_size.
certbot.crypto_util.init_save_csr(privkey, names, path) Initialize a CSR with the given private key.
• privkey (certbot.util.Key) -- Key to include in the CSR
• names (set) -- str names to include in the CSR
• path (str) -- Certificate save directory.
Returns CSR
Return type certbot.util.CSR
certbot.crypto_util.valid_csr(csr) Validate CSR.
Check if csr is a valid CSR for the given domains.
Parameters csr (str) -- CSR in PEM.
Returns Validity of CSR.
certbot.crypto_util.csr_matches_pubkey(csr, privkey) Does private key correspond to the subject public key in the CSR?
• csr (str) -- CSR in PEM.
• privkey (str) -- Private key file contents (PEM)
Returns Correspondence of private key to CSR subject public key.
certbot.crypto_util.import_csr_file(csrfile, data) Import a CSR file, which can be either PEM or DER.
• csrfile (str) -- CSR filename
• data (str) -- contents of the CSR file
Returns (crypto.FILETYPE_PEM, util.CSR object representing the CSR, list of domains requested in the CSR)
certbot.crypto_util.make_key(bits=1024, key_type='rsa', elliptic_curve=None) Generate PEM encoded RSA|EC key.
• bits (int) -- Number of bits if key_type=rsa. At least 1024 for RSA.
• ec_curve (str) -- The elliptic curve to use.
Returns new RSA or ECDSA key in PEM form with specified number of bits or of type ec_curve when key_type ecdsa is used.
certbot.crypto_util.valid_privkey(privkey) Is valid RSA private key?
Parameters privkey (str) -- Private key file contents in PEM
Returns Validity of private key.
certbot.crypto_util.verify_renewable_cert(renewable_cert) For checking that your certs were not corrupted on disk.
Several things are checked:
1. Signature verification for the cert.
2. That fullchain matches cert and chain when concatenated.
3. Check that the private key matches the certificate.
Parameters renewable_cert (certbot.interfaces.RenewableCert) -- cert to verify
Raises errors.Error -- If verification fails.
certbot.crypto_util.verify_renewable_cert_sig(renewable_cert) Verifies the signature of a RenewableCert object.
Raises errors.Error -- If signature verification fails.
certbot.crypto_util.verify_signed_payload(public_key, signature, payload, signature_hash_algorithm) Check the signature of a payload.
• public_key (RSAPublicKey/EllipticCurvePublicKey) -- the public_key to check signature
• signature (bytes) -- the signature bytes
• payload (bytes) -- the payload bytes
:param cryptography.hazmat.primitives.hashes.HashAlgorithm signature_hash_algorithm: algorithm used to hash the payload
• InvalidSignature -- If signature verification fails.
• errors.Error -- If public key type is not supported
certbot.crypto_util.verify_cert_matches_priv_key(cert_path, key_path) Verifies that the private key and cert match.
• cert_path (str) -- path to a cert in PEM format
• key_path (str) -- path to a private key file
Raises errors.Error -- If they don't match.
certbot.crypto_util.verify_fullchain(renewable_cert) Verifies that fullchain is indeed cert concatenated with chain.
Raises errors.Error -- If cert and chain do not combine to fullchain.
certbot.crypto_util.pyopenssl_load_certificate(data) Load PEM/DER certificate.
Raises errors.Error --
certbot.crypto_util.get_sans_from_cert(cert, typ=1) Get a list of Subject Alternative Names from a certificate.
• cert (str) -- Certificate (encoded).
• typ -- crypto.FILETYPE_PEM or crypto.FILETYPE_ASN1
Returns A list of Subject Alternative Names.
certbot.crypto_util.get_names_from_cert(csr, typ=1) Get a list of domains from a cert, including the CN if it is set.
Returns A list of domain names.
certbot.crypto_util.dump_pyopenssl_chain(chain, filetype=1) Dump certificate chain into a bundle.
Parameters chain (list) -- List of crypto.X509 (or wrapped in josepy.util.ComparableX509).
certbot.crypto_util.notBefore(cert_path) When does the cert at cert_path start being valid?
Parameters cert_path (str) -- path to a cert in PEM format
Returns the notBefore value from the cert at cert_path
Return type datetime.datetime
certbot.crypto_util.notAfter(cert_path) When does the cert at cert_path stop being valid?
Returns the notAfter value from the cert at cert_path
certbot.crypto_util.sha256sum(filename) Compute a sha256sum of a file.
NB: In given file, platform specific newlines characters will be converted into their equivalent unicode counterparts before calculating the hash.
Parameters filename (str) -- path to the file whose hash will be computed
Returns sha256 digest of the file in hexadecimal
certbot.crypto_util.cert_and_chain_from_fullchain(fullchain_pem) Split fullchain_pem into cert_pem and chain_pem
Parameters fullchain_pem (str) -- concatenated cert + chain
Returns tuple of string cert_pem and chain_pem
Raises errors.Error -- If there are less than 2 certificates in the chain.
certbot.crypto_util.get_serial_from_cert(cert_path) Retrieve the serial number of a certificate from certificate path
Returns serial number of the certificate
certbot.crypto_util.find_chain_with_issuer(fullchains, issuer_cn, warn_on_no_match=False) Chooses the first certificate chain from fullchains which contains an Issuer Subject Common Name matching issuer_cn.
• fullchains (list of str) -- The list of fullchains in PEM chain format.
• issuer_cn (str) -- The exact Subject Common Name to match against any issuer in the certificate chain.
Returns The best-matching fullchain, PEM-encoded, or the first if none match.
certbot.errors module Certbot client errors.
exception certbot.errors.Error Bases: Exception
Generic Certbot client error.
exception certbot.errors.AccountStorageError Bases: certbot.errors.Error
Generic AccountStorage error.
exception certbot.errors.AccountNotFound Bases: certbot.errors.AccountStorageError
Account not found error.
exception certbot.errors.ReverterError Bases: certbot.errors.Error
Certbot Reverter error.
exception certbot.errors.SubprocessError Bases: certbot.errors.Error
Subprocess handling error.
exception certbot.errors.CertStorageError Bases: certbot.errors.Error
Generic CertStorage error.
exception certbot.errors.HookCommandNotFound Bases: certbot.errors.Error
Failed to find a hook command in the PATH.
exception certbot.errors.SignalExit Bases: certbot.errors.Error
A Unix signal was received while in the ErrorHandler context manager.
exception certbot.errors.OverlappingMatchFound Bases: certbot.errors.Error
Multiple lineages matched what should have been a unique result.
exception certbot.errors.LockError Bases: certbot.errors.Error
File locking error.
exception certbot.errors.AuthorizationError Bases: certbot.errors.Error
Authorization error.
exception certbot.errors.FailedChallenges(failed_achalls) Bases: certbot.errors.AuthorizationError
Failed challenges error.
Variables failed_achalls (set) -- Failed AnnotatedChallenge instances.
exception certbot.errors.PluginError Bases: certbot.errors.Error
Certbot Plugin error.
exception certbot.errors.PluginEnhancementAlreadyPresent Bases: certbot.errors.Error
Enhancement was already set
exception certbot.errors.PluginSelectionError Bases: certbot.errors.Error
A problem with plugin/configurator selection or setup
exception certbot.errors.NoInstallationError Bases: certbot.errors.PluginError
Certbot No Installation error.
exception certbot.errors.MisconfigurationError Bases: certbot.errors.PluginError
Certbot Misconfiguration error.
exception certbot.errors.NotSupportedError Bases: certbot.errors.PluginError
Certbot Plugin function not supported error.
exception certbot.errors.PluginStorageError Bases: certbot.errors.PluginError
Certbot Plugin Storage error.
exception certbot.errors.StandaloneBindError(socket_error, port) Bases: certbot.errors.Error
Standalone plugin bind error.
exception certbot.errors.ConfigurationError Bases: certbot.errors.Error
Configuration sanity error.
exception certbot.errors.MissingCommandlineFlag Bases: certbot.errors.Error
A command line argument was missing in noninteractive usage
certbot.interfaces module Certbot client interfaces.
class certbot.interfaces.AccountStorage Bases: object
Accounts storage interface.
abstract find_all() Find all accounts.
Returns All found accounts.
abstract load(account_id) Load an account by its id.
• AccountNotFound -- if account could not be found
• AccountStorageError -- if account could not be loaded
abstract save(account, client) Save account.
Raises AccountStorageError -- if account could not be saved
interface certbot.interfaces.IPluginFactory IPlugin factory.
Objects providing this interface will be called without satisfying any entry point "extras" (extra dependencies) you might have defined for your plugin, e.g (excerpt from setup.py script):
setup( ... entry_points={ 'certbot.plugins': [ 'name=example_project.plugin[plugin_deps]', ], }, extras_require={ 'plugin_deps': ['dep1', 'dep2'], } )
Therefore, make sure such objects are importable and usable without extras. This is necessary, because CLI does the following operations (in order):
• loads an entry point,
• calls inject_parser_options,
• requires an entry point,
• creates plugin instance (__call__).
description Short plugin description
__call__(config, name) Create new IPlugin.
• config (IConfig) -- Configuration.
• name (str) -- Unique plugin name.
inject_parser_options(parser, name) Inject argument parser options (flags).
1. Be nice and prepend all options and destinations with option_namespace and dest_namespace.
2. Inject options (flags) only. Positional arguments are not allowed, as this would break the CLI.
• parser (ArgumentParser) -- (Almost) top-level CLI parser.
interface certbot.interfaces.IPlugin Certbot plugin.
prepare() Prepare the plugin.
Finish up any additional initialization.
• PluginError -- when full initialization cannot be completed.
• MisconfigurationError -- when full initialization cannot be completed. Plugin will be displayed on a list of available plugins.
• NoInstallationError -- when the necessary programs/files cannot be located. Plugin will NOT be displayed on a list of available plugins.
• NotSupportedError -- when the installation is recognized, but the version is not currently supported.
more_info() Human-readable string to help the user.
Should describe the steps taken and any relevant info to help the user decide which plugin to use.
Rtype str