ssg.utils module

Utils functions consumed by SSG

exception ssg.utils.SSGError[source]

Bases: RuntimeError

class ssg.utils.VersionSpecifier(op, evr_ver_dict)[source]

Bases: object

A class to represent a version specifier with properties and methods to manipulate and retrieve version information.

op

The operation associated with the version specifier.

Type:

str

_evr_ver_dict

A dictionary containing epoch, version, and release information.

Type:

dict

property cpe_id
property ev_ver
static evr_dict_to_str(evr, fully_formed_evr_string=False)[source]

Convert an EVR (Epoch-Version-Release) dictionary to a string representation.

Parameters:
  • evr (dict) – A dictionary containing ‘epoch’, ‘version’, and ‘release’ keys. ‘epoch’ and ‘release’ can be None.

  • fully_formed_evr_string (bool) – If True, ensures that the returned string includes ‘0’ for missing ‘epoch’ and ‘-0’ for missing ‘release’.

Returns:

The string representation of the EVR dictionary.

Return type:

str

property evr_op
property evr_ver
matches(evr: Dict)[source]

Check if a given EVR dictionary satisfies this version specifier.

Parameters:

evr (dict) – A dictionary containing ‘epoch’, ‘version’, and ‘release’ keys.

Returns:

True if the EVR satisfies this version specifier, False otherwise.

Return type:

bool

property oval_id
property title
property ver
class ssg.utils.VersionSpecifierSet(s=())[source]

Bases: set

A set-like collection that only accepts VersionSpecifier objects.

This class extends the built-in set and ensures that all elements are instances of the VersionSpecifier class. It provides additional properties to generate titles, CPE IDs, and OVAL IDs from the contained VersionSpecifier objects.

title

A string representation of the set, joining the titles of the contained VersionSpecifier objects with ‘ and ‘.

Type:

str

cpe_id

A string representation of the set, joining the CPE IDs of the contained VersionSpecifier objects with ‘:’.

Type:

str

oval_id

A string representation of the set, joining the OVAL IDs of the contained VersionSpecifier objects with ‘_’.

Type:

str

property cpe_id
property oval_id
property title
ssg.utils.apply_formatting_on_dict_values(source_dict, string_dict, ignored_keys=frozenset({}))[source]

Apply string formatting on dictionary values.

This function uses Python’s built-in string replacement to replace strings marked by {token} if “token” is a key in the string_dict parameter. It skips keys in source_dict which are listed in the ignored_keys parameter. This function works only for dictionaries whose values are dictionaries or strings.

Parameters:
  • source_dict (dict) – The source dictionary whose values need formatting.

  • string_dict (dict) – A dictionary containing replacement strings for tokens.

  • ignored_keys (frozenset, optional) – A set of keys to be ignored during formatting. Defaults to an empty frozenset.

Returns: dict: A new dictionary with formatted values.

ssg.utils.banner_anchor_wrap(banner_text)[source]

Wraps the given banner text with ‘^’ at the beginning and ‘$’ at the end.

Parameters:

banner_text (str) – The text to be wrapped.

Returns:

The banner text wrapped with ‘^’ at the beginning and ‘$’ at the end.

Return type:

str

ssg.utils.banner_regexify(banner_text)[source]

Converts a banner text into a regex pattern.

This function escapes special regex characters in the input text and then performs the following transformations: - Replaces newline characters (”

“) with a placeholder string “BFLMPSVZ”.
  • Replaces spaces with a regex pattern that matches one or more whitespace characters or newline characters.

  • Replaces the placeholder string “BFLMPSVZ” with a regex pattern that matches one or more newline characters or escaped newline sequences.

Args:

banner_text (str): The banner text to be converted into a regex pattern.

Returns:

str: The resulting regex pattern.

ssg.utils.check_conflict_regex_directory(data)[source]

Validate that either all paths are directories or the ‘file_regex’ key exists.

This function checks the following conditions: 1. If the ‘is_directory’ key is present in the data dictionary, it ensures that all file paths

in the ‘filepath’ list are either directories or files. Mixing directories and files is not allowed.

  1. If the ‘file_regex’ key is present in the data dictionary, it ensures that all file paths in the ‘filepath’ list are directories.

