ACME client that automates the process of obtaining, installing, and renewing SSL/TLS certificates from Let's Encrypt certificate authority.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
General utility functions for file operations, system information, validation, and process management used throughout Certbot operations.
Utilities for safely creating, managing, and accessing files and directories with proper permissions.
def make_or_verify_dir(directory: str, mode: int, strict: bool = True) -> None:
"""
Create directory with specified permissions or verify existing directory.
Args:
directory: Directory path to create or verify
mode: File mode permissions (e.g., 0o700, 0o755)
strict: If true, raise exception if directory permissions don't match
Raises:
errors.Error: If directory creation fails or permissions are incorrect
"""
def safe_open(path: str, mode: str = 'w', chmod: int = 0o644) -> IO:
"""
Safely open a file with specified permissions.
Args:
path: File path to open
mode: File open mode (e.g., 'w', 'r', 'a')
chmod: File permissions to set
Returns:
File object handle
Raises:
OSError: If file cannot be opened
"""
def unique_file(path: str, chmod: int = 0o644, mode: str = 'w') -> tuple[IO, str]:
"""
Create a unique filename if the specified path already exists.
Args:
path: Desired file path
chmod: File permissions to set
mode: File open mode
Returns:
Tuple of (file_handle, actual_path_used)
"""
def unique_lineage_name(path: str, filename: str) -> tuple[IO, str]:
"""
Create a unique lineage filename for certificate storage.
Args:
path: Directory path for lineage
filename: Base filename for lineage
Returns:
Tuple of (file_handle, unique_filename)
"""
def safely_remove(path: str) -> None:
"""
Remove a file that may or may not exist without raising errors.
Args:
path: Path to file to remove
"""
def lock_dir_until_exit(dir_path: str) -> None:
"""
Lock a directory until the program exits.
Args:
dir_path: Directory to lock
Raises:
errors.LockError: If directory cannot be locked
"""
def set_up_core_dir(directory: str, mode: int, strict: bool = True) -> None:
"""
Create and lock a core Certbot directory.
Args:
directory: Directory path to set up
mode: Directory permissions
strict: Whether to enforce strict permissions
"""Functions to gather operating system and platform information.
def get_os_info() -> tuple[str, str]:
"""
Get operating system name and version.
Returns:
Tuple of (os_name, os_version)
"""
def get_os_info_ua() -> str:
"""
Get OS information formatted for User Agent strings.
Returns:
OS information string suitable for HTTP User-Agent header
"""
def get_systemd_os_like() -> list[str]:
"""
Get systemd OS likeness information from /etc/os-release.
Returns:
List of OS distributions this system is like
"""
def get_var_from_file(varname: str, filepath: str) -> str:
"""
Extract variable value from systemd-style configuration file.
Args:
varname: Variable name to extract
filepath: Path to configuration file
Returns:
Variable value as string
"""
def get_python_os_info(pretty: bool = False) -> tuple[str, str]:
"""
Get OS information using Python's platform module.
Args:
pretty: Whether to return pretty-formatted names
Returns:
Tuple of (os_name, os_version)
"""Utilities for running external commands and managing subprocess execution.
def run_script(params: list[str]) -> tuple[str, str]:
"""
Run external command/script with parameters.
Args:
params: List of command and arguments
Returns:
Tuple of (stdout, stderr) output
Raises:
errors.SubprocessError: If command execution fails
"""
def exe_exists(exe: str) -> bool:
"""
Check if executable exists in the system PATH.
Args:
exe: Executable name to check
Returns:
True if executable is found in PATH
"""Domain name and email validation utilities for ensuring input correctness.
def safe_email(email: str) -> bool:
"""
Validate email address format using regex.
Args:
email: Email address to validate
Returns:
True if email format is valid
"""
def enforce_le_validity(domain: str) -> str:
"""
Validate domain name for Let's Encrypt compatibility.
Args:
domain: Domain name to validate
Returns:
Validated domain name
Raises:
errors.ConfigurationError: If domain is invalid for Let's Encrypt
"""
def enforce_domain_sanity(domain: Union[str, bytes]) -> str:
"""
Perform basic domain name validation.
Args:
domain: Domain name to validate
Returns:
Validated domain name as string
Raises:
errors.ConfigurationError: If domain format is invalid
"""
def is_ipaddress(address: str) -> bool:
"""
Check if string represents an IP address.
Args:
address: String to check
Returns:
True if address is a valid IP address
"""
def is_wildcard_domain(domain: Union[str, bytes]) -> bool:
"""
Check if domain is a wildcard domain (starts with *.).
Args:
domain: Domain to check
Returns:
True if domain is wildcard format
"""
def is_staging(srv: str) -> bool:
"""
Determine if ACME server URL is a staging server.
Args:
srv: ACME server URL
Returns:
True if server appears to be staging/testing server
"""
def get_filtered_names(all_names: set[str]) -> set[str]:
"""
Filter domain names to those valid for Let's Encrypt.
Args:
all_names: Set of domain names to filter
Returns:
Set of names valid for Let's Encrypt certificates
"""Version parsing and environment management functions.
def parse_loose_version(version_string: str) -> list:
"""
Parse version string into comparable components.
Args:
version_string: Version string to parse
Returns:
List of version components (integers and strings)
"""
def env_no_snap_for_external_calls() -> dict[str, str]:
"""
Get environment variables for external command calls.
Returns:
Dictionary of environment variables with snap paths removed
"""
def atexit_register(func: Callable, *args: Any, **kwargs: Any) -> None:
"""
Register function to be called at program exit.
Args:
func: Function to call at exit
args: Positional arguments for function
kwargs: Keyword arguments for function
"""from certbot import util
# Create directory with proper permissions
util.make_or_verify_dir('/etc/letsencrypt/live', 0o700, strict=True)
# Safely create unique files
with util.safe_open('/etc/letsencrypt/accounts/account.json', 'w', 0o600) as f:
f.write(account_data)
# Get unique filename if original exists
file_handle, actual_path = util.unique_file('/etc/letsencrypt/csr/example.csr')from certbot import util
# Get OS information
os_name, os_version = util.get_os_info()
print(f"Running on {os_name} {os_version}")
# Check for executable availability
if util.exe_exists('apache2ctl'):
print("Apache is available")from certbot import util
# Validate email
if util.safe_email('user@example.com'):
print("Valid email address")
# Validate domains
try:
domain = util.enforce_le_validity('example.com')
print(f"Valid domain: {domain}")
except errors.ConfigurationError:
print("Invalid domain for Let's Encrypt")
# Check for wildcard domains
if util.is_wildcard_domain('*.example.com'):
print("Wildcard domain detected")class LooseVersion:
"""
Version comparison utility with loose rules.
Supports version strings with mixed integer and string components.
"""
def __init__(self, version_string: str):
"""Parse version string into components."""
def try_risky_comparison(self, other: 'LooseVersion') -> int:
"""
Compare with another LooseVersion.
Returns:
0 if equal, 1 if self > other, -1 if self < other
Raises:
errors.Error: If versions are incompatible for comparison
"""
# Environment and system constants
EMAIL_REGEX: str # Regular expression for email validation
ANSI_SGR_BOLD: str # ANSI bold formatting code
ANSI_SGR_RED: str # ANSI red color code
ANSI_SGR_RESET: str # ANSI reset formatting codeInstall with Tessl CLI
npx tessl i tessl/pypi-certbot