Stage 7 of 10 · about 10–14 hours · intermediate · checked 2026-11-23

Detection-as-code

Goal. By the end you can keep detections in a Git repository with review, automated checks and a repeatable path to deployment, so that every change is explained, tested and reversible.

Why it matters#

If detections live only inside a SIEM's web interface, nobody can answer basic questions: who changed this rule, why, what did it look like last month, and did anyone test it? Treating detections as code gives you history, review, tests, rollback and a single source of truth. It is also the clearest way to show an employer that you do detection engineering. Everything you built in stages 5 and 6 is ready to move in.

What you will learn#

What "as code" buys you#

  • History. Every change has an author, a date and a reason.
  • Review. A second person reads a rule before it reaches production.
  • Tests. A change that breaks an earlier test is caught before it ships.
  • Repeatable deployment. The same files produce the same result in test and in production.
  • Rollback. A bad change is undone by reverting it.
  • Portability. With Sigma, one set of rules can serve more than one platform.

A repository layout#

There is no single correct layout. This one is simple and scales:

Text
rules/        Sigma rules, one per file, grouped by log source or behaviour
tests/        sample events and the result each rule should give
lists/        exclusion and allow lists, each entry with an owner, reason and review date
cards/        detection cards, if you keep them apart from the rule
tools/        small scripts: checks, coverage report
.github/      automated checks (workflows) and the pull request template
README.md     what is here and how to contribute

Keep generated files (such as converted queries) out of version control, or clearly marked as generated, so nobody edits them by hand.

Metadata worth requiring#

Decide which fields every rule must have, and check for them automatically. A good minimum: a unique id, a title, status, description, author, date (and a modified date when you change it), tags with the ATT&CK mapping, logsource, falsepositives and level. Add an owner and a review date if your format has a place for them. The rule is then a record you can query, not just a search.

The change process#

  1. Create a branch and change one thing.

  2. Open a pull request. A short template keeps it honest:

    Markdown
    ## What and why
    ## Data checked (source, fields, latency)
    ## Test evidence (positive and negative)
    ## Known false positives
    ## Rollout plan (shadow, low visibility, live) and rollback
  3. Automated checks run (below).

  4. A second person reviews.

  5. Merge. Protect the main branch so that merging requires passing checks and a review.

Automated checks#

Layer them from cheapest to most expensive:

  1. Syntax and metadata. sigma check validates the rule format. Add your own checks for required fields, unique IDs and file naming.

  2. Conversion. Convert every rule for each platform you support. A rule that cannot convert should fail the check, as you saw with correlation rules and the Kusto backend in stage 4.

  3. Tests. Run rules against sample events and compare with the expected result. You can convert the rules and query a small test SIEM, or run Sigma rules directly over recorded Windows event logs with an open-source tool such as Chainsaw or Hayabusa. Start with a handful of positive and negative cases per rule.

  4. Coverage report. Build the ATT&CK coverage layer from the rules' tags on every merge (stage 8 uses it). Here is a small script that lists the techniques a folder of Sigma rules is tagged with, and the files that carry each tag:

    Python
    """List the ATT&CK techniques that a folder of Sigma rules is tagged with."""
    import re
    import sys
    from pathlib import Path
    
    import yaml  # installed with pySigma
    
    TAG = re.compile(r"^attack\.(t\d{4}(?:\.\d{3})?)$")
    
    
    def techniques(rules_dir):
        found = {}
        for path in Path(rules_dir).rglob("*.yml"):
            for doc in yaml.safe_load_all(path.read_text(encoding="utf-8")):
                for tag in (doc or {}).get("tags", []):
                    match = TAG.match(tag)
                    if match:
                        found.setdefault(match.group(1).upper(), set()).add(path.name)
        return found
    
    
    if __name__ == "__main__":
        for technique, files in sorted(techniques(sys.argv[1]).items()):
            print(technique, ", ".join(sorted(files)))

    Run against the three rules from stage 4 it prints T1053.005, T1059 and T1110.003, each with its file. Turning that into a Navigator layer is exercise 3 below.