Parameters:

data (dict) – A dictionary containing the following keys: - ‘filepath’ (list): A list of file paths to be validated. - ‘is_directory’ (bool, optional): A flag indicating whether the paths are directories. - ‘file_regex’ (str, optional): A regular expression pattern for file matching. - ‘_rule_id’ (str): An identifier for the rule being validated.

Raises:

ValueError – If the file paths are a mix of directories and files, or if the ‘file_regex’ key is used but the file paths are not directories.

ssg.utils.comparison_to_oval(op)[source]

Converts a comparison operator to its corresponding OVAL string representation.

Parameters:

op (str) – The comparison operator to convert. Expected values are ‘==’, ‘!=’, ‘>’, ‘<’, ‘>=’, ‘<=’.

Returns:

The OVAL string representation of the comparison operator.

Return type:

str

Raises:

KeyError – If the provided operator is not one of the expected values.

ssg.utils.ensure_file_paths_and_file_regexes_are_correctly_defined(data)[source]

Ensures that the data structure for file paths and file regexes is correctly defined.

This function is used for the file_owner, file_groupowner, and file_permissions templates. It ensures that: - The ‘filepath’ item in the data is a list. - The number of items in ‘file_regex’ matches the number of items in ‘filepath’.

Note

  • If ‘filepath’ is a string, it will be converted to a list containing that string.

  • If ‘file_regex’ is a string, it will be converted to a list with the same length as ‘filepath’, with each element being the original ‘file_regex’ string.

  • If there are multiple regexes for a single filepath, the filepath must be declared multiple times.

Parameters:

data (dict) – A dictionary containing file path and file regex information. It must contain the keys: - ‘filepath’: A string or list of strings representing file paths. - ‘file_regex’ (optional): A string or list of strings representing file regexes. - ‘_rule_id’: A string representing the rule ID.

Raises:

ValueError – If the number of items in ‘file_regex’ does not match the number of items in ‘filepath’.

ssg.utils.enum(*args)[source]

Creates an enumeration with the given arguments.

Parameters:

*args – A variable length argument list of strings representing the names of the enumeration members.

Returns:

A new enumeration type with the given member names as attributes, each assigned a

unique integer value starting from 0.

Return type:

type

Example

>>> Colors = enum('RED', 'GREEN', 'BLUE')
>>> Colors.RED
0
>>> Colors.GREEN
1
>>> Colors.BLUE
2
ssg.utils.escape_comparison(op)[source]

Maps a comparison operator to its corresponding string representation.

Parameters:

op (str) – The comparison operator to be mapped. Expected values are ‘==’, ‘!=’, ‘>’, ‘<’, ‘>=’, ‘<=’.

Returns:

The string representation of the comparison operator.

Possible return values are ‘eq’, ‘ne’, ‘gt’, ‘le’, ‘gt_or_eq’, ‘le_or_eq’.

Return type:

str

Raises:

KeyError – If the provided operator is not in the mapping dictionary.

ssg.utils.escape_id(text)[source]

Converts a given text into a string that is more readable and compatible with OSCAP/XCCDF/OVAL entity IDs by replacing non-word characters with underscores and stripping leading/trailing underscores.

Parameters:

text (str) – The input string to be converted.

Returns:

The converted string with non-word characters replaced by underscores and

leading/trailing underscores removed.

Return type:

str

ssg.utils.escape_regex(text)[source]

Escapes special characters in a given text to make it safe for use in regular expressions.

This function mimics the behavior of re.escape() in Python 3.7, which escapes a reasonable set of characters. Specifically, it escapes the following characters: #, $, &, *, +, ., ^, , |, ~, :, (, ), and -. Note that the characters ‘!’, ‘”’, ‘%’, “’”, ‘,’, ‘/’, ‘:’, ‘;’, ‘<’, ‘=’, ‘>’, ‘@’, and “” are not escaped.

Parameters:

text (str) – The input string containing characters to be escaped.

Returns:

A new string with special characters escaped.

Return type:

str

ssg.utils.escape_yaml_key(text)[source]

