Skip to navigation

nemoguardrails.library.injection_detection.actions

View as MarkdownOpen in Claude

Module Contents

Classes

NameDescription
InjectionDetectionResult-

Functions

NameDescription
_check_yara_available-
_extract_injection_configExtracts and processes the injection detection configuration values.
_injection_detection_outcomeBlock rejected or unremovable detections, and expose completed rewrites.
_load_rulesLoads and compiles YARA rules from either file paths or direct rule strings.
_omit_injectionRemove the union of matched byte ranges from the original UTF-8 text.
_reject_injectionDetects whether the provided text contains potential injection attempts.
_sanitize_injectionAttempts to sanitize the offending injection attempts in the provided text.
_validate_injection_configValidates the injection detection configuration.
injection_detectionDetects and mitigates potential injection attempts in the provided text.

Data

YARA_DIR

log

API

class nemoguardrails.library.injection_detection.actions.InjectionDetectionResult

Bases: typing.TypedDict

detections
List[str]
is_injection
bool
text
str
nemoguardrails.library.injection_detection.actions._check_yara_available()
nemoguardrails.library.injection_detection.actions._extract_injection_config(
config: nemoguardrails.RailsConfig
) -> typing.Tuple[str, pathlib.Path, typing.Tuple[str], typing.Optional[typing.Dict[str, str]]]

Extracts and processes the injection detection configuration values.

Parameters:

config
RailsConfig

RailsConfig — The Rails configuration object containing injection detection settings.

Returns: str

Tuple[str, Path, Tuple[str], Optional[Dict[str, str]]]: A tuple containing the action option,

Raises:

  • ValueError: If the injection rules contain invalid elements.
nemoguardrails.library.injection_detection.actions._injection_detection_outcome(
action_option: str,
original_text: str

Block rejected or unremovable detections, and expose completed rewrites.

nemoguardrails.library.injection_detection.actions._load_rules(
yara_path: pathlib.Path,
rule_names: typing.Tuple,
yara_rules: typing.Optional[typing.Dict[str, str]] = None
) -> typing.Union[yara.Rules, None]

Loads and compiles YARA rules from either file paths or direct rule strings.

Parameters:

yara_path
Path

The path to the directory containing YARA rule files.

rule_names
Tuple

A tuple of YARA rule names to load.

yara_rules
Optional[Dict[str, str]]Defaults to None

Dictionary mapping rule names to YARA rule strings.

Returns: Union[yara.Rules, None]

Union[‘yara.Rules’, None]: The compiled YARA rules object if successful,

Raises:

  • yara.SyntaxError: If there is a syntax error in the YARA rules.
  • ImportError: If the yara module is not installed.
nemoguardrails.library.injection_detection.actions._omit_injection(
text: str,
matches: list[yara.Match]
) -> typing.Tuple[bool, str]

Remove the union of matched byte ranges from the original UTF-8 text.

Parameters:

text
str

The text to check for command injection.

matches
list[yara.Match]

A list of YARA rule matches.

Returns: Tuple[bool, str]

Tuple[bool, str]: A tuple containing:

  • bool: True if matches were provided, False otherwise.
  • str: The text with all matched byte ranges removed.

Raises:

  • AttributeError: If a match is missing its range information.
  • TypeError: If range information has unusable types.
  • ValueError: If any match has no removable ranges, a range is invalid, or the result is not valid UTF-8.

This method may not be completely effective and could still result in malicious activity. The caller must re-scan the result because deletion can assemble new injection patterns. Offsets and full match lengths remain usable even when YARA truncates the returned match data or decodes it with XOR.

nemoguardrails.library.injection_detection.actions._reject_injection(
text: str,
rules: yara.Rules
) -> typing.Tuple[bool, typing.List[str]]

Detects whether the provided text contains potential injection attempts.

This function is recommended as an output or execution guardrail. It loads all relevant YARA rules and compiles them according to the provided configuration.

Parameters:

text
str

The text to check for command injection.

rules
yara.Rules

The loaded YARA rules.

Returns: Tuple[bool, List[str]]

Tuple[bool, List[str]]: A tuple containing:

  • bool: True if attempted exploitation is detected, False otherwise.
  • List[str]: List of matched rule names.

Raises:

  • ValueError: If the action parameter in the configuration is invalid.
  • ImportError: If the yara module is not installed.
nemoguardrails.library.injection_detection.actions._sanitize_injection(
text: str,
matches: list[yara.Match]
) -> typing.Tuple[bool, str]

Attempts to sanitize the offending injection attempts in the provided text. This is done by ‘de-fanging’ the offending content, transforming it into a state that will not execute downstream commands.

Parameters:

text
str

The text to check for command injection.

matches
list[yara.Match]

A list of YARA rule matches.

Returns: Tuple[bool, str]

Tuple[bool, str]: A tuple containing:

  • bool: True if injection was detected, False otherwise.
  • str: The sanitized text, or original text depending on sanitization outcome. Currently, this function will always raise NotImplementedError.

Raises:

  • NotImplementedError: If the sanitization logic is not implemented.
  • ImportError: If the yara module is not installed.

This method may not be completely effective and could still result in malicious activity. Sanitizing malicious input instead of rejecting or omitting it is inherently risky and generally not recommended.

nemoguardrails.library.injection_detection.actions._validate_injection_config(
config: nemoguardrails.RailsConfig
) -> None

Validates the injection detection configuration.

Parameters:

config
RailsConfig

RailsConfig — The Rails configuration object containing injection detection settings.

Raises:

  • ValueError: If the configuration is missing or invalid.
  • FileNotFoundError: If the provided yara_path is not a directory.
nemoguardrails.library.injection_detection.actions.injection_detection(
text: str,
config: nemoguardrails.RailsConfig
async

Detects and mitigates potential injection attempts in the provided text.

Depending on the configuration, this function can omit or sanitize the detected injection attempts. If the action is set to “reject”, it delegates to the reject_injection function.

Parameters:

text
str

The text to check for command injection.

config
RailsConfig

RailsConfig — The Rails configuration object containing injection detection settings.

Returns: RailOutcome

RailOutcome with InjectionDetectionResult fields in metadata:

  • is_injection (bool): Whether an injection was detected. True if any injection is detected, False if no injection is detected.
  • text (str): The sanitized or original text
  • detections (List[str]): List of matched rule names if any injection is detected

Raises:

  • ValueError: If the action parameter in the configuration is invalid.
  • NotImplementedError: If an unsupported action is encountered.
  • ImportError: If the yara module is not installed.
nemoguardrails.library.injection_detection.actions.YARA_DIR = Path(__file__).resolve().parent.joinpath('yara_rules')
nemoguardrails.library.injection_detection.actions.log = logging.getLogger(__name__)