Code, SQL and XSS injection detection with YARA rules in NeMo Guardrails

The injection detection output rail scans model output for code, SQL and XSS payloads using YARA rules. This page covers the default rules, inline rules, reject versus omit actions and how it fits a layered design.

On this page

Code, SQL and XSS injection detection with YARA rules in NeMo Guardrails: when teams need it

Teams need the injection detection output rail when an agent's output is passed on to something that executes or interprets it, not only shown to a person. An agent that writes SQL into a reporting tool, emits HTML that a browser renders, or produces code that a pipeline runs can carry a payload into a downstream system that trusts its input. According to the NeMo Guardrails documentation, the injection detection output rail checks model output against YARA rules and acts on responses that match. Before you rely on it, read the section of the documentation for the version you run, because the matching behavior and available actions are what your security review will ask about.

The default rules target the payload families named in this topic: code, SQL and XSS injection. Treat that as the stated scope and assume nothing beyond it has been tested for you. Confirm three things against the rule files shipped with your installed release: which patterns each rule matches, which syntaxes and languages it covers, and how the rules are updated between releases. Record the exact version you pin, since the current release is 0.25.0 and rule content can change between versions. Then run the rules against outputs your own tools would actually receive, drawn from recorded agent traffic, and note what passes.

The rail is one control among several and does not form a complete defense. It inspects text the model produced. It cannot decide whether a downstream tool should run a statement, and it does not replace controls that limit damage if a payload gets through. Those include parameterized queries for database access, output encoding in browsers, sandboxed execution, read-only database roles for the agent, and tool permissions that restrict what the agent can call. Assign an owner for rule tuning and false positive review before the rail blocks production responses. The sibling sections on layering defenses and indirect injection show where this rail sits in the wider design.

How the injection output rail sits in the request flow

The flow starts with a user message entering the NeMo Guardrails application, which passes it to the LLM call. The model's response then reaches the output rails, where the injection detection rail checks it against YARA rules before anything downstream acts on it. A match takes the reject or omit branch, so the response never reaches the tool or browser. The trust boundary sits between the model output and downstream systems, so check that every tool call and rendered response crosses the rail first.

Output rail checks model responses before they reach tools or the browser.

What the default YARA rules cover and what they miss

The code injection rules look for text that would change the meaning of a command if a model's output or a user's input reached a shell, interpreter or tool that evaluates strings. They are most relevant in agentic systems where model output becomes an argument to a tool, a file operation or a script runner, because a string that looks like prose in a chat window can become an instruction once it is passed downstream.

  • Shell metacharacters: patterns for command separators, pipes, redirection and substitution that alter how a shell parses a string.
  • Interpreter calls: references to functions or statements that evaluate strings in common scripting languages.
  • Encoded forms: whether obfuscated or encoded variants are matched depends on the specific rule, so test the encodings you expect attackers or users to try.
  • Context blind spots: a value can become dangerous only after an application expands or joins it, such as a filename that a downstream tool globs. A pattern on the raw text cannot see that step.

Confirm which languages, shells and invocation forms the installed rules cover, then test them with payloads drawn from the tools your agent can actually call.

Reject versus omit actions and inline rule options

This table compares the reject and omit outcomes for matched output in the injection detection rail, along with authoring inline YARA rules. Read each row as a trade-off between blocking the whole answer and removing only the matched content. Confirm exact action names, logged fields and rule syntax in the current NeMo Guardrails documentation before setting them in production.

ConsiderationReject actionOmit action
What the user seesThe whole response is withheld and replaced with a refusal or fallback messageMatched code or markup is removed and the rest of the answer is returned
Best fitOutput that must never reach the user, such as an active injection payloadAnswers where a suspicious fragment can be stripped without harming the content
Legitimate code answersA correct answer containing a false positive is lost entirelyOnly the flagged fragment is lost, but the remaining code may be incomplete or broken
Logging and reviewConfirm which fields are logged on a block and whether the matched rule name is recordedConfirm whether removed content is logged and whether reviewers can compare it with the original
Agent and tool workflowsDownstream steps receive a refusal, so test how the agent recovers from a blocked outputDownstream steps receive edited text, so test that the altered output still parses
Strength of the guaranteeFlagged content does not reach the user or the next component in the chainPartial payloads can survive if a pattern matches only part of the injection
Inline rule authoringWrite rules in the configuration, then test each one against known-good code and SQL samplesSame authoring steps, but test edits carefully because removal can change syntax