Escapes uppercase letters and caret symbols in a YAML key by prefixing them with a caret and converts the entire key to lowercase.

This function is used to handle the limitation of OVAL’s name argument of the field type, which requires avoiding uppercase letters for keys. The probe would escape them with the ‘^’ symbol.

Example

myCamelCase^Key -> my^camel^case^^^key

Parameters:

text (str) – The YAML key to be escaped.

Returns:

The escaped and lowercased YAML key.

Return type:

str

ssg.utils.get_cpu_count()[source]

Returns the most likely estimate of the number of CPUs in the machine for threading purposes, gracefully handling errors and possible exceptions.

Returns:

The number of CPUs available. If the number of CPUs cannot be determined, returns 2

as a default value.

Return type:

int

ssg.utils.get_fixed_product_version(product, product_version)[source]

Adjusts the product version format for specific products.

Some product versions have a dot in between the numbers while the product ID doesn’t have the dot, but the full product name does. This function ensures the correct format for the product version.

Parameters:
  • product (str) – The name of the product (e.g., “ubuntu”).

  • product_version (str) – The version of the product as a string.

Returns:

The adjusted product version with the correct format.

Return type:

str

ssg.utils.is_applicable(platform, product)[source]

Check if a platform is applicable for the given product.

This function determines whether a specified platform or a list of platforms is applicable for a given product. It handles cases where the platform is specified as ‘all’ or ‘multi_platform_all’, as well as cases where the platform is a comma-separated list of products.

Parameters:
  • platform (str) – The platform or list of platforms to check.

  • product (str) – The product to check applicability for.

Returns:

True if the product is applicable for the platform or list of platforms, False otherwise.

Return type:

bool

ssg.utils.is_applicable_for_product(platform, product)[source]

Determines if a remediation script is applicable for a given product based on the platform specifier.

The function checks if the platform is either a general multi-platform specifier or matches the specific product name and version.

Parameters:
  • platform (str) – The platform specifier of the remediation script.

  • product (str) – The product name and version.

Returns:

True if the remediation script is applicable for the product, False otherwise.

Return type:

bool

ssg.utils.map_name(version)[source]

Maps SSG Makefile internal product name to official product name.

This function takes a version string and maps it to an official product name based on predefined mappings. It handles multi-platform versions by trimming the “multi_platform_” prefix and recursively mapping the trimmed version.

Parameters:

version (str) – The version string to be mapped.

Returns:

The official product name corresponding to the given version.

Return type:

str

Raises:

RuntimeError – If the version is invalid or cannot be mapped to any known product.

ssg.utils.merge_dicts(left, right)[source]

Merges two dictionaries, keeping left and right as passed.

If there are any common keys between left and right, the value from right is used.

Parameters:
  • left (dict) – The first dictionary.

  • right (dict) – The second dictionary.

Returns:

The merged dictionary containing keys and values from both left and right dictionaries.

Return type:

dict

ssg.utils.mkdir_p(path)[source]

Create a directory and all intermediate-level directories if they do not exist.

Parameters:

path (str) – The directory path to create.

Returns:

True if the directory was created, False if it already exists.

Return type:

bool

Raises:

OSError – If the directory cannot be created and it does not already exist.

ssg.utils.name_to_platform(names)[source]

Converts one or more full names to a string containing one or more <platform> elements.

Parameters:

names (str or list of str) – A single name as a string or a list of names.

Returns:

A string containing one or more <platform> elements.

Return type:

str

ssg.utils.parse_name(product)[source]

Parses a given product string and returns a namedtuple containing the name and version.

Parameters:

product (str) – The product string to parse, e.g., “rhel9”.

Returns:

A namedtuple with ‘name’ and ‘version’ attributes, e.g., (“rhel”, “9”).

Return type:

namedtuple

Example

>>> parse_name("rhel9")
product(name='rhel', version='9')
ssg.utils.parse_platform(platform)[source]

Parses a comma-separated string of platforms and returns a set of trimmed platform names.

Parameters:

platform (str) – A comma-separated string of platform names.

Returns:

A set of platform names with leading and trailing whitespace removed.

Return type:

set

ssg.utils.parse_template_boolean_value(data, parameter, default_value)[source]

