Seclang Deep Dive: Building Smart WAF Rules with Coraza and ModSecurity

Seclang Deep Dive: Building Smart WAF Rules with Coraza and ModSecurity

Web Application Firewalls (WAFs) are now a core part of modern web security architecture, sitting at the HTTP edge to detect and block attacks before they reach your application. Seclang is the rule language that powers that logic for engines like ModSecurity and Coraza, letting you describe how traffic should be inspected and when it should be blocked, logged, or tagged.

This guide gives a practical, from-scratch introduction to Seclang for HackerVault readers: what it is, how the rule model works, and how to use it to build robust defensive logic for real-world web apps and APIs.

What Is Seclang?

Seclang (often written as “SecLang”) is a domain-specific language used by WAF engines such as ModSecurity and Coraza to define web security policies as rules and directives. Instead of writing a general-purpose program, you express what parts of HTTP traffic to inspect, how to test them, and what actions to take when suspicious patterns are detected.

At a high level, Seclang lets you inspect HTTP requests and responses in different phases, evaluate conditions with operators, and apply actions like blocking, logging, or anomaly scoring, all in a declarative style that fits well into infrastructure and DevSecOps workflows.

Why Seclang Matters for WAFs

Because Seclang is widely supported by ModSecurity and Coraza, it has become a de facto standard for writing portable WAF rules, including widely used rule sets like the OWASP Core Rule Set (CRS).

For security teams, this means Seclang rules can be reused across different proxies and platforms, allowing a single language to express detection for SQL injection, XSS, file inclusion, path traversal, credential-stuffing, and many other web attack classes.

Seclang Building Blocks Overview

  • Directives – configuration statements that control global behavior and how rules are loaded and executed.
  • Rules – per-request conditions evaluated against HTTP data and internal state.
  • Variables – references to pieces of the HTTP transaction, like headers, arguments, cookies, and collections such as IP or TX.
  • Operators – tests applied to variables (regex, string match, numeric comparison, etc.).
  • Transformations – normalization steps applied before running operators.
  • Actions – disruptive or non-disruptive responses when a rule matches.

All Seclang rules are combinations of these components, which together define how the WAF interprets and acts on web traffic.

Directives: Configuring the Rule Engine

Directives are Seclang statements that configure the WAF engine itself, rather than evaluating a single request. They define how rules are loaded, which phases are active, and how logging and core behavior should work.

  • Engine control – turning the rule engine on or off, or setting default rule behavior.
  • Rule loading – including other files, directories, or external rule packs such as OWASP CRS.
  • Default actions – specifying which actions apply to rules unless overridden.
  • Logging and audit settings – enabling audit logs and controlling what data is stored.
# Example of top-level directives (generic style)
SecRuleEngine On
Include "owasp-crs/crs-setup.conf"
Include "owasp-crs/rules/*.conf"

While exact directive names vary between engines, the idea is the same: directives shape the environment in which rules run, and typically live at the top of rule files and core configuration.

Execution Phases and Rule Flow

WAF engines process HTTP traffic in multiple phases, and Seclang rules specify which phase they belong to. This phase-based model ensures rules only run when the relevant data is available and keeps complex policies manageable.

  • Request headers phase – request line and headers are available; useful for basic filtering and early blocking.
  • Request body phase – form parameters, JSON, and file uploads can be inspected.
  • Response headers phase – status code and response headers are visible.
  • Response body phase – HTML or API response bodies can be scanned for leaks or anomalies.
  • Logging / cleanup phase – correlation and anomaly scoring logic can run before final logging.

By assigning rules to appropriate phases, you avoid unnecessary processing and can build multi-stage logic, such as collecting signals early and making final allow/deny decisions later.

Variables: What Seclang Inspects

Variables in Seclang tell the engine which parts of the HTTP transaction to examine. Instead of parsing raw HTTP, you work with structured variables representing headers, arguments, cookies, body content, and internal state collections.

  • Request components – URI, request line, headers, query parameters, body parameters, cookies.
  • Response components – status code, headers, body content (if enabled).
  • Collections – per-IP, per-transaction (TX), or global data used to store counters, flags, or computed values.

This design lets you directly target typical attack surfaces such as query strings, form fields, JSON bodies, and cookies, without reinventing HTTP parsing in your rules.

