response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Verify an OCSP response signature against certificate issuer or responder | def _check_ocsp_response_signature(response_ocsp: 'ocsp.OCSPResponse',
issuer_cert: x509.Certificate, cert_path: str) -> None:
"""Verify an OCSP response signature against certificate issuer or responder"""
def _key_hash(cert: x509.Certificate) -> bytes:
return x509.SubjectKeyIdentifier.from_public_key(cert.public_key()).digest
if (response_ocsp.responder_name == issuer_cert.subject
or response_ocsp.responder_key_hash == _key_hash(issuer_cert)):
# Case where the OCSP responder is also the certificate issuer
logger.debug('OCSP response for certificate %s is signed by the certificate\'s issuer.',
cert_path)
responder_cert = issuer_cert
else:
# Case where the OCSP responder is not the certificate issuer
logger.debug('OCSP response for certificate %s is delegated to an external responder.',
cert_path)
responder_certs = [cert for cert in response_ocsp.certificates
if response_ocsp.responder_name == cert.subject or \
response_ocsp.responder_key_hash == _key_hash(cert)]
if not responder_certs:
raise AssertionError('no matching responder certificate could be found')
# We suppose here that the ACME server support only one certificate in the OCSP status
# request. This is currently the case for LetsEncrypt servers.
# See https://github.com/letsencrypt/boulder/issues/2331
responder_cert = responder_certs[0]
if responder_cert.issuer != issuer_cert.subject:
raise AssertionError('responder certificate is not signed '
'by the certificate\'s issuer')
try:
extension = responder_cert.extensions.get_extension_for_class(x509.ExtendedKeyUsage)
delegate_authorized = x509.oid.ExtendedKeyUsageOID.OCSP_SIGNING in extension.value
except (x509.ExtensionNotFound, IndexError):
delegate_authorized = False
if not delegate_authorized:
raise AssertionError('responder is not authorized by issuer to sign OCSP responses')
# Following line may raise UnsupportedAlgorithm
chosen_cert_hash = responder_cert.signature_hash_algorithm
assert chosen_cert_hash # always present for RSA and ECDSA certificates.
# For a delegate OCSP responder, we need first check that its certificate is effectively
# signed by the certificate issuer.
crypto_util.verify_signed_payload(issuer_cert.public_key(), responder_cert.signature,
responder_cert.tbs_certificate_bytes, chosen_cert_hash)
# Following line may raise UnsupportedAlgorithm
chosen_response_hash = response_ocsp.signature_hash_algorithm
# We check that the OSCP response is effectively signed by the responder
# (an authorized delegate one or the certificate issuer itself).
if not chosen_response_hash:
raise AssertionError("no signature hash algorithm defined")
crypto_util.verify_signed_payload(responder_cert.public_key(), response_ocsp.signature,
response_ocsp.tbs_response_bytes, chosen_response_hash) |
Parse openssl's weird output to work out what it means. | def _translate_ocsp_query(cert_path: str, ocsp_output: str, ocsp_errors: str) -> bool:
"""Parse openssl's weird output to work out what it means."""
states = ("good", "revoked", "unknown")
patterns = [r"{0}: (WARNING.*)?{1}".format(cert_path, s) for s in states]
good, revoked, unknown = (re.search(p, ocsp_output, flags=re.DOTALL) for p in patterns)
warning = good.group(1) if good else None
if ("Response verify OK" not in ocsp_errors) or (good and warning) or unknown:
logger.info("Revocation status for %s is unknown", cert_path)
logger.debug("Uncertain output:\n%s\nstderr:\n%s", ocsp_output, ocsp_errors)
return False
elif good and not warning:
return False
elif revoked:
warning = revoked.group(1)
if warning:
logger.info("OCSP revocation warning: %s", warning)
return True
else:
logger.warning("Unable to properly parse OCSP output: %s\nstderr:%s",
ocsp_output, ocsp_errors)
return False |
When Certbot is run inside a Snap, certain environment variables
are modified. But Certbot sometimes calls out to external programs,
since it uses classic confinement. When we do that, we must modify
the env to remove our modifications so it will use the system's
libraries, since they may be incompatible with the versions of
libraries included in the Snap. For example, apachectl, Nginx, and
anything run from inside a hook should call this function and pass
the results into the ``env`` argument of ``subprocess.Popen``.
:returns: A modified copy of os.environ ready to pass to Popen
:rtype: dict | def env_no_snap_for_external_calls() -> Dict[str, str]:
"""
When Certbot is run inside a Snap, certain environment variables
are modified. But Certbot sometimes calls out to external programs,
since it uses classic confinement. When we do that, we must modify
the env to remove our modifications so it will use the system's
libraries, since they may be incompatible with the versions of
libraries included in the Snap. For example, apachectl, Nginx, and
anything run from inside a hook should call this function and pass
the results into the ``env`` argument of ``subprocess.Popen``.
:returns: A modified copy of os.environ ready to pass to Popen
:rtype: dict
"""
env = os.environ.copy()
# Avoid accidentally modifying env
if 'SNAP' not in env or 'CERTBOT_SNAPPED' not in env:
return env
for path_name in ('PATH', 'LD_LIBRARY_PATH'):
if path_name in env:
env[path_name] = ':'.join(x for x in env[path_name].split(':') if env['SNAP'] not in x)
return env |
Run the script with the given params.
:param list params: List of parameters to pass to subprocess.run
:param callable log: Logger method to use for errors | def run_script(params: List[str], log: Callable[[str], None]=logger.error) -> Tuple[str, str]:
"""Run the script with the given params.
:param list params: List of parameters to pass to subprocess.run
:param callable log: Logger method to use for errors
"""
try:
proc = subprocess.run(params,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
env=env_no_snap_for_external_calls())
except (OSError, ValueError):
msg = "Unable to run the command: %s" % " ".join(params)
log(msg)
raise errors.SubprocessError(msg)
if proc.returncode != 0:
msg = "Error while running %s.\n%s\n%s" % (
" ".join(params), proc.stdout, proc.stderr)
# Enter recovery routine...
log(msg)
raise errors.SubprocessError(msg)
return proc.stdout, proc.stderr |
Determine whether path/name refers to an executable.
:param str exe: Executable path or name
:returns: If exe is a valid executable
:rtype: bool | def exe_exists(exe: str) -> bool:
"""Determine whether path/name refers to an executable.
:param str exe: Executable path or name
:returns: If exe is a valid executable
:rtype: bool
"""
path, _ = os.path.split(exe)
if path:
return filesystem.is_executable(exe)
for path in os.environ["PATH"].split(os.pathsep):
if filesystem.is_executable(os.path.join(path, exe)):
return True
return False |
Lock the directory at dir_path until program exit.
:param str dir_path: path to directory
:raises errors.LockError: if the lock is held by another process | def lock_dir_until_exit(dir_path: str) -> None:
"""Lock the directory at dir_path until program exit.
:param str dir_path: path to directory
:raises errors.LockError: if the lock is held by another process
"""
if not _LOCKS: # this is the first lock to be released at exit
atexit_register(_release_locks)
if dir_path not in _LOCKS:
_LOCKS[dir_path] = lock.lock_dir(dir_path) |
Ensure directory exists with proper permissions and is locked.
:param str directory: Path to a directory.
:param int mode: Directory mode.
:param bool strict: require directory to be owned by current user
:raises .errors.LockError: if the directory cannot be locked
:raises .errors.Error: if the directory cannot be made or verified | def set_up_core_dir(directory: str, mode: int, strict: bool) -> None:
"""Ensure directory exists with proper permissions and is locked.
:param str directory: Path to a directory.
:param int mode: Directory mode.
:param bool strict: require directory to be owned by current user
:raises .errors.LockError: if the directory cannot be locked
:raises .errors.Error: if the directory cannot be made or verified
"""
try:
make_or_verify_dir(directory, mode, strict)
lock_dir_until_exit(directory)
except OSError as error:
logger.debug("Exception was:", exc_info=True)
raise errors.Error(PERM_ERR_FMT.format(error)) |
Make sure directory exists with proper permissions.
:param str directory: Path to a directory.
:param int mode: Directory mode.
:param bool strict: require directory to be owned by current user
:raises .errors.Error: if a directory already exists,
but has wrong permissions or owner
:raises OSError: if invalid or inaccessible file names and
paths, or other arguments that have the correct type,
but are not accepted by the operating system. | def make_or_verify_dir(directory: str, mode: int = 0o755, strict: bool = False) -> None:
"""Make sure directory exists with proper permissions.
:param str directory: Path to a directory.
:param int mode: Directory mode.
:param bool strict: require directory to be owned by current user
:raises .errors.Error: if a directory already exists,
but has wrong permissions or owner
:raises OSError: if invalid or inaccessible file names and
paths, or other arguments that have the correct type,
but are not accepted by the operating system.
"""
try:
filesystem.makedirs(directory, mode)
except OSError as exception:
if exception.errno == errno.EEXIST:
if strict and not filesystem.check_permissions(directory, mode):
raise errors.Error(
"%s exists, but it should be owned by current user with"
" permissions %s" % (directory, oct(mode)))
else:
raise |
Safely open a file.
:param str path: Path to a file.
:param str mode: Same os `mode` for `open`.
:param int chmod: Same as `mode` for `filesystem.open`, uses Python defaults
if ``None``. | def safe_open(path: str, mode: str = "w", chmod: Optional[int] = None) -> IO:
"""Safely open a file.
:param str path: Path to a file.
:param str mode: Same os `mode` for `open`.
:param int chmod: Same as `mode` for `filesystem.open`, uses Python defaults
if ``None``.
"""
open_args: Union[Tuple[()], Tuple[int]] = ()
if chmod is not None:
open_args = (chmod,)
fdopen_args: Union[Tuple[()], Tuple[int]] = ()
fd = filesystem.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, *open_args)
return os.fdopen(fd, mode, *fdopen_args) |
Safely finds a unique file.
:param str path: path/filename.ext
:param int chmod: File mode
:param str mode: Open mode
:returns: tuple of file object and file name | def unique_file(path: str, chmod: int = 0o777, mode: str = "w") -> Tuple[IO, str]:
"""Safely finds a unique file.
:param str path: path/filename.ext
:param int chmod: File mode
:param str mode: Open mode
:returns: tuple of file object and file name
"""
path, tail = os.path.split(path)
return _unique_file(
path, filename_pat=(lambda count: "%04d_%s" % (count, tail)),
count=0, chmod=chmod, mode=mode) |
Safely finds a unique file using lineage convention.
:param str path: directory path
:param str filename: proposed filename
:param int chmod: file mode
:param str mode: open mode
:returns: tuple of file object and file name (which may be modified
from the requested one by appending digits to ensure uniqueness)
:raises OSError: if writing files fails for an unanticipated reason,
such as a full disk or a lack of permission to write to
specified location. | def unique_lineage_name(path: str, filename: str, chmod: int = 0o644,
mode: str = "w") -> Tuple[IO, str]:
"""Safely finds a unique file using lineage convention.
:param str path: directory path
:param str filename: proposed filename
:param int chmod: file mode
:param str mode: open mode
:returns: tuple of file object and file name (which may be modified
from the requested one by appending digits to ensure uniqueness)
:raises OSError: if writing files fails for an unanticipated reason,
such as a full disk or a lack of permission to write to
specified location.
"""
preferred_path = os.path.join(path, "%s.conf" % (filename))
try:
return safe_open(preferred_path, chmod=chmod), preferred_path
except OSError as err:
if err.errno != errno.EEXIST:
raise
return _unique_file(
path, filename_pat=(lambda count: "%s-%04d.conf" % (filename, count)),
count=1, chmod=chmod, mode=mode) |
Remove a file that may not exist. | def safely_remove(path: str) -> None:
"""Remove a file that may not exist."""
try:
os.remove(path)
except OSError as err:
if err.errno != errno.ENOENT:
raise |
Removes names that aren't considered valid by Let's Encrypt.
:param set all_names: all names found in the configuration
:returns: all found names that are considered valid by LE
:rtype: set | def get_filtered_names(all_names: Set[str]) -> Set[str]:
"""Removes names that aren't considered valid by Let's Encrypt.
:param set all_names: all names found in the configuration
:returns: all found names that are considered valid by LE
:rtype: set
"""
filtered_names = set()
for name in all_names:
try:
filtered_names.add(enforce_le_validity(name))
except errors.ConfigurationError:
logger.debug('Not suggesting name "%s"', name, exc_info=True)
return filtered_names |
Get OS name and version
:returns: (os_name, os_version)
:rtype: `tuple` of `str` | def get_os_info() -> Tuple[str, str]:
"""
Get OS name and version
:returns: (os_name, os_version)
:rtype: `tuple` of `str`
"""
return get_python_os_info(pretty=False) |
Get OS name and version string for User Agent
:returns: os_ua
:rtype: `str` | def get_os_info_ua() -> str:
"""
Get OS name and version string for User Agent
:returns: os_ua
:rtype: `str`
"""
if _USE_DISTRO:
os_info = distro.name(pretty=True)
if not _USE_DISTRO or not os_info:
return " ".join(get_python_os_info(pretty=True))
return os_info |
Get a list of strings that indicate the distribution likeness to
other distributions.
:returns: List of distribution acronyms
:rtype: `list` of `str` | def get_systemd_os_like() -> List[str]:
"""
Get a list of strings that indicate the distribution likeness to
other distributions.
:returns: List of distribution acronyms
:rtype: `list` of `str`
"""
if _USE_DISTRO:
return distro.like().split(" ")
return [] |
Get single value from a file formatted like systemd /etc/os-release
:param str varname: Name of variable to fetch
:param str filepath: File path of os-release file
:returns: requested value
:rtype: `str` | def get_var_from_file(varname: str, filepath: str = "/etc/os-release") -> str:
"""
Get single value from a file formatted like systemd /etc/os-release
:param str varname: Name of variable to fetch
:param str filepath: File path of os-release file
:returns: requested value
:rtype: `str`
"""
var_string = varname+"="
if not os.path.isfile(filepath):
return ""
with open(filepath, 'r') as fh:
contents = fh.readlines()
for line in contents:
if line.strip().startswith(var_string):
# Return the value of var, normalized
return _normalize_string(line.strip()[len(var_string):])
return "" |
Helper function for get_var_from_file() to remove quotes
and whitespaces | def _normalize_string(orig: str) -> str:
"""
Helper function for get_var_from_file() to remove quotes
and whitespaces
"""
return orig.replace('"', '').replace("'", "").strip() |
Get Operating System type/distribution and major version
using python platform module
:param bool pretty: If the returned OS name should be in longer (pretty) form
:returns: (os_name, os_version)
:rtype: `tuple` of `str` | def get_python_os_info(pretty: bool = False) -> Tuple[str, str]:
"""
Get Operating System type/distribution and major version
using python platform module
:param bool pretty: If the returned OS name should be in longer (pretty) form
:returns: (os_name, os_version)
:rtype: `tuple` of `str`
"""
info = platform.system_alias(
platform.system(),
platform.release(),
platform.version()
)
os_type, os_ver, _ = info
os_type = os_type.lower()
if os_type.startswith('linux') and _USE_DISTRO:
distro_name, distro_version = distro.name() if pretty else distro.id(), distro.version()
# On arch, these values are reportedly empty strings so handle it
# defensively
# so handle it defensively
if distro_name:
os_type = distro_name
if distro_version:
os_ver = distro_version
elif os_type.startswith('darwin'):
try:
proc = subprocess.run(
["/usr/bin/sw_vers", "-productVersion"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=False, universal_newlines=True,
env=env_no_snap_for_external_calls(),
)
except OSError:
proc = subprocess.run(
["sw_vers", "-productVersion"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=False, universal_newlines=True,
env=env_no_snap_for_external_calls(),
)
os_ver = proc.stdout.rstrip('\n')
elif os_type.startswith('freebsd'):
# eg "9.3-RC3-p1"
os_ver = os_ver.partition("-")[0]
os_ver = os_ver.partition(".")[0]
elif platform.win32_ver()[1]:
os_ver = platform.win32_ver()[1]
else:
# Cases known to fall here: Cygwin python
os_ver = ''
return os_type, os_ver |
Scrub email address before using it. | def safe_email(email: str) -> bool:
"""Scrub email address before using it."""
if EMAIL_REGEX.match(email) is not None:
return not email.startswith(".") and ".." not in email
logger.error("Invalid email address: %s.", email)
return False |
Adds a deprecated argument with the name argument_name.
Deprecated arguments are not shown in the help. If they are used on
the command line, a warning is shown stating that the argument is
deprecated and no other action is taken.
:param callable add_argument: Function that adds arguments to an
argument parser/group.
:param str argument_name: Name of deprecated argument.
:param nargs: Value for nargs when adding the argument to argparse. | def add_deprecated_argument(add_argument: Callable[..., None], argument_name: str,
nargs: Union[str, int]) -> None:
"""Adds a deprecated argument with the name argument_name.
Deprecated arguments are not shown in the help. If they are used on
the command line, a warning is shown stating that the argument is
deprecated and no other action is taken.
:param callable add_argument: Function that adds arguments to an
argument parser/group.
:param str argument_name: Name of deprecated argument.
:param nargs: Value for nargs when adding the argument to argparse.
"""
if DeprecatedArgumentAction not in configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE:
# In version 0.12.0 ACTION_TYPES_THAT_DONT_NEED_A_VALUE was
# changed from a set to a tuple.
if isinstance(configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE, set):
configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE.add(
DeprecatedArgumentAction)
else:
configargparse.ACTION_TYPES_THAT_DONT_NEED_A_VALUE += (
DeprecatedArgumentAction,)
add_argument(argument_name, action=DeprecatedArgumentAction,
help=argparse.SUPPRESS, nargs=nargs) |
Checks that Let's Encrypt will consider domain to be valid.
:param str domain: FQDN to check
:type domain: `str`
:returns: The domain cast to `str`, with ASCII-only contents
:rtype: str
:raises ConfigurationError: for invalid domains and cases where Let's
Encrypt currently will not issue certificates | def enforce_le_validity(domain: str) -> str:
"""Checks that Let's Encrypt will consider domain to be valid.
:param str domain: FQDN to check
:type domain: `str`
:returns: The domain cast to `str`, with ASCII-only contents
:rtype: str
:raises ConfigurationError: for invalid domains and cases where Let's
Encrypt currently will not issue certificates
"""
domain = enforce_domain_sanity(domain)
if not re.match("^[A-Za-z0-9.-]*$", domain):
raise errors.ConfigurationError(
"{0} contains an invalid character. "
"Valid characters are A-Z, a-z, 0-9, ., and -.".format(domain))
labels = domain.split(".")
if len(labels) < 2:
raise errors.ConfigurationError(
"{0} needs at least two labels".format(domain))
for label in labels:
if label.startswith("-"):
raise errors.ConfigurationError(
'label "{0}" in domain "{1}" cannot start with "-"'.format(
label, domain))
if label.endswith("-"):
raise errors.ConfigurationError(
'label "{0}" in domain "{1}" cannot end with "-"'.format(
label, domain))
return domain |
Method which validates domain value and errors out if
the requirements are not met.
:param domain: Domain to check
:type domain: `str` or `bytes`
:raises ConfigurationError: for invalid domains and cases where Let's
Encrypt currently will not issue certificates
:returns: The domain cast to `str`, with ASCII-only contents
:rtype: str | def enforce_domain_sanity(domain: Union[str, bytes]) -> str:
"""Method which validates domain value and errors out if
the requirements are not met.
:param domain: Domain to check
:type domain: `str` or `bytes`
:raises ConfigurationError: for invalid domains and cases where Let's
Encrypt currently will not issue certificates
:returns: The domain cast to `str`, with ASCII-only contents
:rtype: str
"""
# Unicode
try:
if isinstance(domain, bytes):
domain = domain.decode('utf-8')
domain.encode('ascii')
except UnicodeError:
raise errors.ConfigurationError("Non-ASCII domain names not supported. "
"To issue for an Internationalized Domain Name, use Punycode.")
domain = domain.lower()
# Remove trailing dot
domain = domain[:-1] if domain.endswith('.') else domain
# Separately check for odd "domains" like "http://example.com" to fail
# fast and provide a clear error message
for scheme in ["http", "https"]: # Other schemes seem unlikely
if domain.startswith("{0}://".format(scheme)):
raise errors.ConfigurationError(
"Requested name {0} appears to be a URL, not a FQDN. "
"Try again without the leading \"{1}://\".".format(
domain, scheme
)
)
if is_ipaddress(domain):
raise errors.ConfigurationError(
"Requested name {0} is an IP address. The Let's Encrypt "
"certificate authority will not issue certificates for a "
"bare IP address.".format(domain))
# FQDN checks according to RFC 2181: domain name should be less than 255
# octets (inclusive). And each label is 1 - 63 octets (inclusive).
# https://tools.ietf.org/html/rfc2181#section-11
msg = "Requested domain {0} is not a FQDN because".format(domain)
if len(domain) > 255:
raise errors.ConfigurationError("{0} it is too long.".format(msg))
labels = domain.split('.')
for l in labels:
if not l:
raise errors.ConfigurationError("{0} it contains an empty label.".format(msg))
if len(l) > 63:
raise errors.ConfigurationError("{0} label {1} is too long.".format(msg, l))
return domain |
Is given address string form of IP(v4 or v6) address?
:param address: address to check
:type address: `str`
:returns: True if address is valid IP address, otherwise return False.
:rtype: bool | def is_ipaddress(address: str) -> bool:
"""Is given address string form of IP(v4 or v6) address?
:param address: address to check
:type address: `str`
:returns: True if address is valid IP address, otherwise return False.
:rtype: bool
"""
try:
socket.inet_pton(socket.AF_INET, address)
# If this line runs it was ip address (ipv4)
return True
except socket.error:
# It wasn't an IPv4 address, so try ipv6
try:
socket.inet_pton(socket.AF_INET6, address)
return True
except socket.error:
return False |
"Is domain a wildcard domain?
:param domain: domain to check
:type domain: `bytes` or `str`
:returns: True if domain is a wildcard, otherwise, False
:rtype: bool | def is_wildcard_domain(domain: Union[str, bytes]) -> bool:
""""Is domain a wildcard domain?
:param domain: domain to check
:type domain: `bytes` or `str`
:returns: True if domain is a wildcard, otherwise, False
:rtype: bool
"""
if isinstance(domain, str):
return domain.startswith("*.")
return domain.startswith(b"*.") |
Determine whether a given ACME server is a known test / staging server.
:param str srv: the URI for the ACME server
:returns: True iff srv is a known test / staging server
:rtype bool: | def is_staging(srv: str) -> bool:
"""
Determine whether a given ACME server is a known test / staging server.
:param str srv: the URI for the ACME server
:returns: True iff srv is a known test / staging server
:rtype bool:
"""
return srv == constants.STAGING_URI or "staging" in srv |
Sets func to be called before the program exits.
Special care is taken to ensure func is only called when the process
that first imports this module exits rather than any child processes.
:param function func: function to be called in case of an error | def atexit_register(func: Callable, *args: Any, **kwargs: Any) -> None:
"""Sets func to be called before the program exits.
Special care is taken to ensure func is only called when the process
that first imports this module exits rather than any child processes.
:param function func: function to be called in case of an error
"""
atexit.register(_atexit_call, func, *args, **kwargs) |
Parses a version string into its components.
This code and the returned tuple is based on the now deprecated
distutils.version.LooseVersion class from the Python standard library.
Two LooseVersion classes and two lists as returned by this function should
compare in the same way. See
https://github.com/python/cpython/blob/v3.10.0/Lib/distutils/version.py#L205-L347.
:param str version_string: version string
:returns: list of parsed version string components
:rtype: list | def parse_loose_version(version_string: str) -> List[Union[int, str]]:
"""Parses a version string into its components.
This code and the returned tuple is based on the now deprecated
distutils.version.LooseVersion class from the Python standard library.
Two LooseVersion classes and two lists as returned by this function should
compare in the same way. See
https://github.com/python/cpython/blob/v3.10.0/Lib/distutils/version.py#L205-L347.
:param str version_string: version string
:returns: list of parsed version string components
:rtype: list
"""
loose_version = LooseVersion(version_string)
return loose_version.version_components |
Apply a POSIX mode on given file_path:
- for Linux, the POSIX mode will be directly applied using chmod,
- for Windows, the POSIX mode will be translated into a Windows DACL that make sense for
Certbot context, and applied to the file using kernel calls.
The definition of the Windows DACL that correspond to a POSIX mode, in the context of Certbot,
is explained at https://github.com/certbot/certbot/issues/6356 and is implemented by the
method `_generate_windows_flags()`.
:param str file_path: Path of the file
:param int mode: POSIX mode to apply | def chmod(file_path: str, mode: int) -> None:
"""
Apply a POSIX mode on given file_path:
- for Linux, the POSIX mode will be directly applied using chmod,
- for Windows, the POSIX mode will be translated into a Windows DACL that make sense for
Certbot context, and applied to the file using kernel calls.
The definition of the Windows DACL that correspond to a POSIX mode, in the context of Certbot,
is explained at https://github.com/certbot/certbot/issues/6356 and is implemented by the
method `_generate_windows_flags()`.
:param str file_path: Path of the file
:param int mode: POSIX mode to apply
"""
if POSIX_MODE:
os.chmod(file_path, mode)
else:
_apply_win_mode(file_path, mode) |
Set the current numeric umask and return the previous umask. On Linux, the built-in umask
method is used. On Windows, our Certbot-side implementation is used.
:param int mask: The user file-creation mode mask to apply.
:rtype: int
:return: The previous umask value. | def umask(mask: int) -> int:
"""
Set the current numeric umask and return the previous umask. On Linux, the built-in umask
method is used. On Windows, our Certbot-side implementation is used.
:param int mask: The user file-creation mode mask to apply.
:rtype: int
:return: The previous umask value.
"""
if POSIX_MODE:
return os.umask(mask)
previous_umask = _WINDOWS_UMASK.mask
_WINDOWS_UMASK.mask = mask
return previous_umask |
Apply a umask temporarily, meant to be used in a `with` block. Uses the Certbot
implementation of umask.
:param int mask: The user file-creation mode mask to apply temporarily | def temp_umask(mask: int) -> Generator[None, None, None]:
"""
Apply a umask temporarily, meant to be used in a `with` block. Uses the Certbot
implementation of umask.
:param int mask: The user file-creation mode mask to apply temporarily
"""
old_umask: Optional[int] = None
try:
old_umask = umask(mask)
yield None
finally:
if old_umask is not None:
umask(old_umask) |
Copy ownership (user and optionally group on Linux) from the source to the
destination, then apply given mode in compatible way for Linux and Windows.
This replaces the os.chown command.
:param str src: Path of the source file
:param str dst: Path of the destination file
:param int mode: Permission mode to apply on the destination file
:param bool copy_user: Copy user if `True`
:param bool copy_group: Copy group if `True` on Linux (has no effect on Windows) | def copy_ownership_and_apply_mode(src: str, dst: str, mode: int,
copy_user: bool, copy_group: bool) -> None:
"""
Copy ownership (user and optionally group on Linux) from the source to the
destination, then apply given mode in compatible way for Linux and Windows.
This replaces the os.chown command.
:param str src: Path of the source file
:param str dst: Path of the destination file
:param int mode: Permission mode to apply on the destination file
:param bool copy_user: Copy user if `True`
:param bool copy_group: Copy group if `True` on Linux (has no effect on Windows)
"""
if POSIX_MODE:
stats = os.stat(src)
user_id = stats.st_uid if copy_user else -1
group_id = stats.st_gid if copy_group else -1
# On Windows, os.chown does not exist. This is checked through POSIX_MODE value,
# but MyPy/PyLint does not know it and raises an error here on Windows.
# We disable specifically the check to fix the issue.
os.chown(dst, user_id, group_id)
elif copy_user:
# There is no group handling in Windows
_copy_win_ownership(src, dst)
chmod(dst, mode) |
Copy ownership (user and optionally group on Linux) and mode/DACL
from the source to the destination.
:param str src: Path of the source file
:param str dst: Path of the destination file
:param bool copy_user: Copy user if `True`
:param bool copy_group: Copy group if `True` on Linux (has no effect on Windows) | def copy_ownership_and_mode(src: str, dst: str,
copy_user: bool = True, copy_group: bool = True) -> None:
"""
Copy ownership (user and optionally group on Linux) and mode/DACL
from the source to the destination.
:param str src: Path of the source file
:param str dst: Path of the destination file
:param bool copy_user: Copy user if `True`
:param bool copy_group: Copy group if `True` on Linux (has no effect on Windows)
"""
if POSIX_MODE:
# On Linux, we just delegate to chown and chmod.
stats = os.stat(src)
user_id = stats.st_uid if copy_user else -1
group_id = stats.st_gid if copy_group else -1
os.chown(dst, user_id, group_id)
chmod(dst, stats.st_mode)
else:
if copy_user:
# There is no group handling in Windows
_copy_win_ownership(src, dst)
_copy_win_mode(src, dst) |
Check if the given mode matches the permissions of the given file.
On Linux, will make a direct comparison, on Windows, mode will be compared against
the security model.
:param str file_path: Path of the file
:param int mode: POSIX mode to test
:rtype: bool
:return: True if the POSIX mode matches the file permissions | def check_mode(file_path: str, mode: int) -> bool:
"""
Check if the given mode matches the permissions of the given file.
On Linux, will make a direct comparison, on Windows, mode will be compared against
the security model.
:param str file_path: Path of the file
:param int mode: POSIX mode to test
:rtype: bool
:return: True if the POSIX mode matches the file permissions
"""
if POSIX_MODE:
return stat.S_IMODE(os.stat(file_path).st_mode) == mode
return _check_win_mode(file_path, mode) |
Check if given file is owned by current user.
:param str file_path: File path to check
:rtype: bool
:return: True if given file is owned by current user, False otherwise. | def check_owner(file_path: str) -> bool:
"""
Check if given file is owned by current user.
:param str file_path: File path to check
:rtype: bool
:return: True if given file is owned by current user, False otherwise.
"""
if POSIX_MODE:
return os.stat(file_path).st_uid == os.getuid()
# Get owner sid of the file
security = win32security.GetFileSecurity(file_path, win32security.OWNER_SECURITY_INFORMATION)
user = security.GetSecurityDescriptorOwner()
# Compare sids
return _get_current_user() == user |
Check if given file has the given mode and is owned by current user.
:param str file_path: File path to check
:param int mode: POSIX mode to check
:rtype: bool
:return: True if file has correct mode and owner, False otherwise. | def check_permissions(file_path: str, mode: int) -> bool:
"""
Check if given file has the given mode and is owned by current user.
:param str file_path: File path to check
:param int mode: POSIX mode to check
:rtype: bool
:return: True if file has correct mode and owner, False otherwise.
"""
return check_owner(file_path) and check_mode(file_path, mode) |
Wrapper of original os.open function, that will ensure on Windows that given mode
is correctly applied.
:param str file_path: The file path to open
:param int flags: Flags to apply on file while opened
:param int mode: POSIX mode to apply on file when opened,
Python defaults will be applied if ``None``
:returns: the file descriptor to the opened file
:rtype: int
:raise: OSError(errno.EEXIST) if the file already exists and os.O_CREAT & os.O_EXCL are set,
OSError(errno.EACCES) on Windows if the file already exists and is a directory, and
os.O_CREAT is set. | def open(file_path: str, flags: int, mode: int = 0o777) -> int: # pylint: disable=redefined-builtin
"""
Wrapper of original os.open function, that will ensure on Windows that given mode
is correctly applied.
:param str file_path: The file path to open
:param int flags: Flags to apply on file while opened
:param int mode: POSIX mode to apply on file when opened,
Python defaults will be applied if ``None``
:returns: the file descriptor to the opened file
:rtype: int
:raise: OSError(errno.EEXIST) if the file already exists and os.O_CREAT & os.O_EXCL are set,
OSError(errno.EACCES) on Windows if the file already exists and is a directory, and
os.O_CREAT is set.
"""
if POSIX_MODE:
# On Linux, invoke os.open directly.
return os.open(file_path, flags, mode)
# Windows: handle creation of the file atomically with proper permissions.
if flags & os.O_CREAT:
# If os.O_EXCL is set, we will use the "CREATE_NEW", that will raise an exception if
# file exists, matching the API contract of this bit flag. Otherwise, we use
# "CREATE_ALWAYS" that will always create the file whether it exists or not.
disposition = win32con.CREATE_NEW if flags & os.O_EXCL else win32con.CREATE_ALWAYS
attributes = win32security.SECURITY_ATTRIBUTES()
security = attributes.SECURITY_DESCRIPTOR
user = _get_current_user()
dacl = _generate_dacl(user, mode, _WINDOWS_UMASK.mask)
# We set second parameter to 0 (`False`) to say that this security descriptor is
# NOT constructed from a default mechanism, but is explicitly set by the user.
# See https://docs.microsoft.com/en-us/windows/desktop/api/securitybaseapi/nf-securitybaseapi-setsecuritydescriptorowner # pylint: disable=line-too-long
security.SetSecurityDescriptorOwner(user, 0)
# We set first parameter to 1 (`True`) to say that this security descriptor contains
# a DACL. Otherwise second and third parameters are ignored.
# We set third parameter to 0 (`False`) to say that this security descriptor is
# NOT constructed from a default mechanism, but is explicitly set by the user.
# See https://docs.microsoft.com/en-us/windows/desktop/api/securitybaseapi/nf-securitybaseapi-setsecuritydescriptordacl # pylint: disable=line-too-long
security.SetSecurityDescriptorDacl(1, dacl, 0)
handle = None
try:
handle = win32file.CreateFile(file_path, win32file.GENERIC_READ,
win32file.FILE_SHARE_READ & win32file.FILE_SHARE_WRITE,
attributes, disposition, 0, None)
except pywintypes.error as err:
# Handle native windows errors into python errors to be consistent with the API
# of os.open in the situation of a file already existing or locked.
if err.winerror == winerror.ERROR_FILE_EXISTS:
raise OSError(errno.EEXIST, err.strerror)
if err.winerror == winerror.ERROR_SHARING_VIOLATION:
raise OSError(errno.EACCES, err.strerror)
raise err
finally:
if handle:
handle.Close()
# At this point, the file that did not exist has been created with proper permissions,
# so os.O_CREAT and os.O_EXCL are not needed anymore. We remove them from the flags to
# avoid a FileExists exception before calling os.open.
return os.open(file_path, flags ^ os.O_CREAT ^ os.O_EXCL)
# Windows: general case, we call os.open, let exceptions be thrown, then chmod if all is fine.
fd = os.open(file_path, flags)
chmod(file_path, mode)
return fd |
Rewrite of original os.makedirs function, that will ensure on Windows that given mode
is correctly applied.
:param str file_path: The file path to open
:param int mode: POSIX mode to apply on leaf directory when created, Python defaults
will be applied if ``None`` | def makedirs(file_path: str, mode: int = 0o777) -> None:
"""
Rewrite of original os.makedirs function, that will ensure on Windows that given mode
is correctly applied.
:param str file_path: The file path to open
:param int mode: POSIX mode to apply on leaf directory when created, Python defaults
will be applied if ``None``
"""
current_umask = umask(0)
try:
# Since Python 3.7, os.makedirs does not set the given mode to the intermediate
# directories that could be created in the process. To keep things safe and consistent
# on all Python versions, we set the umask accordingly to have all directories
# (intermediate and leaf) created with the given mode.
umask(current_umask | 0o777 ^ mode)
if POSIX_MODE:
return os.makedirs(file_path, mode)
orig_mkdir_fn = os.mkdir
try:
# As we know that os.mkdir is called internally by os.makedirs, we will swap the
# function in os module for the time of makedirs execution on Windows.
os.mkdir = mkdir # type: ignore
return os.makedirs(file_path, mode)
finally:
os.mkdir = orig_mkdir_fn
finally:
umask(current_umask) |
Rewrite of original os.mkdir function, that will ensure on Windows that given mode
is correctly applied.
:param str file_path: The file path to open
:param int mode: POSIX mode to apply on directory when created, Python defaults
will be applied if ``None`` | def mkdir(file_path: str, mode: int = 0o777) -> None:
"""
Rewrite of original os.mkdir function, that will ensure on Windows that given mode
is correctly applied.
:param str file_path: The file path to open
:param int mode: POSIX mode to apply on directory when created, Python defaults
will be applied if ``None``
"""
if POSIX_MODE:
return os.mkdir(file_path, mode)
attributes = win32security.SECURITY_ATTRIBUTES()
security = attributes.SECURITY_DESCRIPTOR
user = _get_current_user()
dacl = _generate_dacl(user, mode, _WINDOWS_UMASK.mask)
security.SetSecurityDescriptorOwner(user, False)
security.SetSecurityDescriptorDacl(1, dacl, 0)
try:
win32file.CreateDirectory(file_path, attributes)
except pywintypes.error as err:
# Handle native windows error into python error to be consistent with the API
# of os.mkdir in the situation of a directory already existing.
if err.winerror == winerror.ERROR_ALREADY_EXISTS:
raise OSError(errno.EEXIST, err.strerror, file_path, err.winerror)
raise err
return None |
Rename a file to a destination path and handles situations where the destination exists.
:param str src: The current file path.
:param str dst: The new file path. | def replace(src: str, dst: str) -> None:
"""
Rename a file to a destination path and handles situations where the destination exists.
:param str src: The current file path.
:param str dst: The new file path.
"""
if hasattr(os, 'replace'):
# Use replace if possible. Since we don't support Python 2 on Windows
# and os.replace() was added in Python 3.3, we can assume that
# os.replace() is always available on Windows.
getattr(os, 'replace')(src, dst)
else:
# Otherwise, use os.rename() that behaves like os.replace() on Linux.
os.rename(src, dst) |
Find the real path for the given path. This method resolves symlinks, including
recursive symlinks, and is protected against symlinks that creates an infinite loop.
:param str file_path: The path to resolve
:returns: The real path for the given path
:rtype: str | def realpath(file_path: str) -> str:
"""
Find the real path for the given path. This method resolves symlinks, including
recursive symlinks, and is protected against symlinks that creates an infinite loop.
:param str file_path: The path to resolve
:returns: The real path for the given path
:rtype: str
"""
original_path = file_path
# Since Python 3.8, os.path.realpath also resolves symlinks on Windows.
if POSIX_MODE or sys.version_info >= (3, 8):
path = os.path.realpath(file_path)
if os.path.islink(path):
# If path returned by realpath is still a link, it means that it failed to
# resolve the symlink because of a loop.
# See realpath code: https://github.com/python/cpython/blob/master/Lib/posixpath.py
raise RuntimeError('Error, link {0} is a loop!'.format(original_path))
return path
inspected_paths: List[str] = []
while os.path.islink(file_path):
link_path = file_path
file_path = os.readlink(file_path)
if not os.path.isabs(file_path):
file_path = os.path.join(os.path.dirname(link_path), file_path)
if file_path in inspected_paths:
raise RuntimeError('Error, link {0} is a loop!'.format(original_path))
inspected_paths.append(file_path)
return os.path.abspath(file_path) |
Return a string representing the path to which the symbolic link points.
:param str link_path: The symlink path to resolve
:return: The path the symlink points to
:returns: str
:raise: ValueError if a long path (260> characters) is encountered on Windows | def readlink(link_path: str) -> str:
"""
Return a string representing the path to which the symbolic link points.
:param str link_path: The symlink path to resolve
:return: The path the symlink points to
:returns: str
:raise: ValueError if a long path (260> characters) is encountered on Windows
"""
path = os.readlink(link_path)
if POSIX_MODE or not path.startswith('\\\\?\\'):
return path
# At this point, we know we are on Windows and that the path returned uses
# the extended form which is done for all paths in Python 3.8+
# Max length of a normal path is 260 characters on Windows, including the non printable
# termination character "<NUL>". The termination character is not included in Python
# strings, giving a max length of 259 characters, + 4 characters for the extended form
# prefix, to an effective max length 263 characters on a string representing a normal path.
if len(path) < 264:
return path[4:]
raise ValueError("Long paths are not supported by Certbot on Windows.") |
Is path an executable file?
:param str path: path to test
:return: True if path is an executable file
:rtype: bool | def is_executable(path: str) -> bool:
"""
Is path an executable file?
:param str path: path to test
:return: True if path is an executable file
:rtype: bool
"""
if POSIX_MODE:
return os.path.isfile(path) and os.access(path, os.X_OK)
return _win_is_executable(path) |
Check if everybody/world has any right (read/write/execute) on a file given its path.
:param str path: path to test
:return: True if everybody/world has any right to the file
:rtype: bool | def has_world_permissions(path: str) -> bool:
"""
Check if everybody/world has any right (read/write/execute) on a file given its path.
:param str path: path to test
:return: True if everybody/world has any right to the file
:rtype: bool
"""
if POSIX_MODE:
return bool(stat.S_IMODE(os.stat(path).st_mode) & stat.S_IRWXO)
security = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
dacl = security.GetSecurityDescriptorDacl()
return bool(dacl.GetEffectiveRightsFromAcl({
'TrusteeForm': win32security.TRUSTEE_IS_SID,
'TrusteeType': win32security.TRUSTEE_IS_USER,
'Identifier': win32security.ConvertStringSidToSid('S-1-1-0'),
})) |
Calculate the POSIX mode to apply to a private key given the previous private key.
:param str old_key: path to the previous private key
:param int base_mode: the minimum modes to apply to a private key
:return: the POSIX mode to apply
:rtype: int | def compute_private_key_mode(old_key: str, base_mode: int) -> int:
"""
Calculate the POSIX mode to apply to a private key given the previous private key.
:param str old_key: path to the previous private key
:param int base_mode: the minimum modes to apply to a private key
:return: the POSIX mode to apply
:rtype: int
"""
if POSIX_MODE:
# On Linux, we keep read/write/execute permissions
# for group and read permissions for everybody.
old_mode = (stat.S_IMODE(os.stat(old_key).st_mode) &
(stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH))
return base_mode | old_mode
# On Windows, the mode returned by os.stat is not reliable,
# so we do not keep any permission from the previous private key.
return base_mode |
Return True if the ownership of two files given their respective path is the same.
On Windows, ownership is checked against owner only, since files do not have a group owner.
:param str path1: path to the first file
:param str path2: path to the second file
:return: True if both files have the same ownership, False otherwise
:rtype: bool | def has_same_ownership(path1: str, path2: str) -> bool:
"""
Return True if the ownership of two files given their respective path is the same.
On Windows, ownership is checked against owner only, since files do not have a group owner.
:param str path1: path to the first file
:param str path2: path to the second file
:return: True if both files have the same ownership, False otherwise
:rtype: bool
"""
if POSIX_MODE:
stats1 = os.stat(path1)
stats2 = os.stat(path2)
return (stats1.st_uid, stats1.st_gid) == (stats2.st_uid, stats2.st_gid)
security1 = win32security.GetFileSecurity(path1, win32security.OWNER_SECURITY_INFORMATION)
user1 = security1.GetSecurityDescriptorOwner()
security2 = win32security.GetFileSecurity(path2, win32security.OWNER_SECURITY_INFORMATION)
user2 = security2.GetSecurityDescriptorOwner()
return user1 == user2 |
Check if a file given its path has at least the permissions defined by the given minimal mode.
On Windows, group permissions are ignored since files do not have a group owner.
:param str path: path to the file to check
:param int min_mode: the minimal permissions expected
:return: True if the file matches the minimal permissions expectations, False otherwise
:rtype: bool | def has_min_permissions(path: str, min_mode: int) -> bool:
"""
Check if a file given its path has at least the permissions defined by the given minimal mode.
On Windows, group permissions are ignored since files do not have a group owner.
:param str path: path to the file to check
:param int min_mode: the minimal permissions expected
:return: True if the file matches the minimal permissions expectations, False otherwise
:rtype: bool
"""
if POSIX_MODE:
st_mode = os.stat(path).st_mode
return st_mode == st_mode | min_mode
# Resolve symlinks, to get a consistent result with os.stat on Linux,
# that follows symlinks by default.
path = realpath(path)
# Get owner sid of the file
security = win32security.GetFileSecurity(
path, win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION)
user = security.GetSecurityDescriptorOwner()
dacl = security.GetSecurityDescriptorDacl()
min_dacl = _generate_dacl(user, min_mode)
for index in range(min_dacl.GetAceCount()):
min_ace = min_dacl.GetAce(index)
# On a given ACE, index 0 is the ACE type, 1 is the permission mask, and 2 is the SID.
# See: http://timgolden.me.uk/pywin32-docs/PyACL__GetAce_meth.html
mask = min_ace[1]
user = min_ace[2]
effective_mask = dacl.GetEffectiveRightsFromAcl({
'TrusteeForm': win32security.TRUSTEE_IS_SID,
'TrusteeType': win32security.TRUSTEE_IS_USER,
'Identifier': user,
})
if effective_mask != effective_mask | mask:
return False
return True |
This function converts the given POSIX mode into a Windows ACL list, and applies it to the
file given its path. If the given path is a symbolic link, it will resolved to apply the
mode on the targeted file. | def _apply_win_mode(file_path: str, mode: int) -> None:
"""
This function converts the given POSIX mode into a Windows ACL list, and applies it to the
file given its path. If the given path is a symbolic link, it will resolved to apply the
mode on the targeted file.
"""
file_path = realpath(file_path)
# Get owner sid of the file
security = win32security.GetFileSecurity(file_path, win32security.OWNER_SECURITY_INFORMATION)
user = security.GetSecurityDescriptorOwner()
# New DACL, that will overwrite existing one (including inherited permissions)
dacl = _generate_dacl(user, mode)
# Apply the new DACL
security.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetFileSecurity(file_path, win32security.DACL_SECURITY_INFORMATION, security) |
This method compare the two given DACLs to check if they are identical.
Identical means here that they contains the same set of ACEs in the same order. | def _compare_dacls(dacl1: Any, dacl2: Any) -> bool:
"""
This method compare the two given DACLs to check if they are identical.
Identical means here that they contains the same set of ACEs in the same order.
"""
return ([dacl1.GetAce(index) for index in range(dacl1.GetAceCount())] ==
[dacl2.GetAce(index) for index in range(dacl2.GetAceCount())]) |
Return the pySID corresponding to the current user. | def _get_current_user() -> Any:
"""
Return the pySID corresponding to the current user.
"""
# We craft the account_name ourselves instead of calling for instance win32api.GetUserNameEx,
# because this function returns nonsense values when Certbot is run under NT AUTHORITY\SYSTEM.
# To run Certbot under NT AUTHORITY\SYSTEM, you can open a shell using the instructions here:
# https://blogs.technet.microsoft.com/ben_parker/2010/10/27/how-do-i-run-powershell-execommand-prompt-as-the-localsystem-account-on-windows-7/
account_name = r"{0}\{1}".format(win32api.GetDomainName(), win32api.GetUserName())
# LookupAccountName() expects the system name as first parameter. By passing None to it,
# we instruct Windows to first search the matching account in the machine local accounts,
# then into the primary domain accounts, if the machine has joined a domain, then finally
# into the trusted domains accounts. This is the preferred lookup mechanism to use in Windows
# if there is no reason to use a specific lookup mechanism.
# See https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-lookupaccountnamea
return win32security.LookupAccountName(None, account_name)[0] |
On Windows, raise if current shell does not have the administrative rights.
Do nothing on Linux.
:raises .errors.Error: If the current shell does not have administrative rights on Windows. | def raise_for_non_administrative_windows_rights() -> None:
"""
On Windows, raise if current shell does not have the administrative rights.
Do nothing on Linux.
:raises .errors.Error: If the current shell does not have administrative rights on Windows.
"""
if not POSIX_MODE and shellwin32.IsUserAnAdmin() == 0: # pragma: no cover
raise errors.Error('Error, certbot must be run on a shell with administrative rights.') |
On Windows, ensure that Console Virtual Terminal Sequences are enabled. | def prepare_virtual_console() -> None:
"""
On Windows, ensure that Console Virtual Terminal Sequences are enabled.
"""
if POSIX_MODE:
return
# https://docs.microsoft.com/en-us/windows/console/setconsolemode
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
# stdout/stderr will be the same console screen buffer, but this could return None or raise
try:
h = GetStdHandle(STD_OUTPUT_HANDLE)
if h:
h.SetConsoleMode(h.GetConsoleMode() | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
except pywinerror:
logger.debug("Failed to set console mode", exc_info=True) |
Read user input to return the first line entered, or raise after specified timeout.
:param float timeout: The timeout in seconds given to the user.
:param str prompt: The prompt message to display to the user.
:returns: The first line entered by the user.
:rtype: str | def readline_with_timeout(timeout: float, prompt: Optional[str]) -> str:
"""
Read user input to return the first line entered, or raise after specified timeout.
:param float timeout: The timeout in seconds given to the user.
:param str prompt: The prompt message to display to the user.
:returns: The first line entered by the user.
:rtype: str
"""
try:
# Linux specific
#
# Call to select can only be done like this on UNIX
rlist, _, _ = select.select([sys.stdin], [], [], timeout)
if not rlist:
raise errors.Error(
"Timed out waiting for answer to prompt '{0}'".format(prompt if prompt else ""))
return rlist[0].readline()
except OSError:
# Windows specific
#
# No way with select to make a timeout to the user input on Windows,
# as select only supports socket in this case.
# So no timeout on Windows for now.
return sys.stdin.readline() |
Return the relevant default folder for the current OS
:param str folder_type: The type of folder to retrieve (config, work or logs)
:returns: The relevant default folder.
:rtype: str | def get_default_folder(folder_type: str) -> str:
"""
Return the relevant default folder for the current OS
:param str folder_type: The type of folder to retrieve (config, work or logs)
:returns: The relevant default folder.
:rtype: str
"""
if os.name != 'nt':
# Linux specific
return LINUX_DEFAULT_FOLDERS[folder_type]
# Windows specific
return WINDOWS_DEFAULT_FOLDERS[folder_type] |
Replace unsupported characters in path for current OS by underscores.
:param str path: the path to normalize
:return: the normalized path
:rtype: str | def underscores_for_unsupported_characters_in_path(path: str) -> str:
"""
Replace unsupported characters in path for current OS by underscores.
:param str path: the path to normalize
:return: the normalized path
:rtype: str
"""
if os.name != 'nt':
# Linux specific
return path
# Windows specific
drive, tail = os.path.splitdrive(path)
return drive + tail.replace(':', '_') |
Run a command:
- on Linux command will be run by the standard shell selected with
subprocess.run(shell=True)
- on Windows command will be run in a Powershell shell
This function returns the exit code, and does not log the result and output
of the command.
:param str cmd_name: the user facing name of the hook being run
:param str shell_cmd: shell command to execute
:param dict env: environ to pass into subprocess.run
:returns: `tuple` (`int` returncode, `str` stderr, `str` stdout) | def execute_command_status(cmd_name: str, shell_cmd: str,
env: Optional[dict] = None) -> Tuple[int, str, str]:
"""
Run a command:
- on Linux command will be run by the standard shell selected with
subprocess.run(shell=True)
- on Windows command will be run in a Powershell shell
This function returns the exit code, and does not log the result and output
of the command.
:param str cmd_name: the user facing name of the hook being run
:param str shell_cmd: shell command to execute
:param dict env: environ to pass into subprocess.run
:returns: `tuple` (`int` returncode, `str` stderr, `str` stdout)
"""
logger.info("Running %s command: %s", cmd_name, shell_cmd)
if POSIX_MODE:
proc = subprocess.run(shell_cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, universal_newlines=True,
check=False, env=env)
else:
line = ['powershell.exe', '-Command', shell_cmd]
proc = subprocess.run(line, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True, check=False, env=env)
# universal_newlines causes stdout and stderr to be str objects instead of
# bytes in Python 3
out, err = proc.stdout, proc.stderr
return proc.returncode, err, out |
Method os.chmod() is forbidden | def chmod(*unused_args, **unused_kwargs): # type: ignore
"""Method os.chmod() is forbidden"""
raise RuntimeError('Usage of os.chmod() is forbidden. '
'Use certbot.compat.filesystem.chmod() instead.') |
Method os.chmod() is forbidden | def umask(*unused_args, **unused_kwargs): # type: ignore
"""Method os.chmod() is forbidden"""
raise RuntimeError('Usage of os.umask() is forbidden. '
'Use certbot.compat.filesystem.umask() instead.') |
Method os.chown() is forbidden | def chown(*unused_args, **unused_kwargs): # type: ignore
"""Method os.chown() is forbidden"""
raise RuntimeError('Usage of os.chown() is forbidden.'
'Use certbot.compat.filesystem.copy_ownership_and_apply_mode() instead.') |
Method os.open() is forbidden | def open(*unused_args, **unused_kwargs): # type: ignore
"""Method os.open() is forbidden"""
raise RuntimeError('Usage of os.open() is forbidden. '
'Use certbot.compat.filesystem.open() instead.') |
Method os.mkdir() is forbidden | def mkdir(*unused_args, **unused_kwargs): # type: ignore
"""Method os.mkdir() is forbidden"""
raise RuntimeError('Usage of os.mkdir() is forbidden. '
'Use certbot.compat.filesystem.mkdir() instead.') |
Method os.makedirs() is forbidden | def makedirs(*unused_args, **unused_kwargs): # type: ignore
"""Method os.makedirs() is forbidden"""
raise RuntimeError('Usage of os.makedirs() is forbidden. '
'Use certbot.compat.filesystem.makedirs() instead.') |
Method os.rename() is forbidden | def rename(*unused_args, **unused_kwargs): # type: ignore
"""Method os.rename() is forbidden"""
raise RuntimeError('Usage of os.rename() is forbidden. '
'Use certbot.compat.filesystem.replace() instead.') |
Method os.replace() is forbidden | def replace(*unused_args, **unused_kwargs): # type: ignore
"""Method os.replace() is forbidden"""
raise RuntimeError('Usage of os.replace() is forbidden. '
'Use certbot.compat.filesystem.replace() instead.') |
Method os.access() is forbidden | def access(*unused_args, **unused_kwargs): # type: ignore
"""Method os.access() is forbidden"""
raise RuntimeError('Usage of os.access() is forbidden. '
'Use certbot.compat.filesystem.check_mode() or '
'certbot.compat.filesystem.is_executable() instead.') |
Method os.stat() is forbidden | def stat(*unused_args, **unused_kwargs): # type: ignore
"""Method os.stat() is forbidden"""
raise RuntimeError('Usage of os.stat() is forbidden. '
'Use certbot.compat.filesystem functions instead '
'(eg. has_min_permissions, has_same_ownership).') |
Method os.stat() is forbidden | def fstat(*unused_args, **unused_kwargs): # type: ignore
"""Method os.stat() is forbidden"""
raise RuntimeError('Usage of os.fstat() is forbidden. '
'Use certbot.compat.filesystem functions instead '
'(eg. has_min_permissions, has_same_ownership).') |
Method os.readlink() is forbidden | def readlink(*unused_args, **unused_kwargs): # type: ignore
"""Method os.readlink() is forbidden"""
raise RuntimeError('Usage of os.readlink() is forbidden. '
'Use certbot.compat.filesystem.realpath() instead.') |
Method os.path.realpath() is forbidden | def realpath(*unused_args, **unused_kwargs): # type: ignore
"""Method os.path.realpath() is forbidden"""
raise RuntimeError('Usage of os.path.realpath() is forbidden. '
'Use certbot.compat.filesystem.realpath() instead.') |
Prompt for valid email address.
:param bool invalid: True if an invalid address was provided by the user
:param bool optional: True if the user can use
--register-unsafely-without-email to avoid providing an e-mail
:returns: e-mail address
:rtype: str
:raises errors.Error: if the user cancels | def get_email(invalid: bool = False, optional: bool = True) -> str:
"""Prompt for valid email address.
:param bool invalid: True if an invalid address was provided by the user
:param bool optional: True if the user can use
--register-unsafely-without-email to avoid providing an e-mail
:returns: e-mail address
:rtype: str
:raises errors.Error: if the user cancels
"""
invalid_prefix = "There seem to be problems with that address. "
msg = "Enter email address (used for urgent renewal and security notices)\n"
unsafe_suggestion = ("\n\nIf you really want to skip this, you can run "
"the client with --register-unsafely-without-email "
"but you will then be unable to receive notice about "
"impending expiration or revocation of your "
"certificates or problems with your Certbot "
"installation that will lead to failure to renew.\n\n")
if optional:
if invalid:
msg += unsafe_suggestion
suggest_unsafe = False
else:
suggest_unsafe = True
else:
suggest_unsafe = False
while True:
try:
code, email = display_util.input_text(invalid_prefix + msg if invalid else msg,
force_interactive=True)
except errors.MissingCommandlineFlag:
msg = ("You should register before running non-interactively, "
"or provide --agree-tos and --email <email_address> flags.")
raise errors.MissingCommandlineFlag(msg)
if code != display_util.OK:
if optional:
raise errors.Error(
"An e-mail address or "
"--register-unsafely-without-email must be provided.")
raise errors.Error("An e-mail address must be provided.")
if util.safe_email(email):
return email
if suggest_unsafe:
msg = unsafe_suggestion + msg
suggest_unsafe = False # add this message at most once
invalid = bool(email) |
Choose an account.
:param list accounts: Containing at least one
:class:`~certbot._internal.account.Account` | def choose_account(accounts: List[account.Account]) -> Optional[account.Account]:
"""Choose an account.
:param list accounts: Containing at least one
:class:`~certbot._internal.account.Account`
"""
# Note this will get more complicated once we start recording authorizations
labels = [acc.slug for acc in accounts]
code, index = display_util.menu("Please choose an account", labels, force_interactive=True)
if code == display_util.OK:
return accounts[index]
return None |
Display screen to let user pick one or multiple values from the provided
list.
:param list values: Values to select from
:param str question: Question to ask to user while choosing values
:returns: List of selected values
:rtype: list | def choose_values(values: List[str], question: Optional[str] = None) -> List[str]:
"""Display screen to let user pick one or multiple values from the provided
list.
:param list values: Values to select from
:param str question: Question to ask to user while choosing values
:returns: List of selected values
:rtype: list
"""
code, items = display_util.checklist(question if question else "", tags=values,
force_interactive=True)
if code == display_util.OK and items:
return items
return [] |
Display screen to select domains to validate.
:param installer: An installer object
:type installer: :class:`certbot.interfaces.Installer`
:param `str` question: Overriding default question to ask the user if asked
to choose from domain names.
:returns: List of selected names
:rtype: `list` of `str` | def choose_names(installer: Optional[interfaces.Installer],
question: Optional[str] = None) -> List[str]:
"""Display screen to select domains to validate.
:param installer: An installer object
:type installer: :class:`certbot.interfaces.Installer`
:param `str` question: Overriding default question to ask the user if asked
to choose from domain names.
:returns: List of selected names
:rtype: `list` of `str`
"""
if installer is None:
logger.debug("No installer, picking names manually")
return _choose_names_manually()
domains = list(installer.get_all_names())
names = get_valid_domains(domains)
if not names:
return _choose_names_manually()
code, names = _filter_names(names, question)
if code == display_util.OK and names:
return names
return [] |
Helper method for choose_names that implements basic checks
on domain names
:param list domains: Domain names to validate
:return: List of valid domains
:rtype: list | def get_valid_domains(domains: Iterable[str]) -> List[str]:
"""Helper method for choose_names that implements basic checks
on domain names
:param list domains: Domain names to validate
:return: List of valid domains
:rtype: list
"""
valid_domains: List[str] = []
for domain in domains:
try:
valid_domains.append(util.enforce_domain_sanity(domain))
except errors.ConfigurationError:
continue
return valid_domains |
Sort FQDNs by SLD (and if many, by their subdomains)
:param list FQDNs: list of domain names
:returns: Sorted list of domain names
:rtype: list | def _sort_names(FQDNs: Iterable[str]) -> List[str]:
"""Sort FQDNs by SLD (and if many, by their subdomains)
:param list FQDNs: list of domain names
:returns: Sorted list of domain names
:rtype: list
"""
return sorted(FQDNs, key=lambda fqdn: fqdn.split('.')[::-1][1:]) |
Determine which names the user would like to select from a list.
:param list names: domain names
:returns: tuple of the form (`code`, `names`) where
`code` - str display exit code
`names` - list of names selected
:rtype: tuple | def _filter_names(names: Iterable[str],
override_question: Optional[str] = None) -> Tuple[str, List[str]]:
"""Determine which names the user would like to select from a list.
:param list names: domain names
:returns: tuple of the form (`code`, `names`) where
`code` - str display exit code
`names` - list of names selected
:rtype: tuple
"""
# Sort by domain first, and then by subdomain
sorted_names = _sort_names(names)
if override_question:
question = override_question
else:
question = (
"Which names would you like to activate HTTPS for?\n"
"We recommend selecting either all domains, or all domains in a VirtualHost/server "
"block.")
code, names = display_util.checklist(
question, tags=sorted_names, cli_flag="--domains", force_interactive=True)
return code, [str(s) for s in names] |
Manually input names for those without an installer.
:param str prompt_prefix: string to prepend to prompt for domains
:returns: list of provided names
:rtype: `list` of `str` | def _choose_names_manually(prompt_prefix: str = "") -> List[str]:
"""Manually input names for those without an installer.
:param str prompt_prefix: string to prepend to prompt for domains
:returns: list of provided names
:rtype: `list` of `str`
"""
code, input_ = display_util.input_text(
prompt_prefix +
"Please enter the domain name(s) you would like on your certificate "
"(comma and/or space separated)",
cli_flag="--domains", force_interactive=True)
if code == display_util.OK:
invalid_domains = {}
retry_message = ""
try:
domain_list = internal_display_util.separate_list_input(input_)
except UnicodeEncodeError:
domain_list = []
retry_message = (
"Internationalized domain names are not presently "
"supported.{0}{0}Would you like to re-enter the "
"names?{0}").format(os.linesep)
for i, domain in enumerate(domain_list):
try:
domain_list[i] = util.enforce_domain_sanity(domain)
except errors.ConfigurationError as e:
invalid_domains[domain] = str(e)
if invalid_domains:
retry_message = (
"One or more of the entered domain names was not valid:"
"{0}{0}").format(os.linesep)
for invalid_domain, err in invalid_domains.items():
retry_message = retry_message + "{1}: {2}{0}".format(
os.linesep, invalid_domain, err)
retry_message = retry_message + (
"{0}Would you like to re-enter the names?{0}").format(
os.linesep)
if retry_message:
# We had error in input
retry = display_util.yesno(retry_message, force_interactive=True)
if retry:
return _choose_names_manually()
else:
return domain_list
return [] |
Display a box confirming the installation of HTTPS.
:param list domains: domain names which were enabled | def success_installation(domains: List[str]) -> None:
"""Display a box confirming the installation of HTTPS.
:param list domains: domain names which were enabled
"""
display_util.notify(
"Congratulations! You have successfully enabled HTTPS on {0}"
.format(_gen_https_names(domains))
) |
Display a box confirming the renewal of an existing certificate.
:param list domains: domain names which were renewed | def success_renewal(unused_domains: List[str]) -> None:
"""Display a box confirming the renewal of an existing certificate.
:param list domains: domain names which were renewed
"""
display_util.notify(
"Your existing certificate has been successfully renewed, and the "
"new certificate has been installed."
) |
Display a message confirming a certificate has been revoked.
:param list cert_path: path to certificate which was revoked. | def success_revocation(cert_path: str) -> None:
"""Display a message confirming a certificate has been revoked.
:param list cert_path: path to certificate which was revoked.
"""
display_util.notify(
"Congratulations! You have successfully revoked the certificate "
"that was located at {0}.".format(cert_path)
) |
Display a message describing the success or failure of an executed process (e.g. hook).
:param str command_name: Human-readable description of the executed command
:param int returncode: The exit code of the executed command
:param str stdout: The stdout output of the executed command
:param str stderr: The stderr output of the executed command | def report_executed_command(command_name: str, returncode: int, stdout: str, stderr: str) -> None:
"""Display a message describing the success or failure of an executed process (e.g. hook).
:param str command_name: Human-readable description of the executed command
:param int returncode: The exit code of the executed command
:param str stdout: The stdout output of the executed command
:param str stderr: The stderr output of the executed command
"""
out_s, err_s = stdout.strip(), stderr.strip()
if returncode != 0:
logger.warning("%s reported error code %d", command_name, returncode)
if out_s:
display_util.notify(f"{command_name} ran with output:\n{indent(out_s, ' ')}")
if err_s:
logger.warning("%s ran with error output:\n%s", command_name, indent(err_s, ' ')) |
Returns a string of the https domains.
Domains are formatted nicely with ``https://`` prepended to each.
:param list domains: Each domain is a 'str' | def _gen_https_names(domains: List[str]) -> str:
"""Returns a string of the https domains.
Domains are formatted nicely with ``https://`` prepended to each.
:param list domains: Each domain is a 'str'
"""
if len(domains) == 1:
return "https://{0}".format(domains[0])
elif len(domains) == 2:
return "https://{dom[0]} and https://{dom[1]}".format(dom=domains)
elif len(domains) > 2:
return "{0}{1}{2}".format(
", ".join("https://%s" % dom for dom in domains[:-1]),
", and https://",
domains[-1])
return "" |
Like `~certbot.display.util.input_text`, but with validation.
:param callable validator: 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.
:param list `*args`: Arguments to be passed to `~certbot.display.util.input_text`.
:param dict `**kwargs`: Arguments to be passed to `~certbot.display.util.input_text`.
:return: as `~certbot.display.util.input_text`
:rtype: tuple | def validated_input(validator: Callable[[str], Any],
*args: Any, **kwargs: Any) -> Tuple[str, str]:
"""Like `~certbot.display.util.input_text`, but with validation.
:param callable validator: 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.
:param list `*args`: Arguments to be passed to `~certbot.display.util.input_text`.
:param dict `**kwargs`: Arguments to be passed to `~certbot.display.util.input_text`.
:return: as `~certbot.display.util.input_text`
:rtype: tuple
"""
return _get_validated(display_util.input_text, validator, *args, **kwargs) |
Like `~certbot.display.util.directory_select`, but with validation.
:param callable validator: 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.
:param list `*args`: Arguments to be passed to `~certbot.display.util.directory_select`.
:param dict `**kwargs`: Arguments to be passed to
`~certbot.display.util.directory_select`.
:return: as `~certbot.display.util.directory_select`
:rtype: tuple | def validated_directory(validator: Callable[[str], Any],
*args: Any, **kwargs: Any) -> Tuple[str, str]:
"""Like `~certbot.display.util.directory_select`, but with validation.
:param callable validator: 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.
:param list `*args`: Arguments to be passed to `~certbot.display.util.directory_select`.
:param dict `**kwargs`: Arguments to be passed to
`~certbot.display.util.directory_select`.
:return: as `~certbot.display.util.directory_select`
:rtype: tuple
"""
return _get_validated(display_util.directory_select, validator, *args, **kwargs) |
Display a basic status message.
:param str msg: message to display | def notify(msg: str) -> None:
"""Display a basic status message.
:param str msg: message to display
"""
obj.get_display().notification(msg, pause=False, decorate=False, wrap=False) |
Displays a notification and waits for user acceptance.
:param str message: Message to display
:param bool pause: Whether or not the program should pause for the
user's confirmation
:param bool wrap: Whether or not the application should wrap text
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:param bool decorate: Whether to surround the message with a
decorated frame | def notification(message: str, pause: bool = True, wrap: bool = True,
force_interactive: bool = False, decorate: bool = True) -> None:
"""Displays a notification and waits for user acceptance.
:param str message: Message to display
:param bool pause: Whether or not the program should pause for the
user's confirmation
:param bool wrap: Whether or not the application should wrap text
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:param bool decorate: Whether to surround the message with a
decorated frame
"""
obj.get_display().notification(message, pause=pause, wrap=wrap,
force_interactive=force_interactive, decorate=decorate) |
Display a menu.
.. todo:: This doesn't enable the help label/button (I wasn't sold on
any interface I came up with for this). It would be a nice feature.
:param str message: title of menu
:param choices: Menu lines, len must be > 0
:type choices: list of tuples (tag, item) or
list of descriptions (tags will be enumerated)
:param default: default value to return, if interaction is not possible
:param str cli_flag: option used to set this value with the CLI
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:returns: tuple of (`code`, `index`) where
`code` - str display exit code
`index` - int index of the user's selection
:rtype: tuple | def menu(message: str, choices: Union[List[str], List[Tuple[str, str]]],
default: Optional[int] = None, cli_flag: Optional[str] = None,
force_interactive: bool = False) -> Tuple[str, int]:
"""Display a menu.
.. todo:: This doesn't enable the help label/button (I wasn't sold on
any interface I came up with for this). It would be a nice feature.
:param str message: title of menu
:param choices: Menu lines, len must be > 0
:type choices: list of tuples (tag, item) or
list of descriptions (tags will be enumerated)
:param default: default value to return, if interaction is not possible
:param str cli_flag: option used to set this value with the CLI
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:returns: tuple of (`code`, `index`) where
`code` - str display exit code
`index` - int index of the user's selection
:rtype: tuple
"""
return obj.get_display().menu(message, choices, default=default, cli_flag=cli_flag,
force_interactive=force_interactive) |
Accept input from the user.
:param str message: message to display to the user
:param default: default value to return, if interaction is not possible
:param str cli_flag: option used to set this value with the CLI
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:returns: tuple of (`code`, `input`) where
`code` - str display exit code
`input` - str of the user's input
:rtype: tuple | def input_text(message: str, default: Optional[str] = None, cli_flag: Optional[str] = None,
force_interactive: bool = False) -> Tuple[str, str]:
"""Accept input from the user.
:param str message: message to display to the user
:param default: default value to return, if interaction is not possible
:param str cli_flag: option used to set this value with the CLI
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:returns: tuple of (`code`, `input`) where
`code` - str display exit code
`input` - str of the user's input
:rtype: tuple
"""
return obj.get_display().input(message, default=default, cli_flag=cli_flag,
force_interactive=force_interactive) |
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.
:param str message: question for the user
:param str yes_label: Label of the "Yes" parameter
:param str no_label: Label of the "No" parameter
:param default: default value to return, if interaction is not possible
:param str cli_flag: option used to set this value with the CLI
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:returns: True for "Yes", False for "No"
:rtype: bool | def yesno(message: str, yes_label: str = "Yes", no_label: str = "No",
default: Optional[bool] = None, cli_flag: Optional[str] = None,
force_interactive: bool = False) -> bool:
"""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.
:param str message: question for the user
:param str yes_label: Label of the "Yes" parameter
:param str no_label: Label of the "No" parameter
:param default: default value to return, if interaction is not possible
:param str cli_flag: option used to set this value with the CLI
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:returns: True for "Yes", False for "No"
:rtype: bool
"""
return obj.get_display().yesno(message, yes_label=yes_label, no_label=no_label, default=default,
cli_flag=cli_flag, force_interactive=force_interactive) |
Display a checklist.
:param str message: Message to display to user
:param list tags: `str` tags to select, len(tags) > 0
:param default: default value to return, if interaction is not possible
:param str cli_flag: option used to set this value with the CLI
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:returns: tuple of (`code`, `tags`) where
`code` - str display exit code
`tags` - list of selected tags
:rtype: tuple | def checklist(message: str, tags: List[str], default: Optional[List[str]] = None,
cli_flag: Optional[str] = None,
force_interactive: bool = False) -> Tuple[str, List[str]]:
"""Display a checklist.
:param str message: Message to display to user
:param list tags: `str` tags to select, len(tags) > 0
:param default: default value to return, if interaction is not possible
:param str cli_flag: option used to set this value with the CLI
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:returns: tuple of (`code`, `tags`) where
`code` - str display exit code
`tags` - list of selected tags
:rtype: tuple
"""
return obj.get_display().checklist(message, tags, default=default, cli_flag=cli_flag,
force_interactive=force_interactive) |
Display a directory selection screen.
:param str message: prompt to give the user
:param default: default value to return, if interaction is not possible
:param str cli_flag: option used to set this value with the CLI
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:returns: tuple of the form (`code`, `string`) where
`code` - display exit code
`string` - input entered by the user | def directory_select(message: str, default: Optional[str] = None, cli_flag: Optional[str] = None,
force_interactive: bool = False) -> Tuple[str, str]:
"""Display a directory selection screen.
:param str message: prompt to give the user
:param default: default value to return, if interaction is not possible
:param str cli_flag: option used to set this value with the CLI
:param bool force_interactive: True if it's safe to prompt the user
because it won't cause any workflow regressions
:returns: tuple of the form (`code`, `string`) where
`code` - display exit code
`string` - input entered by the user
"""
return obj.get_display().directory_select(message, default=default, cli_flag=cli_flag,
force_interactive=force_interactive) |
Verify that provided arguments is a valid display call.
:param str prompt: prompt for the user
:param default: default answer to prompt
:param str cli_flag: command line option for setting an answer
to this question
:param bool force_interactive: if interactivity is forced | def assert_valid_call(prompt: str, default: str, cli_flag: str, force_interactive: bool) -> None:
"""Verify that provided arguments is a valid display call.
:param str prompt: prompt for the user
:param default: default answer to prompt
:param str cli_flag: command line option for setting an answer
to this question
:param bool force_interactive: if interactivity is forced
"""
msg = "Invalid display call for this prompt:\n{0}".format(prompt)
if cli_flag:
msg += ("\nYou can set an answer to "
"this prompt with the {0} flag".format(cli_flag))
assert default is not None or force_interactive, msg |
ArgumentParser options namespace (prefix of all options). | def option_namespace(name: str) -> str:
"""ArgumentParser options namespace (prefix of all options)."""
return name + "-" |
ArgumentParser dest namespace (prefix of all destinations). | def dest_namespace(name: str) -> str:
"""ArgumentParser dest namespace (prefix of all destinations)."""
return name.replace("-", "_") + "_" |
Copy a file into an active location (likely the system's config dir) if required.
:param str dest_path: destination path for version controlled file
:param str digest_path: path to save a digest of the file in
:param str src_path: path to version controlled file found in distribution
:param list all_hashes: hashes of every released version of the file | def install_version_controlled_file(dest_path: str, digest_path: str, src_path: str,
all_hashes: Iterable[str]) -> None:
"""Copy a file into an active location (likely the system's config dir) if required.
:param str dest_path: destination path for version controlled file
:param str digest_path: path to save a digest of the file in
:param str src_path: path to version controlled file found in distribution
:param list all_hashes: hashes of every released version of the file
"""
current_hash = crypto_util.sha256sum(src_path)
def _write_current_hash() -> None:
with open(digest_path, "w") as file_h:
file_h.write(current_hash)
def _install_current_file() -> None:
shutil.copyfile(src_path, dest_path)
_write_current_hash()
# Check to make sure options-ssl.conf is installed
if not os.path.isfile(dest_path):
_install_current_file()
return
# there's already a file there. if it's up to date, do nothing. if it's not but
# it matches a known file hash, we can update it.
# otherwise, print a warning once per new version.
active_file_digest = crypto_util.sha256sum(dest_path)
if active_file_digest == current_hash: # already up to date
return
if active_file_digest in all_hashes: # safe to update
_install_current_file()
else: # has been manually modified, not safe to update
# did they modify the current version or an old version?
if os.path.isfile(digest_path):
with open(digest_path, "r") as f:
saved_digest = f.read()
# they modified it after we either installed or told them about this version, so return
if saved_digest == current_hash:
return
# there's a new version but we couldn't update the file, or they deleted the digest.
# save the current digest so we only print this once, and print a warning
_write_current_hash()
logger.warning("%s has been manually modified; updated file "
"saved to %s. We recommend updating %s for security purposes.",
dest_path, src_path, dest_path) |
Setup the directories necessary for the configurator. | def dir_setup(test_dir: str, pkg: str) -> Tuple[str, str, str]: # pragma: no cover
"""Setup the directories necessary for the configurator."""
def expanded_tempdir(prefix: str) -> str:
"""Return the real path of a temp directory with the specified prefix
Some plugins rely on real paths of symlinks for working correctly. For
example, certbot-apache uses real paths of configuration files to tell
a virtual host from another. On systems where TMP itself is a symbolic
link, (ex: OS X) such plugins will be confused. This function prevents
such a case.
"""
return filesystem.realpath(tempfile.mkdtemp(prefix))
temp_dir = expanded_tempdir("temp")
config_dir = expanded_tempdir("config")
work_dir = expanded_tempdir("work")
filesystem.chmod(temp_dir, constants.CONFIG_DIRS_MODE)
filesystem.chmod(config_dir, constants.CONFIG_DIRS_MODE)
filesystem.chmod(work_dir, constants.CONFIG_DIRS_MODE)
test_dir_ref = importlib_resources.files(pkg).joinpath("testdata").joinpath(test_dir)
with importlib_resources.as_file(test_dir_ref) as path:
shutil.copytree(
path, os.path.join(temp_dir, test_dir), symlinks=True)
return temp_dir, config_dir, work_dir |
Ensure that the specified file exists. | def validate_file(filename: str) -> None:
"""Ensure that the specified file exists."""
if not os.path.exists(filename):
raise errors.PluginError('File not found: {0}'.format(filename))
if os.path.isdir(filename):
raise errors.PluginError('Path is a directory: {0}'.format(filename)) |
Ensure that the specified file exists and warn about unsafe permissions. | def validate_file_permissions(filename: str) -> None:
"""Ensure that the specified file exists and warn about unsafe permissions."""
validate_file(filename)
if filesystem.has_world_permissions(filename):
logger.warning('Unsafe permissions on credentials configuration file: %s', filename) |
Return a list of progressively less-specific domain names.
One of these will probably be the domain name known to the DNS provider.
:Example:
>>> base_domain_name_guesses('foo.bar.baz.example.com')
['foo.bar.baz.example.com', 'bar.baz.example.com', 'baz.example.com', 'example.com', 'com']
:param str domain: The domain for which to return guesses.
:returns: The a list of less specific domain names.
:rtype: list | def base_domain_name_guesses(domain: str) -> List[str]:
"""Return a list of progressively less-specific domain names.
One of these will probably be the domain name known to the DNS provider.
:Example:
>>> base_domain_name_guesses('foo.bar.baz.example.com')
['foo.bar.baz.example.com', 'bar.baz.example.com', 'baz.example.com', 'example.com', 'com']
:param str domain: The domain for which to return guesses.
:returns: The a list of less specific domain names.
:rtype: list
"""
fragments = domain.split('.')
return ['.'.join(fragments[i:]) for i in range(0, len(fragments))] |
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
.. deprecated:: 2.7.0
Please use certbot.plugins.dns_common_lexicon.LexiconDNSAuthenticator instead. | def build_lexicon_config(lexicon_provider_name: str,
lexicon_options: Mapping[str, Any], provider_options: Mapping[str, Any]
) -> Union[ConfigResolver, Dict[str, Any]]: # pragma: no cover
"""
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
.. deprecated:: 2.7.0
Please use certbot.plugins.dns_common_lexicon.LexiconDNSAuthenticator instead.
"""
config_dict: Dict[str, Any] = {'provider_name': lexicon_provider_name}
config_dict.update(lexicon_options)
if ConfigResolver is None:
# Lexicon 2.x
config_dict.update(provider_options)
return config_dict
else:
# Lexicon 3.x
provider_config: Dict[str, Any] = {}
provider_config.update(provider_options)
config_dict[lexicon_provider_name] = provider_config
return ConfigResolver().with_dict(config_dict).with_env() |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.