Parses a boolean value from a template parameter.

Parameters:
  • data (dict) – The dictionary containing the template data.

  • parameter (str) – The key for the parameter to parse.

  • default_value (bool) – The default value to return if the parameter is not found or is None.

Returns:

The parsed boolean value.

Return type:

bool

Raises:

ValueError – If the parameter value is not “true” or “false”.

ssg.utils.product_to_name(prod)[source]

Converts a product identifier into a full product name.

This function takes a product identifier and attempts to match it with a full product name from the FULL_NAME_TO_PRODUCT_MAPPING dictionary. If the product identifier is found in the dictionary, the corresponding full product name is returned. If the product identifier is in the MULTI_PLATFORM_LIST or is ‘all’, a string prefixed with “multi_platform_” is returned. If the product identifier is not recognized, a RuntimeError is raised.

Parameters:

prod (str) – The product identifier to convert.

Returns:

The full product name corresponding to the given product identifier.

Return type:

str

Raises:

RuntimeError – If the product identifier is not recognized.

ssg.utils.product_to_platform(prods)[source]

Converts one or more product ids into a string with one or more <platform> elements.

Parameters:

prods (str or list of str) – A single product id as a string or a list of product ids.

Returns:

A string containing one or more <platform> elements.

Return type:

str

ssg.utils.read_file_list(path)[source]

Reads the given file path and returns the contents as a list.

Parameters:

path (str) – The path to the file to be read.

Returns:

A list containing the contents of the file, split by lines or other delimiters as

defined by split_string_content.

Return type:

list

Raises:
  • FileNotFoundError – If the file at the given path does not exist.

  • IOError – If an I/O error occurs while reading the file.

ssg.utils.recurse_or_substitute_or_do_nothing(v, string_dict, ignored_keys=frozenset({}))[source]

Recursively applies string formatting to dictionary values, substitutes strings, or returns the value unchanged.

Parameters:
  • v (Any) – The value to process. Can be a dictionary, string, or any other type.

  • string_dict (dict) – A dictionary containing string keys and values to be used for formatting.

  • ignored_keys (frozenset, optional) – A set of keys to ignore when processing dictionaries. Defaults to an empty frozenset.

Returns:

The processed value. If v is a dictionary, returns a dictionary with formatted values.

If v is a string, returns the formatted string. Otherwise, returns v unchanged.

Return type:

Any

ssg.utils.required_key(_dict, _key)[source]

Returns the value associated with the specified key in the given dictionary.

Parameters:
  • _dict (dict) – The dictionary to search for the key.

  • _key – The key to look for in the dictionary.

Returns:

The value associated with the specified key in the dictionary.

Raises:

ValueError – If the key is not found in the dictionary, an exception is raised with a message indicating that the key is required but was not found.

ssg.utils.select_templated_tests(test_dir_config, available_scenarios_basenames)[source]
ssg.utils.sha256(text)[source]

Generate a SHA-256 hash for the given text.

Parameters:

text (str) – The input text to be hashed.

Returns:

The SHA-256 hash of the input text as a hexadecimal string.

Return type:

str

ssg.utils.split_string_content(content)[source]

Splits the input string content by newline characters and returns the result as a list of strings.

Parameters:

content (str) – The string content to be split.

Returns:

A list of strings, each representing a line from the input content.

The last element will be removed if it is an empty string.

Return type:

list

ssg.utils.subset_dict(dictionary, keys)[source]

Restricts a dictionary to only include specified keys.

This function creates a new dictionary that contains only the key-value pairs from the original dictionary where the key is present in the provided list of keys. Neither the original dictionary nor the list of keys is modified.

Parameters:
  • dictionary (dict) – The original dictionary from which to create the subset.

  • keys (iterable) – An iterable of keys that should be included in the subset.

Returns:

A new dictionary containing only the key-value pairs where the key is in the

provided list of keys.

Return type:

dict

ssg.utils.write_list_file(path, contents)[source]

Writes the given contents to the specified file path.

Parameters:
  • path (str) – The file path where the contents will be written.

  • contents (list of str) – A list of strings to be written to the file.

Returns:

None