# Example of targeting arguments and headers (generic Seclang-style)
SecRule ARGS "attackpattern" "id:1001,phase:2,log,deny"
SecRule REQUEST_HEADERS:User-Agent "badbot" "id:1002,phase:1,log,deny"

By scoping variables carefully (all arguments, a specific parameter, a subset of headers), you can tune rules to be broad or precise depending on your risk tolerance and application behavior.

Operators: How Seclang Tests Conditions

Operators perform the actual checks on variable values. They implement simple and advanced logic, from plain string comparisons to regular expressions and list-based lookups.

  • Regex operators – detect patterns typical of SQL injection, XSS, or path traversal.
  • String operators – check for equality, containment, or simple matches.
  • Numeric operators – compare lengths, scores, and counters (e.g., greater than a threshold).
  • IP / subnet checks – allowlist or blocklist specific IP ranges.
  • Lookup operators – test membership in data files (bad user agents, known Tor exits, etc.).
# Pseudo-example of a numeric threshold
SecRule TX:anomaly_score ">= 10" "id:9001,phase:5,log,deny,msg:'Anomaly score too high'"

Combining operators with thoughtful variable selection and transformations allows you to build rules that catch real attacks while minimizing noise and false positives.

Transformations: Normalizing Input to Beat Evasion

Attackers rarely send straightforward payloads; they use encodings, unusual casing, or whitespace tricks to evade naive filters. Transformations in Seclang normalize input before operators run, making detection more reliable against obfuscated payloads.

  • URL decoding – decoding percent-encoded data, sometimes multiple times.
  • Lowercasing – normalizing case to avoid case-based evasion.
  • Whitespace normalization – compressing or standardizing whitespace.
  • Path normalization – simplifying path constructs such as ../.
# Conceptual example with transformations (pseudo-style)
SecRule ARGS "pattern" "id:1100,phase:2,log,deny,t:urlDecodeUni,t:lowercase"

Well-tuned rules almost always rely on transformations; using them thoughtfully is key to balancing detection coverage with performance and false positive control.

Actions: What Happens When a Rule Matches

Actions define Seclang’s behavior when an operator indicates a match. They can alter the request flow (disruptive actions) or simply record information and update state (non-disruptive actions).

  • Disruptive actions – deny requests, send specific HTTP codes, or redirect clients when high-risk conditions are triggered.
  • Non-disruptive actions – log matches, write audit records, tag transactions, and adjust anomaly scores or internal variables.
# Example rule with mixed actions (pseudo-style)
SecRule ARGS "union select" "id:1200,phase:2,log,tag:'attack-sqli',setvar:'TX.anomaly_score=+5'"

Modern rulesets frequently use anomaly scoring, where multiple lower-severity matches accumulate into a total score that triggers blocking only when a threshold is exceeded, helping reduce false positives from single noisy indicators.

Seclang Rule Syntax

The canonical Seclang rule syntax can be summarized as:

SecRule VARIABLES OPERATOR "ACTIONS"

Variables specify what to inspect, operators define how to test data, and actions declare what to do, often in a comma-separated list. Chaining and additional modifiers extend this syntax for more complex logic.

  • Variables – specify one or more collections or request parts.
  • Operator – apply a pattern, comparison, or lookup to those values.
  • Actions – log, deny, tag, transform data, and update internal collections.

By stacking many such rules, each focused on a specific pattern or behavior, you build up a layered web security policy in Seclang.

Chaining Rules for Multi-Step Logic

Sometimes you want to trigger an action only when multiple conditions are true, but you do not want to cram everything into a single complex expression. Seclang supports rule chaining, where a second rule executes only if the previous one matched.

This allows you to build multi-step logic, such as “only inspect the body deeply if the URL matches a particular endpoint” or “increment a score only if both a suspicious header and a suspicious argument are present.”

# Conceptual pattern for chaining (pseudo-style)
SecRule REQUEST_URI "login" "id:1300,phase:2,chain,log"
    SecRule ARGS:password "(?i)(select|union|sleep)" "setvar:'TX.anomaly_score=+5'"

Chaining is a powerful tool for reducing false positives, because it enforces context: only when conditions align do you escalate the response.

Practical Detection Scenarios with Seclang