How to configure the injection detection rail step by step

This sequence takes a clean Python environment to a working injection detection output rail, with a custom YARA rule tested against benign and malicious sample outputs. It ends with a confirmed reject or omit action that your team can review and repeat after changes. Each step closes with a check that shows whether the work is done.

  1. Confirm the Python version and create an environment

    Someone on the platform or application team creates a virtual environment using Python 3.11, 3.12 or 3.13, the versions NeMo Guardrails 0.25.0 requires. Run python --version inside the environment before installing anything. The step is done when the output starts with 3.11, 3.12 or 3.13. Keep this environment alongside the agent code so the rail is tested on the same runtime that will ship.

  2. Install the NeMo Guardrails library

    Install the nemoguardrails package from PyPI with pip in that environment. The package is licensed under Apache-2.0, and the current release is 0.25.0, so pin that version in your requirements file so every environment loads the same rail code. Run pip show nemoguardrails to confirm the installed version is 0.25.0 and the license is Apache-2.0. If your team installs from an internal package mirror, confirm the mirror carries this release first.

  3. Create the config folder with the output rail

    Create a configuration folder containing config.yml, then enable the injection detection rail in the output rails section. Confirm the exact configuration keys and flow names in the NeMo Guardrails documentation for your release, because rail names are the part most likely to change between versions. Load the folder from Python with RailsConfig.from_path and create the runtime object with the Guardrails class, which 0.25.0 introduces in place of LLMRails. The step is done when the configuration loads without error.

  4. Add an inline YARA rule for your payloads

    The engineer who owns the output policy writes a YARA rule for the pattern to catch, such as a SQL fragment or a script tag in model output, and adds it inline in the configuration. The pattern shown in your review should be illustrative until your team has tested it against real application output. Give the rule a clear name so the logs identify it later. Compile the rule with a YARA tool before loading it. The step is done when the configuration loads and the rule compiles cleanly.

  5. Test the rail with benign sample outputs

    Run a set of normal model outputs through the rail. Include plain prose, the code snippets your application is expected to return, and sentences that mention SQL keywords or HTML tags in an explanatory way. Use the same runtime and configuration you plan to deploy. The step is done when every benign sample passes unchanged and no action fires. Record each false positive as a finding, adjust the rule, and rerun the full benign set before continuing.

  6. Test malicious samples and confirm the action

    Run outputs that should match the rule, such as a SQL injection fragment, an XSS payload and a code injection string. Compare each result with your chosen action. Reject should return the blocked response, and omit should remove only the matched content and pass the rest. Check the logs or trace to confirm the rule name appears for each match. The step is done when every malicious sample produces the expected action. Repeat both test sets after any change to the configuration or rules.

Security and operational risks of YARA-based output checks

A YARA rule set is pattern matching, so its failures are predictable: it misses payloads it was not written for, it blocks valid code, and it drifts as the application changes. The cards below name each risk for code, SQL and XSS detection in NeMo Guardrails and the control that keeps it manageable.

Novel encodings evade rules

A rule that matches <script> or a literal UNION SELECT misses the same payload once it is URL-encoded, Unicode-escaped, split across chunks or wrapped in a template the model reproduces differently. Attackers and generated output both produce variants the rule author did not anticipate. Ask the team to test each rule against encoded and obfuscated versions of its target and to treat a clean result as a weak signal, not proof that output is safe.

NeMo Guardrails docs

Legitimate code gets blocked

Developer-facing assistants legitimately produce SQL examples, HTML templates and code that quotes attack strings, such as a security tutorial or a sanitizer unit test. A broad rule blocks this work and pushes users toward workarounds that bypass the rail entirely. Collect a sample of blocked outputs from your own users, classify them, and narrow the rule or move the check to the affected route before tuning the global threshold.

Rules drift from the application