Here is a minimal workflow for GitHub Actions that runs the first two layers on every pull request. It is an example for your own repository; it reads your code and changes nothing.

YAML
name: Check detections
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.12"
      - name: Install the Sigma tools
        run: pip install "pysigma<2" "sigma-cli<4" pysigma-backend-splunk pysigma-pipeline-sysmon pysigma-pipeline-windows
      - name: Validate rules
        run: sigma check rules/
      - name: Convert for Splunk
        run: sigma convert -t splunk -p sysmon -p splunk_windows rules/ > /dev/null

Illustrative: test it in your lab before relying on it. The version pins are the ones that worked together on 2026-11-22 (see stage 4); check the Sigma project's documentation and the Actions marketplace for current guidance, and adjust the pipelines to match your data.

Deployment#

Checks tell you a change is safe to ship. Deployment then pushes it to the platform, from the main branch, after the checks pass. How depends on the platform:

Platform Common approach
Splunk contentctl, Splunk's command-line tool for building, validating and testing detections as code, or packaging rules as an app
Elastic The command-line tool in the detection-rules repository, or the Kibana API
Microsoft Sentinel The Repositories feature, which connects a GitHub or Azure DevOps repository to a workspace
Panther The panther_analysis_tool command-line tool
Anything else Convert with sigma-cli in CI and call the platform's API

Good habits whichever you use:

  • Separate environments. Deploy to test first, and promote to production by merging, not by redoing it by hand.
  • Least privilege. The deployment account should be able to manage detections and nothing else. Store its credentials in your CI system's secret store, never in the repository.
  • One direction. The repository wins. If someone edits a rule in the SIEM's interface, the next deployment overwrites it, so agree that rule up front. Export and compare periodically to catch drift.
  • Retire, do not delete. Mark a rule deprecated first, so its history and reasoning stay findable.

Protect the pipeline itself#

A detection pipeline can change what your organisation can see, so it is a target. Pin tool versions (stage 4 showed why). Give workflows the smallest permissions: they need. Prefer third-party actions pinned to a full commit identifier rather than a moving tag, and read what they do. Protect the main branch. And treat a real detection repository as sensitive: exclusion lists and tuning notes tell an attacker exactly what you ignore. Stage 10 returns to this when you build a public portfolio.

Sigma-first or platform-native?#

Sigma is portable but sits at the lowest common denominator: some logic is awkward or unsupported on some backends. Native queries use the full power of one platform but lock you in. A practical compromise is Sigma for behaviours that map cleanly across platforms, and native queries for platform-specific analytics, with the same metadata, tests and review process for both.

Do this#

  1. Create the repository (2 hours). Put your stage 5 rules in rules/, add a README and the pull request template above, and commit.
  2. Add the checks (2 to 3 hours). Add the workflow, open a pull request with a deliberately broken rule (a missing field, or a bad condition), watch the check fail, then fix it and watch it pass. Turn on branch protection so a failing check blocks the merge.
  3. Generate a coverage layer (3 to 4 hours). Export a layer from ATT&CK Navigator and open the JSON to see its structure. Extend the script above so that it writes a layer with your techniques. Commit the script and run it in CI.
  4. Add tests (3 hours). Choose a recorded sample set (stage 6 lists some), run your rules over it with an open-source tool, and make CI fail if an expected detection is missing.

Resources#

Free first

Paid or needs an account

  • A GitHub account (free) for the exercises. Nothing paid is required.

Checkpoint#

You are ready to move on when you can:

Go deeper (optional)#

  • Read the validation tooling in one public rule repository and list the checks it runs that you do not.
  • Compare how two of the platforms above handle deployment and rollback.

0 / 6 checkpoints ticked

View this page on GitHub