To use Seclang effectively, think in terms of threats and how they manifest in HTTP traffic, not just isolated regex signatures. Below are example scenarios that map naturally to Seclang rules.

  • Brute-force login detection – track failed login attempts per IP or per account, increasing anomaly scores and temporarily blocking abusive sessions.
  • File upload abuse detection – scan uploaded filenames and content types for double extensions, executable content, or known webshell signatures.
  • API abuse and rate limiting – monitor request frequency per IP or API key, and enforce soft and hard limits with anomaly scores and blocks.
  • Data exfiltration via responses – inspect response bodies for patterns indicating secrets, error dumps, or sensitive data being returned unintentionally.

Each of these patterns can be implemented as a small cluster of Seclang rules using appropriate variables, operators, and actions tuned to your environment.

Seclang with Coraza vs ModSecurity

ModSecurity has long been the classic Seclang-capable WAF, especially embedded with Apache and Nginx, while Coraza provides a modern, cloud-native engine that also supports Seclang syntax and semantics.

This compatibility means that rule sets like OWASP CRS, as well as custom Seclang rules you create, can be reused across both engines, allowing migration from legacy setups to modern reverse proxies without rewriting your entire WAF policy.

coraza vs modsecurity hackervault
Seclang rules can be shared between ModSecurity and Coraza, giving you a portable policy layer across different infrastructures.

Common Pitfalls and Tuning Strategies

Seclang is powerful, but like any security engine, misconfiguration and poor tuning can cause pain in production. Understanding common pitfalls helps you deploy more confidently.

  • Overly broad signatures – generic patterns applied to all parameters can generate false positives, especially for internal tools and rich APIs.
  • Heavy regexes on large bodies – complex regular expressions scanning large request bodies may degrade performance when traffic spikes.
  • Insufficient logging – without logging the right context, debugging blocked requests becomes slow and frustrating.
  • Lack of documentation – large rule sets with no comments or naming conventions are hard for teams to maintain or safely modify.

To mitigate these issues, use anomaly scoring, apply complex checks only where necessary, increase logging for high-risk rules, and treat your Seclang policy like code: review, document, and test it in staging before production rollout.

Seclang and Defense-in-Depth

Seclang-based WAF rules complement, but do not replace, secure coding and platform hardening. They are one layer in a defense-in-depth strategy that includes secure development practices, authentication and authorization, endpoint protection, and monitoring.

Because Seclang operates at the HTTP edge, it is especially valuable for shielding legacy applications, buying time to patch newly discovered vulnerabilities, and providing a consistent security layer across multiple services and technologies.

Ideas for Future HackerVault Seclang Content

Once this foundational Seclang article is live on HackerVault, you can extend the topic in several directions that align with your brand and your readers’ interests.

  • Rule write-ups for specific CVEs – show how to express detections for current vulnerabilities in Seclang and integrate them into Coraza.
  • Seclang labs on GitHub – build small vulnerable apps with accompanying WAF rule packs so readers can practice writing and tuning rules.
  • Deployment guides – walkthroughs for running Coraza with Nginx, Envoy, or Kubernetes ingress, using Seclang to enforce policies consistently across environments.

Sample Seclang Rule Snippet (Conceptual)

The snippet below shows a conceptual layout of a Seclang configuration where directives, variables, operators, transformations, and actions work together as part of a consistent rule strategy.

# Enable rule engine (generic)
SecRuleEngine On

# Example: basic SQLi pattern on login endpoint (pseudo-style)
SecRule REQUEST_URI "login" "id:2000,phase:2,chain,log,tag:'endpoint-login'"
    SecRule ARGS:password "(?i)(union select|sleep\()" \
        "id:2001,log,tag:'attack-sqli',setvar:'TX.anomaly_score=+5'"

# Example: block when anomaly score exceeds threshold
SecRule TX:anomaly_score ">= 10" \
    "id:9000,phase:5,log,deny,status:403,msg:'WAF: high anomaly score'"

In a real deployment, these rules would live alongside larger rule sets such as OWASP CRS, and would be tuned for your specific applications, endpoints, and risk appetite.

FAQ

4 thoughts on “Seclang Deep Dive: Building Smart WAF Rules with Coraza and ModSecurity

  1. Hey, has anyone checked out rrs88 lately? I’ve been having some decent luck there with the slots. The bonuses could be a little better, but overall, it’s a solid platform. Worth a look if you’re after a new spot to play. Check it out: rrs88

Leave a Reply

Your email address will not be published. Required fields are marked *