Rules written against today's prompts, output formats and frameworks go stale when templates change, a new model changes its formatting, or a team adds a language the rules do not cover. Nothing fails loudly when this happens, so coverage quietly shrinks. Assign each rule an owner, record the reason it exists, and review the set on a schedule and after every model or prompt change.

Blocked content lands in logs

When the rail rejects an output, the matched text is often what gets logged, which can copy malicious payloads and any sensitive data around them into log stores with broader access than the chat. Decide what the rail logs, for how long and who can read it. Confirm with your team whether matched fragments are redacted, whether the retention period matches your data policy, and whether log access follows the same controls as the application data.

Untested rules ship to production

A rule set that was never run against real traffic has unknown precision and recall, so both the block rate and the miss rate are guesses. Replay recorded, anonymized outputs from production or a staging environment through the rail before enabling it, and compare decisions with a reviewed label for each sample. Repeat the replay after every rule change, so tuning is measured instead of anecdotal.

Where the injection output rail fits among other controls

The injection output rail is one layer in a defense-in-depth design, and it does not replace the controls that stop an injected instruction from doing damage. A YARA rule can flag a suspicious SQL fragment, script tag or shell pattern in model output, but it cannot make a query safe. The controls that carry that weight sit elsewhere: least-privilege tool permissions that limit what the agent's database or API credentials can do, parameterized queries and output encoding in the downstream systems that consume the text, and secure coding practices in those systems. Treat the rail as a backstop that catches obvious payloads and produces logs, not as the reason the application is safe.

Order the controls by where untrusted text enters and where it can act. Input rails and jailbreak or injection checks on user prompts run first, so that obviously hostile requests never reach the model. Retrieval checks on documents and tool results run before that content is placed into the context window, because indirect injection often arrives through retrieved text rather than the user. The injection output rail runs on the model's response before it is returned or passed to a tool or renderer, and it is the last check before a payload can leave the model. Tool calls should be validated against the agent's permissions independently of any text scanning, since a generated query can look clean to a rule and still be wrong.

Before you rely on the rail's position in the chain, confirm two deployment details with your own setup and the NeMo Guardrails documentation. First, measure the added latency of the output rail on realistic response lengths, particularly with streaming enabled, because an output check that buffers the full response changes how users experience the assistant. Second, confirm the fail behavior: whether a rail error blocks the response or lets it through, and how your application handles that outcome. Record which behavior applies in your deployment and test it, so the team knows exactly what protection exists during an outage or a misconfiguration.

Limits to confirm in your environment before relying on YARA rules

YARA-based injection detection is only as strong as the rules, encodings and runtime conditions behind it. The cards below cover the points to confirm with the vendor documentation and your own testing before a control sits in front of production traffic. Each one changes what the rail will and will not catch.

Rule coverage per version

Confirm exactly which SQL, code and XSS patterns the bundled rule set detects in the NeMo Guardrails version you deploy. Rule content can change between releases, so a configuration that blocked a payload on one version may pass it on the next. Record the version you tested against and repeat the check after every upgrade, including the 0.25.0 release line you are planning around.

NeMo Guardrails docs

Language and encoding gaps

Ask whether the rules handle payloads that are URL-encoded, Base64-encoded, Unicode-escaped, double-encoded or split across messages. Attackers and legitimate developers both paste unusual text, so a rule written for plain ASCII may miss obfuscated input. Build a test corpus with these variants and non-English identifiers, then record which ones pass unflagged.

Performance on long outputs

Measure how rule matching behaves when the model returns large code blocks, generated reports or long query results. Scanning cost grows with output size, and a rail that is fast on short answers can add noticeable delay on long ones. Ask the vendor whether the rules run per chunk or on the full text, and set a test size that matches your largest realistic response.

Behavior with streaming responses

Determine whether an output rail sees the complete response before any tokens reach the user or only partial fragments as they stream. A pattern split across two streamed chunks can evade a rule that only inspects each fragment. Test with your streaming mode enabled, confirm what the client receives when a rule fires mid-stream, and document the result.

Who manages rule updates

Decide whether your team or the vendor owns changes to the rule set, and how a new rule reaches your deployment. If you copy rules into your own configuration, you must track upstream changes yourself and test each one. If you rely on bundled rules, confirm how updates are published, how they are versioned, and how you pin a version for auditability.

Coverage against your own traffic

Replay recorded or representative prompts and outputs from your application through the rail, then review every block and every miss. Public samples rarely match the code, SQL and markup your users produce. Treat the results as evidence for your own threshold decisions, and repeat the replay after rule changes so you can show what changed.

Questions teams ask before adding YARA injection detection

How much does YARA injection detection cost to implement?

The NeMo Guardrails library is licensed under Apache 2.0, so the software itself has no license fee of the kind a commercial product charges. Your cost is the work and the infrastructure around it. One-time costs include designing the rules and actions, integrating them with your agents and output paths, building test cases, and reviewing which matches should block content. Recurring costs include compute for the guardrails server, staff time to tune rules against new traffic, and retesting after each upgrade. Costs rise with the number of applications covered and the amount of tuning needed. Ask any quote to separate labor, infrastructure and ongoing support, and to state whether any NVIDIA product in your stack is licensed separately.

How long does adding YARA injection detection take?

The duration depends on what the work covers, and a timeline should come from a written scope. The main drivers are how many agents, tools and output paths need coverage, whether your configuration uses Colang 1.0, the default, or Colang 2.x, and whether an existing configuration must be migrated. NVIDIA's convert tool helps with Colang migration, but NVIDIA says converted configurations still need manual review, and that review takes time. Plan for test case development and a tuning period against real traffic. Confirm your Python version as well, since NeMo Guardrails 0.25.0 requires Python 3.11, 3.12 or 3.13. Ask for the timeline split into design, build, test and rollout phases, with client checkpoints in each.

What does our team need to provide for this work?

The work depends on four client inputs that a partner or in-house team cannot supply alone:

  • Representative sample traffic, anonymized where needed, covering normal prompts, tool arguments and model outputs.
  • A named security owner who decides whether a match should reject the request or omit the matched content.
  • Application owners who can describe the code, SQL, markup and data formats their assistant produces or renders.
  • Known attack and test cases, including SQL, XSS and code injection payloads that apply to your systems.

You also need a non-production environment for testing, and a change approval path for rollout. Without the security owner decisions and the test cases, the rules can be built but cannot be proven.

Can our own engineers implement YARA injection detection without a partner?

Yes, a team with Python and security testing skills can do this in-house. The configuration itself is approachable: rails are defined in a config.yml file, with optional Python actions and Colang files. The harder work is deciding which matches block, tuning out false positives on your traffic, and proving coverage with repeatable tests. Teams without a security owner for those decisions, or without a test harness for agent outputs, often find testing takes longer than the build. A partner is worth considering when you need a fixed scope, an independent test pass or evidence for a review. DeployOpen plans, implements and tests this kind of setup inside your infrastructure, with scope and deliverables agreed in writing before work starts.

What makes the scope of a detection project grow?

Scope grows with the number of places untrusted text reaches the model and the places model output reaches other systems. Common drivers include:

  • The number of agents, tools and retrieval paths whose inputs or outputs need inspection.
  • The output formats your assistant generates or renders, such as code, SQL, HTML and other markup.
  • Existing custom rules and Colang dialog flows that must be merged with the new rails.
  • A Colang 1.0 to 2.x migration and the manual review of converted configurations.
  • Logging, observability and evidence requirements that an assessor may ask to see.

Each added application or output format adds rules, test cases and tuning time, so confirm these items in the written scope before work begins.

Will YARA rules keep working after a NeMo Guardrails upgrade?

Configurations can carry over between releases, but each upgrade needs a retest. NeMo Guardrails 0.25.0 was published on 19 November 2026, after release 0.24.1 on 16 September 2026. Release 0.25.0 deprecates the LLMRails class in favor of Guardrails, with removal planned no earlier than 0.27.0, and NVIDIA publishes a 0.25 migration guide. Read the migration notes before upgrading any production server, and rerun your injection test set after each version change. Check the release notes for every version you adopt. Budget ongoing effort for this, since it recurs with each release you take.

Is the NeMo Guardrails microservice still supported?

No. NVIDIA has sunset the NeMo Guardrails microservice as of October 1, 2026, and its container will receive no new releases. Plan the implementation around the open-source library or the guardrails server, which NVIDIA's repository ships under Apache 2.0. If an existing deployment uses the microservice, NVIDIA's archived documentation asks those users to contact their NVIDIA account team about next steps. The NeMo Platform repository now resolves to NeMo Helix, which runs NeMo Guardrails as an inference gateway plugin. Treat that as a separate architecture decision, and confirm it against your own requirements before choosing it. You can review the NGC catalog entry to confirm the sunset status yourself.

Does YARA detection replace parameterized queries and output encoding?

No single rule replaces them, so treat YARA detection as one layer in a defense-in-depth design. Parameterized queries, least-privilege database accounts, output encoding and strict tool permissions address the cause inside the application. A pattern match on text catches known payload shapes, can miss new encodings, and can flag legitimate code that resembles an attack. Pair the rail with those application controls, log every match, and record a decision for each rule about reject or omit. Retest the layers together after changes. The sibling topic on layering prompt injection defenses explains how to stack these rails across input, retrieval, tools and output.

How to prove the rules work on your traffic

Before you trust the injection detection output rail, build a test set from your own application's traffic and measure what it blocks and what it misses. Start with three groups of benign content: code answers in the languages your assistant actually produces, SQL that your analysts or developers legitimately ask for, and HTML or Markdown answers that contain tags, links and formatting. Add a fourth group of known payloads covering the code, SQL and XSS patterns your security team already tracks. Keep the benign group large and realistic, because the false positives that frustrate users come from ordinary content that happens to contain a keyword or a pattern. Record which rule fires for each sample, so a block can be traced back to a specific rule rather than a general verdict.

Measure two numbers for each group: the share of benign samples that were blocked, and the share of payloads that got through. Review every miss and every false block by hand, because a single rule change often moves both numbers. If a benign sample is blocked, decide whether the rule needs narrowing, whether the reject or omit action is the right response for that content, or whether the sample belongs in an exception path handled elsewhere in your design. If a payload is missed, decide whether a custom inline rule should cover it or whether another control in the stack, such as output encoding in the application, is the better place for that case. Write down each decision next to the test that prompted it.

Retest the full set after every change: an edit to a rule, a change to the action, an upgrade of the NeMo Guardrails package, or a change to the default rule set that ships with it. Confirm the release you are testing against with the NeMo Guardrails documentation and the project's release notes, since default rules can change between versions. Keep the test set under version control with the configuration, so an auditor or your own team can see which results matched which rule set. Ask any partner you engage to deliver the test set, the results and the retest evidence as part of the written scope.

How DeployOpen works on this

DeployOpen plans, implements and supports NeMo Guardrails in infrastructure you control, including the output rail that applies YARA rules for code, SQL and XSS injection patterns. The work is scoped in writing first, then built, tested, documented and handed over to your team, with ongoing support available as a retainer.

How we scope

  • Written scope names which injection categories the YARA rules must cover, such as code, SQL and XSS patterns.
  • Scope records which rails run before and after the YARA output check, and which application endpoints they protect.
  • Scope lists the action per rule, reject or omit, and who decides when a rule's behavior changes.

How we build

  • Configuration files are built with the default YARA rules enabled, and any inline rules are written and version controlled.
  • Test cases cover known injection payloads and benign inputs that resemble code, SQL or markup your users legitimately send.
  • The injection check is placed alongside input, tool and retrieval controls, with the latency it adds measured on your traffic.

How we hand over

  • Handover includes configuration files, inline rule sources, test results and a record of each reject or omit decision.
  • Runbooks explain how to add, disable or review a rule and how to rerun the test set after a change.
  • Documentation states which controls the YARA rule does not cover and which application permissions must still limit damage.

How we support

  • Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts.
  • Ongoing support, upgrades and continuous testing are available as a retainer, including retesting after NeMo Guardrails releases.
  • Confirm with DeployOpen how rule updates, false positive reviews and retests will be handled under your retainer.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.