From 3c3bcbcfcb0ba398a4a541d9c9475a73fc9371cd Mon Sep 17 00:00:00 2001 From: Herman Kaufman <234932957+finsecguy@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:06:37 +0000 Subject: [PATCH] feat: add KQL output and CI validation for Sigma rules Generate Microsoft Sentinel and Defender KQL with pySigma and pysigma-backend-kusto, in the same layout as the Splunk build. Pin CI actions by commit SHA, run sigma check, and require both SPL and KQL conversion to succeed. Add a v0.1.0 changelog, a KQL usage section, and SigmaHQ filename and reference fixes for the Microsoft 365 finance rules. --- .github/workflows/ci.yml | 15 ++- CHANGELOG.md | 28 ++++ README.md | 86 ++++++++++-- docs/erp-log-schema.md | 5 +- docs/m365-fields.md | 4 +- docs/rule-writing-guide.md | 7 +- docs/sigmahq-submission.md | 123 ++++++++++++++++++ pipelines/sigmafin_kusto.yml | 72 ++++++++++ requirements.txt | 2 + ...entra_anonymous_signin_then_inbox_rule.yml | 3 +- ...5_inbox_rule_external_forward_finance.yml} | 2 +- ...soft365_inbox_rule_hides_finance_mail.yml} | 2 +- ...5_mailbox_forwarding_external_finance.yml} | 2 +- .../erp_new_vendor_created_then_paid.yml | 3 +- .../erp_vendor_bank_change_then_payment.yml | 3 +- ...ated_and_payment_approved_by_same_user.yml | 3 +- scripts/build_kql.py | 97 ++++++++++++++ scripts/check_metadata.py | 7 +- scripts/gen_docs.py | 25 ++-- scripts/policy.yml | 15 ++- tests/test_gates.py | 35 ++++- 21 files changed, 499 insertions(+), 40 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 docs/sigmahq-submission.md create mode 100644 pipelines/sigmafin_kusto.yml rename rules/bec_payment_fraud/{m365_inbox_rule_external_forward_finance.yml => microsoft365_inbox_rule_external_forward_finance.yml} (98%) rename rules/bec_payment_fraud/{m365_inbox_rule_hides_finance_mail.yml => microsoft365_inbox_rule_hides_finance_mail.yml} (98%) rename rules/bec_payment_fraud/{m365_mailbox_forwarding_external_finance.yml => microsoft365_mailbox_forwarding_external_finance.yml} (98%) create mode 100644 scripts/build_kql.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 613e4d1..19fa492 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,8 +15,8 @@ jobs: matrix: python-version: ["3.12", "3.14"] steps: - - uses: actions/checkout@v7 - - uses: actions/setup-python@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ matrix.python-version }} cache: pip @@ -34,10 +34,19 @@ jobs: run: python scripts/gen_docs.py --check - name: Convert rules to Splunk SPL run: python scripts/build_spl.py + - name: Convert rules to KQL + run: python scripts/build_kql.py - name: Publish SPL as build artifact if: always() && matrix.python-version == '3.12' - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: splunk-spl path: build/spl if-no-files-found: warn + - name: Publish KQL as build artifact + if: always() && matrix.python-version == '3.12' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: kusto-kql + path: build/kql + if-no-files-found: warn diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..bacd009 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog + +All notable changes to SigmaFin are documented in this file. + +The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Version numbers follow semantic +versioning. This file is the version record. It is not a GitHub release, and this repository has no release tags. + +## [0.1.0] - 2026-11-22 + +### Added + +- Sigma rules for business email compromise and payment fraud, vendor and payment manipulation, and privileged ERP + abuse, with positive and negative samples and a SQLite test harness. +- Splunk SPL generation (`scripts/build_spl.py`, output under `build/spl/`). +- Microsoft Sentinel and Defender KQL generation with pySigma and pysigma-backend-kusto 1.0.1 + (`scripts/build_kql.py`, output under `build/kql/`). Support rules, the unsupported list, and the summary file + follow the SPL build. Generated queries stay out of git because `build/` is ignored, and CI uploads them. +- Continuous integration (`.github/workflows/ci.yml`) that runs `sigma check --fail-on-issues --fail-on-error` and + requires conversion to both SPL and KQL to succeed. Actions are pinned to commit SHAs. The workflow permission is + `contents: read`. +- `docs/sigmahq-submission.md`, notes for a future SigmaHQ contribution. Nothing has been submitted. + +### Changed + +- The three `rules/bec_payment_fraud/m365_*` files are renamed to the SigmaHQ `microsoft365_*` filename pattern. + The rule `name` values stay `m365_*` so tests, correlations, and `scripts/policy.yml` keep their keys. +- MITRE ATT&CK website links were removed from those rules' `references`. The techniques remain in `tags`, which is + how the SigmaHQ reference convention records ATT&CK. diff --git a/README.md b/README.md index 889b647..f574c67 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ exists, and the rule's description says so. | Rule | Theme | ATT&CK technique | Log source | Level | Notes | |---|---|---|---|---|---| -| Finance Anonymous Sign-in Followed by Inbox Rule Change (`entra_anonymous_signin_then_inbox_rule`) | 1. BEC and payment fraud | T1078.004 Cloud Accounts, T1564.008 Email Hiding Rules | azure/signinlogs + m365/audit | high | Sigma + SQLite tested, no SPL (Splunk backend lacks temporal_ordered) | +| Finance Anonymous Sign-in Followed by Inbox Rule Change (`entra_anonymous_signin_then_inbox_rule`) | 1. BEC and payment fraud | T1078.004 Cloud Accounts, T1564.008 Email Hiding Rules | azure/signinlogs + m365/audit | high | Sigma + SQLite tested, no SPL (Splunk backend lacks temporal_ordered); no KQL (Kusto backend has no correlation support) | | Finance Anonymous Sign-in Correlation Input (`entra_finance_anonymous_signin_event`) | 1. BEC and payment fraud | none (support rule) | azure/signinlogs | informational | Support rule, not deployed alone | | Finance Account Signs In From Anonymous IP Address (`entra_finance_signin_anonymous_ip`) | 1. BEC and payment fraud | T1078.004 Cloud Accounts, T1090.003 Multi-hop Proxy | azure/signinlogs | medium | | | Finance Account Sign-in From Country Outside Allowed List (`entra_finance_signin_unlisted_country`) | 1. BEC and payment fraud | T1078.004 Cloud Accounts | azure/signinlogs | medium | | @@ -51,15 +51,15 @@ exists, and the rule's description says so. | Finance Mailbox Inbox Rule Hides or Deletes Finance Keyword Mail (`m365_inbox_rule_hides_finance_mail`) | 1. BEC and payment fraud | T1564.008 Email Hiding Rules | m365/audit | medium | | | Finance Mailbox Forwarding Set to External Address (`m365_mailbox_forwarding_external_finance`) | 1. BEC and payment fraud | T1114.003 Email Forwarding Rule | m365/audit | high | | | Vendor Created (Correlation Input) (`erp_new_vendor_created_event`) | 2. Vendor and payment manipulation (ERP) | none (support rule) | erp/vendor_master | informational | Support rule, not deployed alone | -| New Vendor Created Then Paid Within Three Days (`erp_new_vendor_paid_quickly`) | 2. Vendor and payment manipulation (ERP) | fraud, no technique | erp/vendor_master + erp/payments | medium | Sigma + SQLite tested, no SPL (Splunk backend lacks temporal_ordered) | +| New Vendor Created Then Paid Within Three Days (`erp_new_vendor_paid_quickly`) | 2. Vendor and payment manipulation (ERP) | fraud, no technique | erp/vendor_master + erp/payments | medium | Sigma + SQLite tested, no SPL (Splunk backend lacks temporal_ordered); no KQL (Kusto backend has no correlation support) | | Vendor Payment Released (New Vendor Correlation Input) (`erp_new_vendor_payment_released_event`) | 2. Vendor and payment manipulation (ERP) | none (support rule) | erp/payments | informational | Support rule, not deployed alone | | Payment Run Modified Outside Business Hours (`erp_payment_run_modified_outside_hours`) | 2. Vendor and payment manipulation (ERP) | fraud, no technique | erp/payments | medium | | | Vendor Payment Approved (Correlation Input) (`erp_sod_payment_approved_event`) | 2. Vendor and payment manipulation (ERP) | none (support rule) | erp/payments | informational | Support rule, not deployed alone | | Vendor Created (Segregation of Duties Correlation Input) (`erp_sod_vendor_created_event`) | 2. Vendor and payment manipulation (ERP) | none (support rule) | erp/vendor_master | informational | Support rule, not deployed alone | | Vendor Bank Details Changed (Correlation Input) (`erp_vendor_bank_change_event`) | 2. Vendor and payment manipulation (ERP) | none (support rule) | erp/vendor_master | informational | Support rule, not deployed alone | -| Vendor Bank Details Changed Then Payment Released (`erp_vendor_bank_change_then_payment`) | 2. Vendor and payment manipulation (ERP) | T1657 Financial Theft | erp/vendor_master + erp/payments | high | Sigma + SQLite tested, no SPL (Splunk backend lacks temporal_ordered) | +| Vendor Bank Details Changed Then Payment Released (`erp_vendor_bank_change_then_payment`) | 2. Vendor and payment manipulation (ERP) | T1657 Financial Theft | erp/vendor_master + erp/payments | high | Sigma + SQLite tested, no SPL (Splunk backend lacks temporal_ordered); no KQL (Kusto backend has no correlation support) | | Vendor Master Bank Details Changed (`erp_vendor_bank_details_changed`) | 2. Vendor and payment manipulation (ERP) | T1657 Financial Theft | erp/vendor_master | medium | | -| Same User Created a Vendor and Approved a Payment to It (`erp_vendor_created_and_payment_approved_by_same_user`) | 2. Vendor and payment manipulation (ERP) | fraud, no technique | erp/vendor_master + erp/payments | high | | +| Same User Created a Vendor and Approved a Payment to It (`erp_vendor_created_and_payment_approved_by_same_user`) | 2. Vendor and payment manipulation (ERP) | fraud, no technique | erp/vendor_master + erp/payments | high | Sigma + SQLite tested, no KQL (Kusto backend has no correlation support) | | Vendor Payment Released (`erp_vendor_payment_released`) | 2. Vendor and payment manipulation (ERP) | none (support rule) | erp/payments | informational | Support rule, not deployed alone | | ERP Emergency Access Started (`erp_emergency_access_started`) | 3. Privileged ERP and finance app abuse | T1078 Valid Accounts | erp/user_admin | medium | | | ERP Privileged Role Assigned Without Approval (`erp_privileged_role_assigned_without_approval`) | 3. Privileged ERP and finance app abuse | T1098 Account Manipulation | erp/user_admin | high | | @@ -91,6 +91,7 @@ sigma check --fail-on-issues --fail-on-error rules # Sigma validation python scripts/check_metadata.py # references, tags, ids, samples, mirrors python -m pytest -q tests # sample tests, harness and gate self-tests python scripts/build_spl.py # Splunk SPL into build/spl/ +python scripts/build_kql.py # KQL into build/kql/ ``` Other commands: @@ -105,11 +106,51 @@ To convert one rule yourself, pass the pipelines it needs. This prints SPL: ```bash sigma convert -t splunk -p pipelines/finance_scope.yml -p pipelines/sigmafin_splunk.yml \ - rules/bec_payment_fraud/m365_inbox_rule_external_forward_finance.yml + rules/bec_payment_fraud/microsoft365_inbox_rule_external_forward_finance.yml ``` A rule that uses a finance scope placeholder fails loudly if `finance_scope.yml` is missing ("unhandled placeholder") -instead of silently producing an unscoped query. +instead of silently producing an unscoped query. KQL usage is in the next section. + +## KQL usage + +`scripts/build_kql.py` converts every rule to Kusto Query Language with pySigma and `pysigma-backend-kusto`, and +writes `build/kql//.kql` plus `build/kql/SUMMARY.md`. The layout matches `scripts/build_spl.py`. +Support rules are not written as their own files. A conversion failure fails the build unless the rule is listed +under `kusto_unsupported` in `scripts/policy.yml`, and a listed rule that starts converting also fails the build. +`build/` is gitignored, so the generated KQL is not committed, the same as the generated SPL. CI publishes `build/kql` +as the `kusto-kql` artifact. + +The conversion passes `pipelines/finance_scope.yml` and `pipelines/sigmafin_kusto.yml`. The first expands the finance +lists. The second sets the Kusto table: + +| Log source | Shipped table | What it is | +|---|---|---| +| `product: m365`, `service: audit` | `OfficeActivity` | Microsoft Sentinel unified audit log | +| `product: azure`, `service: signinlogs` | `SigninLogs` | Microsoft Sentinel Entra sign-in log | +| `product: erp`, `service: vendor_master` | `sigmafin_erp_vendor_master` | Placeholder for the ERP schema | +| `product: erp`, `service: payments` | `sigmafin_erp_payments` | Placeholder for the ERP schema | +| `product: erp`, `service: user_admin` | `sigmafin_erp_user_admin` | Placeholder for the ERP schema | + +Microsoft Defender XDR advanced hunting speaks KQL and uses different tables and columns (`CloudAppEvents`, +`AADSignInEventsBeta`, and custom tables). Copy `pipelines/sigmafin_kusto.yml`, change `query_table`, and add +`field_name_mapping` entries before you run a generated query as a Defender hunt. The shipped queries use the +Sentinel column names the rules already use. + +To convert one rule with the raw backend: + +```bash +sigma convert -t kusto -p pipelines/finance_scope.yml -p pipelines/sigmafin_kusto.yml \ + rules/bec_payment_fraud/microsoft365_inbox_rule_external_forward_finance.yml +``` + +That command prints the backend text, which single-quotes dotted field names. `build_kql.py` is what CI runs. It +rewrites those identifiers to KQL bracket quotes (`['Parameters.ForwardTo']`), because a single-quoted token in KQL +is a string, not a column. The stock `OfficeActivity` table still stores `Parameters` as a property bag, so the +bracket name matches only after you flatten parameters the way [docs/m365-fields.md](docs/m365-fields.md) describes. + +Correlation rules have no KQL file. Backend 1.0.1 does not implement Sigma correlations. Those rules stay listed in +`scripts/policy.yml`. ## Log sources and schemas @@ -126,7 +167,8 @@ workstations, and the reserved ERP services `user_admin`, `system_audit` and `re [docs/erp-log-schema.md](docs/erp-log-schema.md). It is shaped like field-level change records (object, field, old value, new value) plus payment records. You map your ERP audit data into it. No ERP product has been tested, and SigmaFin makes no vendor-specific support claim. `pipelines/sigmafin_splunk.yml` maps the logsources to Splunk -sourcetypes. The sourcetype names are placeholders you should change. +sourcetypes. `pipelines/sigmafin_kusto.yml` maps them to KQL tables. The ERP names in both files are placeholders +you should change. **Business hours field.** Sigma has no time-of-day condition. Rules that need one read a precomputed `outside_business_hours` field (`true` or `false`) that your ingestion or enrichment step must populate from the @@ -184,12 +226,14 @@ Tests convert the real rule files, not a copy of their logic. - **Known gaps.** `tests/known_gaps/` holds events a rule should flag but currently misses. `tests/test_known_gaps.py` asserts the miss, so a gap stays visible and the test fails when the rule is fixed. -What the tests do not do: they apply only `finance_scope.yml`, so the logsource mapping in `sigmafin_splunk.yml` is not -exercised, and nothing checks sample field names against the schema documents. +What the tests do not do: they apply only `finance_scope.yml`, so the logsource mapping in `sigmafin_splunk.yml` and +the table mapping in `sigmafin_kusto.yml` are not exercised, and nothing checks sample field names against the schema +documents. ## CI gates -CI (`.github/workflows/ci.yml`) runs on every push and pull request, on Python 3.12 and 3.14. The steps: +CI (`.github/workflows/ci.yml`) runs on every push and pull request, on Python 3.12 and 3.14. The workflow +permission is `contents: read`. Actions are pinned to commit SHAs. The steps: | Gate | Fails on | Self-tested | |---|---|---| @@ -199,7 +243,8 @@ CI (`.github/workflows/ci.yml`) runs on every push and pull request, on Python 3 | `pytest` | Failing positive or negative samples, harness checks, known gap checks, whole-directory checks | The harness is self-tested. The sample tests themselves are not | | `gen_docs.py --check` | README table or generated docs out of date | Yes | | `build_spl.py` | A rule fails to convert and is not listed as unsupported, or a listed rule now converts | Yes, both directions | -| Artifact upload | Not a gate. Publishes `build/spl` as the `splunk-spl` artifact from the 3.12 job | No | +| `build_kql.py` | A rule fails to convert and is not listed as unsupported, or a listed rule now converts | Yes, both directions | +| Artifact upload | Not a gate. Publishes `build/spl` as `splunk-spl` and `build/kql` as `kusto-kql` from the 3.12 job | No | Rule metadata is also covered only as far as these checks go. References are checked for presence and HTTPS, not for whether the URL resolves or supports the rule. That was done by hand when each rule was written. @@ -209,12 +254,21 @@ whether the URL resolves or supports the rule. That was done by hand when each r - **SPL is converted but never executed against Splunk.** Tests run the SQLite conversion. The SPL is only generated and published as a CI artifact. SQL and SPL differ in case handling, wildcards and boolean precedence, so SPL behaviour is unproven. +- **KQL is converted but never executed.** The same limit applies to Sentinel and Defender. `build_kql.py` checks + that each query starts with a table name. It does not run the query. A boolean comparison is emitted with the + backend's `=~` operator (`outside_business_hours =~ true` on the payment run rule). - **Some SPL is expected to behave differently from SQLite.** The Splunk conversion of an unordered `temporal` correlation bins time in fixed windows, so one sample is predicted to match on SQLite and miss on Splunk. The prediction and its sample are in [docs/splunk-expectations.md](docs/splunk-expectations.md). It is not a test result. - **`temporal_ordered` rules have no SPL output.** The pySigma Splunk backend 2.1.0 cannot convert that correlation type. These rules keep strict event ordering, are tested on SQLite only and are marked in the table. They are listed in `scripts/policy.yml`, and CI fails if the list goes stale. +- **Correlation rules have no KQL output.** The pySigma Kusto backend 1.0.1 does not implement Sigma correlation + rules, so both `temporal` and `temporal_ordered` rules are omitted. The `temporal` rule still converts to SPL. + The gaps are listed under `kusto_unsupported` in `scripts/policy.yml`, and CI fails if the list goes stale. +- **Shipped KQL uses Sentinel table names.** `OfficeActivity` and `SigninLogs` follow the field names in the rules. + Defender XDR advanced hunting uses other tables and columns. ERP tables are placeholders (`sigmafin_erp_*`). + Change `pipelines/sigmafin_kusto.yml` before you deploy a query. - **Samples are synthetic.** Every event is made up. Passing tests show the rule logic does what the author intended on those events, not that it fits real telemetry or finds real attacks. - **The ERP schema is generic.** You must map your ERP audit data into it, and no vendor-specific mapping or support @@ -252,6 +306,10 @@ commit `f083329`, 2026-10-19) was searched for an equivalent. The terms, matches Only rules that exist have been checked. Each new rule gets the same check first. +[docs/sigmahq-submission.md](docs/sigmahq-submission.md) records which `microsoft365_*` finance rules meet SigmaHQ +conventions and which edits were applied in this repo. That note is preparation only. No pull request has been +opened against SigmaHQ. + ## Version pins `requirements.txt` pins exact versions: @@ -261,11 +319,13 @@ Only rules that exist have been checked. Each new rule gets the same check first | pySigma | 1.5.1 | | pysigma-backend-sqlite | 2.0.0 | | pysigma-backend-splunk | 2.1.0 | +| pysigma-backend-kusto | 1.0.1 | | sigma-cli | 3.1.0 | sigma-cli 3.1.0 requires pySigma below 2.0, and the newer SQLite backend (2.1.x) requires pySigma 2.0.1 or newer, so -the two cannot be installed together. The set above was verified to install and pass every gate. Revisit the pins when -a sigma-cli release supports pySigma 2.x. +the two cannot be installed together. pysigma-backend-kusto 1.0.1 is the newest Kusto release that still accepts +pySigma 1.x. The set above was verified to install and pass every gate. Revisit the pins when a sigma-cli release +supports pySigma 2.x. ## Roadmap diff --git a/docs/erp-log-schema.md b/docs/erp-log-schema.md index ce3fec0..74ba8f1 100644 --- a/docs/erp-log-schema.md +++ b/docs/erp-log-schema.md @@ -98,6 +98,7 @@ can be thin. That is a design intent, not tested support: SigmaFin has not been ## Using the schema with a backend -`pipelines/sigmafin_splunk.yml` maps each service to a Splunk sourcetype (made-up names that you should change). To +`pipelines/sigmafin_splunk.yml` maps each service to a Splunk sourcetype (made-up names that you should change). +`pipelines/sigmafin_kusto.yml` maps each service to a KQL table name (`sigmafin_erp_*`, also a placeholder). To rename fields to your ERP's column names, add `field_name_mapping` transformations conditioned on the logsource. The -file contains a commented, untested example of the shape. +Splunk file contains a commented, untested example of the shape. The Kusto file has the same example. diff --git a/docs/m365-fields.md b/docs/m365-fields.md index 9b81807..170c39d 100644 --- a/docs/m365-fields.md +++ b/docs/m365-fields.md @@ -19,7 +19,9 @@ parameter as its own field named `Parameters.`: Flatten at ingestion (for example with a Splunk field extraction or an ingestion pipeline). SigmaFin does not ship this normalization. SigmaHQ M365 rules solve the same problem differently, by matching the serialized list with -`Parameters|contains`, which cannot express an external domain check. +`Parameters|contains`, which cannot express an external domain check. Generated KQL keeps these dotted names and +writes them as KQL bracket identifiers, for example `['Parameters.ForwardTo']`. The stock Sentinel `OfficeActivity` +table still stores `Parameters` as a property bag until you promote the flattened columns. Known limitation: when one parameter holds several recipients, the rules judge only the end of the value against the internal domains. Normalizing to one event per recipient removes the limitation. diff --git a/docs/rule-writing-guide.md b/docs/rule-writing-guide.md index d3c387d..6d33eab 100644 --- a/docs/rule-writing-guide.md +++ b/docs/rule-writing-guide.md @@ -20,7 +20,8 @@ correlation its own support rules: a support rule shared by two correlations makes pySigma fail when the whole `rules/` directory is converted ("Conversion state not available"), so copy it and list the copy under `mirrors`. Give the support rules `status`, tests and a `support_rules` entry in `policy.yml`. The SQLite backend converts - `event_count`, `value_count`, `temporal` and `temporal_ordered`; the Splunk backend 2.1.0 does not convert - `temporal_ordered`. -8. **Run everything.** `sigma check -i rules`, `pytest`, `python scripts/gen_docs.py`, `python scripts/build_spl.py`. + `event_count`, `value_count`, `temporal` and `temporal_ordered`. The Splunk backend 2.1.0 does not convert + `temporal_ordered`. The Kusto backend 1.0.1 does not convert any correlation type. +8. **Run everything.** `sigma check -i rules`, `pytest`, `python scripts/gen_docs.py`, `python scripts/build_spl.py`, + `python scripts/build_kql.py`. 9. **No em dashes** in docs, comments or commit messages. CI enforces this. diff --git a/docs/sigmahq-submission.md b/docs/sigmahq-submission.md new file mode 100644 index 0000000..2d72717 --- /dev/null +++ b/docs/sigmahq-submission.md @@ -0,0 +1,123 @@ +# SigmaHQ submission + +Prepared in this repository on 2026-11-22. Not submitted. No pull request was opened against +[SigmaHQ/sigma](https://github.com/SigmaHQ/sigma). + +## Scope + +The file glob `rules/bec_payment_fraud/m365_*` at the start of this note. Three rules. They are renamed below to +`microsoft365_*` and stay in `rules/bec_payment_fraud/`. + +`m365_inbox_rule_change_event` is a rule name inside `entra_anonymous_signin_then_inbox_rule.yml`. That file does +not match the glob, so the support rule is outside this note. + +Conventions checked, and only these: + +- [SigmaHQ rule conventions](https://sigmahq.io/sigma-specification/sigmahq/sigmahq-rule-convention.html): `id`, + `status`, `level`, `falsepositives`, `references` +- [SigmaHQ filename conventions](https://sigmahq.io/sigma-specification/sigmahq/sigmahq-filename-convention.html): + product `m365` uses the `microsoft365_*` pattern +- [Sigma taxonomy](https://sigmahq.io/sigma-specification/specification/sigma-appendix-taxonomy.html): `product: m365` + with `service: audit` is a listed logsource + +## Summary + +| Rule file (after the rename) | id | status | logsource | level | falsepositives | references | filename | +|---|---|---|---|---|---|---|---| +| `microsoft365_inbox_rule_external_forward_finance.yml` | meets | meets | meets | meets | meets | fixed | fixed | +| `microsoft365_inbox_rule_hides_finance_mail.yml` | meets | meets | meets | meets | meets | fixed | fixed | +| `microsoft365_mailbox_forwarding_external_finance.yml` | meets | meets | meets | meets | meets | fixed | fixed | + +After the edits in this repository, all three meet the seven checks. The per-rule sections say what was already +true and what changed. + +## What already met the conventions + +**id.** Required, and a UUID version 4 is the form SigmaHQ expects. Each id below parses as version 4 with the +RFC 4122 variant, is lowercase, and is unique in this repository. None were changed. + +**status.** A new SigmaHQ rule starts at `experimental`. All three were already `experimental`. + +**logsource.** All three already set `product: m365` and `service: audit`, which the taxonomy lists for M365. + +**level.** `high` and `medium` are allowed values. + +- `m365_inbox_rule_external_forward_finance`: `high` +- `m365_inbox_rule_hides_finance_mail`: `medium` +- `m365_mailbox_forwarding_external_finance`: `high` + +The related SigmaHQ hunting rule `c726e007-2cd0-4a55-abfb-79730fbedee5` is `medium`. That difference is a tuning +choice a reviewer might question. It is not a convention miss, so the levels were left as they are. + +**falsepositives.** Each rule already lists specific operational cases (approved outsourcing, leave forwarding, +migrations, user filing rules). None use the rejected keywords `None`, `Pentest`, `Penetration Test`, or `Red Team`. + +Titles are already title case, and each description already starts with "Detects". Those points are in the same +convention document and were already satisfied, so they were not edited. + +## What each rule needed + +### `microsoft365_inbox_rule_external_forward_finance.yml` + +Rule `name`: `m365_inbox_rule_external_forward_finance`. Id `4b0f8f5e-2c6a-4d1e-9a47-3e5d7b1c9f20`. + +- **references.** The list included `https://attack.mitre.org/techniques/T1114/003/`. SigmaHQ does not allow MITRE + ATT&CK website links in `references`. The technique stays in the tags `attack.collection` and `attack.t1114.003`. + The link was removed. The remaining references are `https://www.ic3.gov/CSA/2020/201204.pdf` and + `https://www.ic3.gov/PSA/2020/PSA200406`. +- **filename.** The file was `m365_inbox_rule_external_forward_finance.yml`. The product pattern is + `microsoft365_*`. Renamed to `microsoft365_inbox_rule_external_forward_finance.yml` (52 characters, inside the + 10 to 70 character filename length). + +### `microsoft365_inbox_rule_hides_finance_mail.yml` + +Rule `name`: `m365_inbox_rule_hides_finance_mail`. Id `8e3c1a57-6d24-4b9f-a0c8-5f27d9b4e611`. + +- **references.** Removed `https://attack.mitre.org/techniques/T1564/008/`. The technique stays in the tags + `attack.stealth` and `attack.t1564.008`. The remaining references are the Red Canary email hiding rules page, the + Microsoft cookie-theft to BEC blog post from 2022-07-12, and the Microsoft Defender page on responding to a + compromised email account. +- **filename.** Renamed from `m365_inbox_rule_hides_finance_mail.yml` to + `microsoft365_inbox_rule_hides_finance_mail.yml` (46 characters). + +### `microsoft365_mailbox_forwarding_external_finance.yml` + +Rule `name`: `m365_mailbox_forwarding_external_finance`. Id `2d9a6b40-7c13-4e85-b1f6-0a4e8c3d5927`. + +- **references.** Removed `https://attack.mitre.org/techniques/T1114/003/`. The technique stays in the tags + `attack.collection` and `attack.t1114.003`. The remaining references are the Microsoft Defender compromised-account + page, the Exchange Online forwarding documentation, and `https://www.ic3.gov/PSA/2020/PSA200406`. +- **filename.** Renamed from `m365_mailbox_forwarding_external_finance.yml` to + `microsoft365_mailbox_forwarding_external_finance.yml` (52 characters). + +Each edited rule has `modified: 2026-11-22`. `modified` is optional in the convention. It records this edit. + +## Edits applied in this repository + +- The three filenames now use the `microsoft365_*` prefix. +- The three `references` lists no longer contain `attack.mitre.org` links. +- `name` was not changed. Tests, correlations, and `scripts/policy.yml` key off `m365_*`. + +## Still open before a SigmaHQ pull request + +These items are outside the seven checks. They were not changed here, because changing them would change the +detection or this repository's layout. A copy made for SigmaHQ still needs them. + +- **Placeholders.** All three rules expand `%finance_mailboxes%` and, where they check the recipient, + `%internal_domains%` through `|expand` and `pipelines/finance_scope.yml`. SigmaHQ conversion does not load that + pipeline. A submission copy has to replace the placeholders with something SigmaHQ can convert, or ship an + equivalent pipeline the project will accept. +- **Flattened parameters.** The rules match `Parameters.`. The overlapping SigmaHQ rules match the serialized + `Parameters` list with `|contains`. The descriptions already say the fields are flattened. A `logsource.definition` + like the one on `microsoft365_susp_email_forwarding_activity.yml` would tell a reviewer that. It was not added, + because `product` and `service` already match the taxonomy. +- **Filter names.** SigmaHQ recommends `filter_main_*` for mandatory exclusions and `filter_optional_*` for local + ones. These rules use `filter_internal_*`. That recommendation was not applied, so the detection text stays + aligned with the samples. +- **`name`.** SigmaHQ rules usually omit `name`. The field is allowed as a custom attribute. Drop it in the + SigmaHQ copy if a reviewer asks. Keep it in this repository. +- **Directory.** SigmaHQ would place an `m365` / `audit` rule under `rules/cloud/m365/` or + `rules-threat-hunting/cloud/m365/audit/` (the overlapping hunting rules use the second path). This repository + keeps `rules/bec_payment_fraud/` because the test folders are `tests///`. Move the file only in + the upstream pull request. Which of the two SigmaHQ trees fits is a maintainer decision: these rules are narrower + than the hunting rules, and they still document false positives. diff --git a/pipelines/sigmafin_kusto.yml b/pipelines/sigmafin_kusto.yml new file mode 100644 index 0000000..10672a1 --- /dev/null +++ b/pipelines/sigmafin_kusto.yml @@ -0,0 +1,72 @@ +# Maps SigmaFin logsources to Kusto table names. +# +# The table values are assumptions: change them to match how your data is +# onboarded. OfficeActivity and SigninLogs are the Microsoft Sentinel tables +# whose column names match the fields these rules already use (see +# docs/m365-fields.md and docs/entra-fields.md). Defender XDR advanced hunting +# uses different tables and columns (CloudAppEvents, AADSignInEventsBeta, and +# so on). Point the same logsource at your Defender table and add a +# field_name_mapping if you hunt there. "sigmafin_erp_*" is a made-up name for +# the vendor-neutral ERP schema in docs/erp-log-schema.md. To map the generic +# ERP field names to the columns of a specific audit table, add a +# field_name_mapping transformation conditioned on the same logsource (see the +# commented example). +name: SigmaFin Kusto table mapping +priority: 20 +allowed_backends: + - kusto +transformations: + - id: m365_audit_table + type: set_state + key: query_table + val: OfficeActivity + rule_conditions: + - type: logsource + product: m365 + service: audit + - id: entra_signinlogs_table + type: set_state + key: query_table + val: SigninLogs + rule_conditions: + - type: logsource + product: azure + service: signinlogs + - id: erp_vendor_master_table + type: set_state + key: query_table + val: sigmafin_erp_vendor_master + rule_conditions: + - type: logsource + product: erp + service: vendor_master + - id: erp_payments_table + type: set_state + key: query_table + val: sigmafin_erp_payments + rule_conditions: + - type: logsource + product: erp + service: payments + - id: erp_user_admin_table + type: set_state + key: query_table + val: sigmafin_erp_user_admin + rule_conditions: + - type: logsource + product: erp + service: user_admin + # Illustrative only, not tested against any real ERP: + # - id: erp_vendor_master_field_names + # type: field_name_mapping + # mapping: + # vendor_id: SUPPLIER_NO + # rule_conditions: + # - type: logsource + # product: erp + # service: vendor_master +postprocessing: + - type: template + template: | + {{ pipeline.state['query_table'] }} + | where {{ query }} diff --git a/requirements.txt b/requirements.txt index dba6cb8..ed3a01f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,5 +5,7 @@ pysigma==1.5.1 sigma-cli==3.1.0 pysigma-backend-sqlite==2.0.0 pysigma-backend-splunk==2.1.0 +# 1.0.1 is the newest Kusto backend that still accepts pySigma 1.x. +pysigma-backend-kusto==1.0.1 pytest==9.1.1 PyYAML==6.0.3 diff --git a/rules/bec_payment_fraud/entra_anonymous_signin_then_inbox_rule.yml b/rules/bec_payment_fraud/entra_anonymous_signin_then_inbox_rule.yml index f9fb08d..e94b331 100644 --- a/rules/bec_payment_fraud/entra_anonymous_signin_then_inbox_rule.yml +++ b/rules/bec_payment_fraud/entra_anonymous_signin_then_inbox_rule.yml @@ -73,7 +73,8 @@ description: | the severity when an inbox rule change follows. The correlation uses its own copies of both conditions (entra_finance_anonymous_signin_event and m365_inbox_rule_change_event) so everything can be deployed together. Needs a backend with temporal_ordered correlation support. The pySigma Splunk backend 2.1.0 does not convert it, - so this rule is tested on the SQLite backend only and has no SPL output. + and the pySigma Kusto backend 1.0.1 does not convert correlation rules, so this rule is tested on the SQLite + backend only and has no SPL or KQL output. references: - https://www.microsoft.com/en-us/security/blog/2022/07/12/from-cookie-theft-to-bec-attackers-use-aitm-phishing-sites-as-entry-point-to-further-financial-fraud/ - https://learn.microsoft.com/en-us/defender-office-365/responding-to-a-compromised-email-account diff --git a/rules/bec_payment_fraud/m365_inbox_rule_external_forward_finance.yml b/rules/bec_payment_fraud/microsoft365_inbox_rule_external_forward_finance.yml similarity index 98% rename from rules/bec_payment_fraud/m365_inbox_rule_external_forward_finance.yml rename to rules/bec_payment_fraud/microsoft365_inbox_rule_external_forward_finance.yml index f266247..6f0c030 100644 --- a/rules/bec_payment_fraud/m365_inbox_rule_external_forward_finance.yml +++ b/rules/bec_payment_fraud/microsoft365_inbox_rule_external_forward_finance.yml @@ -20,11 +20,11 @@ description: | "external@mail.example.net;colleague@corp.example.com"), the rule misses it; this is asserted in tests/known_gaps/. references: - - https://attack.mitre.org/techniques/T1114/003/ - https://www.ic3.gov/CSA/2020/201204.pdf - https://www.ic3.gov/PSA/2020/PSA200406 author: SigmaFin Contributors date: 2026-10-20 +modified: 2026-11-22 tags: - attack.collection - attack.t1114.003 diff --git a/rules/bec_payment_fraud/m365_inbox_rule_hides_finance_mail.yml b/rules/bec_payment_fraud/microsoft365_inbox_rule_hides_finance_mail.yml similarity index 98% rename from rules/bec_payment_fraud/m365_inbox_rule_hides_finance_mail.yml rename to rules/bec_payment_fraud/microsoft365_inbox_rule_hides_finance_mail.yml index 732608c..28d21c5 100644 --- a/rules/bec_payment_fraud/m365_inbox_rule_hides_finance_mail.yml +++ b/rules/bec_payment_fraud/microsoft365_inbox_rule_hides_finance_mail.yml @@ -20,12 +20,12 @@ description: | Known limitation: a rule that selects mail by sender domain only, without keywords (the pattern in the Microsoft report), is not matched. This is asserted in tests/known_gaps/. references: - - https://attack.mitre.org/techniques/T1564/008/ - https://redcanary.com/threat-detection-report/techniques/email-hiding-rules/ - https://www.microsoft.com/en-us/security/blog/2022/07/12/from-cookie-theft-to-bec-attackers-use-aitm-phishing-sites-as-entry-point-to-further-financial-fraud/ - https://learn.microsoft.com/en-us/defender-office-365/responding-to-a-compromised-email-account author: SigmaFin Contributors date: 2026-10-20 +modified: 2026-11-22 tags: - attack.stealth - attack.t1564.008 diff --git a/rules/bec_payment_fraud/m365_mailbox_forwarding_external_finance.yml b/rules/bec_payment_fraud/microsoft365_mailbox_forwarding_external_finance.yml similarity index 98% rename from rules/bec_payment_fraud/m365_mailbox_forwarding_external_finance.yml rename to rules/bec_payment_fraud/microsoft365_mailbox_forwarding_external_finance.yml index 42dca0e..87bf778 100644 --- a/rules/bec_payment_fraud/m365_mailbox_forwarding_external_finance.yml +++ b/rules/bec_payment_fraud/microsoft365_mailbox_forwarding_external_finance.yml @@ -20,12 +20,12 @@ description: | and Microsoft documents it as an internal recipient, so it is not covered. A mail contact that points outside is not seen by this rule. Inbox rule forwarding is covered by m365_inbox_rule_external_forward_finance. references: - - https://attack.mitre.org/techniques/T1114/003/ - https://learn.microsoft.com/en-us/defender-office-365/responding-to-a-compromised-email-account - https://learn.microsoft.com/en-us/exchange/recipients-in-exchange-online/manage-user-mailboxes/configure-email-forwarding - https://www.ic3.gov/PSA/2020/PSA200406 author: SigmaFin Contributors date: 2026-10-20 +modified: 2026-11-22 tags: - attack.collection - attack.t1114.003 diff --git a/rules/erp_vendor_payment/erp_new_vendor_created_then_paid.yml b/rules/erp_vendor_payment/erp_new_vendor_created_then_paid.yml index a880580..4c4291e 100644 --- a/rules/erp_vendor_payment/erp_new_vendor_created_then_paid.yml +++ b/rules/erp_vendor_payment/erp_new_vendor_created_then_paid.yml @@ -70,7 +70,8 @@ description: | The 3 day window is a starting point. Tune it to your onboarding process, which may be much longer, and consider suppressing vendors created through an approved onboarding workflow. Needs a backend with temporal_ordered correlation support. The pySigma Splunk backend 2.1.0 does not convert it, - so this rule is tested on the SQLite backend only and has no SPL output. + and the pySigma Kusto backend 1.0.1 does not convert correlation rules, so this rule is tested on the SQLite + backend only and has no SPL or KQL output. references: - https://www.oversight.gov/sites/default/files/documents/reports/2020-04/2019-15666.pdf - https://www.criadv.com/insight/unearthing-occupational-fraud-in-your-business diff --git a/rules/erp_vendor_payment/erp_vendor_bank_change_then_payment.yml b/rules/erp_vendor_payment/erp_vendor_bank_change_then_payment.yml index 0ba4633..92073df 100644 --- a/rules/erp_vendor_payment/erp_vendor_bank_change_then_payment.yml +++ b/rules/erp_vendor_payment/erp_vendor_bank_change_then_payment.yml @@ -72,7 +72,8 @@ description: | raises the severity when money moves. The correlation uses its own copy of the bank change condition (erp_vendor_bank_change_event) so both can be deployed together. Needs a backend with temporal_ordered correlation support. The pySigma Splunk backend 2.1.0 does not convert it, - so this rule is tested on the SQLite backend only and has no SPL output. + and the pySigma Kusto backend 1.0.1 does not convert correlation rules, so this rule is tested on the SQLite + backend only and has no SPL or KQL output. references: - https://attack.mitre.org/techniques/T1657/ - https://www.ic3.gov/PSA/2017/PSA170504 diff --git a/rules/erp_vendor_payment/erp_vendor_created_and_payment_approved_by_same_user.yml b/rules/erp_vendor_payment/erp_vendor_created_and_payment_approved_by_same_user.yml index e2f11b4..c7b872e 100644 --- a/rules/erp_vendor_payment/erp_vendor_created_and_payment_approved_by_same_user.yml +++ b/rules/erp_vendor_payment/erp_vendor_created_and_payment_approved_by_same_user.yml @@ -61,7 +61,8 @@ description: | expects access authorizations that support separation of duties, and describes it as reducing the risk of abuse without collusion. The correlation is unordered (temporal): approving a payment to a vendor that does not exist yet cannot happen, - so the order adds nothing, and unordered correlations convert to Splunk. + so the order adds nothing, and unordered correlations convert to Splunk. The pySigma Kusto backend 1.0.1 does + not convert correlation rules, so this rule has no KQL output. No ATT&CK technique applies. This is business process fraud, tagged with no ATT&CK technique. It only sees the approval event. If your ERP puts the approving account in a different field than user, map it into user at ingestion (docs/erp-log-schema.md). Small teams where one person legitimately does both need an diff --git a/scripts/build_kql.py b/scripts/build_kql.py new file mode 100644 index 0000000..b007733 --- /dev/null +++ b/scripts/build_kql.py @@ -0,0 +1,97 @@ +"""Convert every SigmaFin rule to Kusto Query Language (KQL). + +Writes build/kql//.kql and build/kql/SUMMARY.md. + +Conversion is strict. A rule that fails to convert fails the build unless it is +listed under kusto_unsupported in scripts/policy.yml, and a listed rule that +now converts also fails the build so the list cannot go stale. Support rules +(policy support_rules) are converted only as part of their correlation. + +The output is the same shape as scripts/build_spl.py. Table names come from +pipelines/sigmafin_kusto.yml. The shipped names are Microsoft Sentinel tables +where the rule fields already match (OfficeActivity, SigninLogs) and +placeholder names for the ERP schema. Defender XDR advanced hunting needs its +own table and field mapping in that pipeline. + +The Kusto backend quotes dotted field names with single quotes. In KQL a +single-quoted token is a string, so Parameters.ForwardTo would never match +the column. This script rewrites those identifiers to KQL bracket quotes. +String values stay double-quoted, which is how the backend emits them. +""" + +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +from sigma.backends.kusto import KustoBackend +from sigma.exceptions import SigmaError + +import sigmafin_lib as lib + +PIPELINES = ("finance_scope.yml", "sigmafin_kusto.yml") +TABLE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\n\| where ") +FIELD_QUOTE_RE = re.compile(r"'([A-Za-z_][\w.]*)'") + + +def kql_identifier_quotes(query: str) -> str: + """Turn backend single-quoted field names into KQL bracket identifiers.""" + return FIELD_QUOTE_RE.sub(r"['\1']", query) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--out", type=Path, default=lib.ROOT / "build" / "kql") + parser.add_argument("--policy", type=Path, default=lib.POLICY_FILE) + args = parser.parse_args(argv) + + policy = lib.load_policy(args.policy) + unsupported = {e["name"]: e["reason"] for e in policy.get("kusto_unsupported", [])} + support = set(policy.get("support_rules", [])) + docs = lib.load_rule_docs() + index = lib.index_docs(docs) + + failures: list[str] = [] + rows: list[tuple[str, str, str]] = [] + for doc in docs: + if doc.name in support: + rows.append((doc.name, "support rule", "converted only inside its correlation")) + continue + backend = KustoBackend(processing_pipeline=lib.load_pipeline(*PIPELINES)) + try: + queries = [kql_identifier_quotes(str(q)) for q in backend.convert(lib.build_collection(doc, index))] + except (SigmaError, NotImplementedError) as exc: + if doc.name in unsupported: + rows.append((doc.name, "unsupported", unsupported[doc.name])) + else: + failures.append(f"{doc.name}: conversion failed and is not listed in policy.yml: {exc}") + continue + if doc.name in unsupported: + failures.append(f"{doc.name}: listed as kusto_unsupported but it converts; remove it from policy.yml") + continue + missing = [q for q in queries if not TABLE_RE.match(q)] + if missing: + failures.append( + f"{doc.name}: KQL has no table name; add its logsource to pipelines/sigmafin_kusto.yml" + ) + continue + target = args.out / doc.theme / f"{doc.name}.kql" + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("\n\n".join(queries) + "\n", encoding="utf-8") + rows.append((doc.name, "converted", str(target.relative_to(args.out)))) + + args.out.mkdir(parents=True, exist_ok=True) + lines = ["# KQL conversion summary", "", "| Rule | Result | Detail |", "|---|---|---|"] + lines += [f"| {n} | {r} | {d} |" for n, r, d in rows] + (args.out / "SUMMARY.md").write_text("\n".join(lines) + "\n", encoding="utf-8") + for row in rows: + print(" | ".join(row)) + for failure in failures: + print(f"ERROR {failure}") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check_metadata.py b/scripts/check_metadata.py index b3cfc9e..8054cc9 100644 --- a/scripts/check_metadata.py +++ b/scripts/check_metadata.py @@ -94,7 +94,12 @@ def check(rules_dir: Path, tests_dir: Path, policy_file: Path) -> list[str]: if support.data.get(key) != original.data.get(key): errors.append(f"{support.name}: {key} differs from {original.name} (mirrored rules must match)") - for entry in policy.get("no_technique", []) + policy.get("support_rules", []) + policy.get("splunk_unsupported", []): + for entry in ( + policy.get("no_technique", []) + + policy.get("support_rules", []) + + policy.get("splunk_unsupported", []) + + policy.get("kusto_unsupported", []) + ): name = entry["name"] if isinstance(entry, dict) else entry if name not in index: errors.append(f"policy.yml lists unknown rule {name!r}") diff --git a/scripts/gen_docs.py b/scripts/gen_docs.py index 7384f62..048d35a 100644 --- a/scripts/gen_docs.py +++ b/scripts/gen_docs.py @@ -64,21 +64,26 @@ def technique_cell(doc: lib.RuleDoc, support: set[str]) -> str: return ", ".join(f"{t} {mitre_attack_techniques.get(t, '?')}" for t in ts) -def note(doc: lib.RuleDoc, unsupported: set[str], support: set[str]) -> str: +def note(doc: lib.RuleDoc, splunk_unsupported: set[str], kusto_unsupported: set[str], support: set[str]) -> str: if doc.name in support: return "Support rule, not deployed alone" - if doc.name in unsupported: + gaps = [] + if doc.name in splunk_unsupported: ctype = doc.data["correlation"]["type"] - return f"Sigma + SQLite tested, no SPL (Splunk backend lacks {ctype})" - return "" + gaps.append(f"no SPL (Splunk backend lacks {ctype})") + if doc.name in kusto_unsupported: + gaps.append("no KQL (Kusto backend has no correlation support)") + if not gaps: + return "" + return "Sigma + SQLite tested, " + "; ".join(gaps) -def build_readme_table(docs, index, support, unsupported) -> str: +def build_readme_table(docs, index, support, splunk_unsupported, kusto_unsupported) -> str: lines = ["| Rule | Theme | ATT&CK technique | Log source | Level | Notes |", "|---|---|---|---|---|---|"] for doc in sorted(docs, key=lambda d: (list(THEMES).index(d.theme) if d.theme in THEMES else 99, d.name)): lines.append( f"| {doc.data['title']} (`{doc.name}`) | {THEMES.get(doc.theme, doc.theme)} | {technique_cell(doc, support)} " - f"| {logsource(doc, index)} | {doc.data['level']} | {note(doc, unsupported, support)} |" + f"| {logsource(doc, index)} | {doc.data['level']} | {note(doc, splunk_unsupported, kusto_unsupported, support)} |" ) return "\n".join(lines) @@ -136,7 +141,8 @@ def main(argv=None) -> int: index = lib.index_docs(docs) policy = lib.load_policy() support = set(policy.get("support_rules", [])) - unsupported = {e["name"] for e in policy.get("splunk_unsupported", [])} + splunk_unsupported = {e["name"] for e in policy.get("splunk_unsupported", [])} + kusto_unsupported = {e["name"] for e in policy.get("kusto_unsupported", [])} overlap = yaml.safe_load(OVERLAP.read_text(encoding="utf-8")) readme = README.read_text(encoding="utf-8") @@ -144,7 +150,10 @@ def main(argv=None) -> int: if not pattern.search(readme): print(f"README.md is missing the {START} / {END} markers") return 1 - new_readme = pattern.sub(lambda _: f"{START}\n{build_readme_table(docs, index, support, unsupported)}\n{END}", readme) + new_readme = pattern.sub( + lambda _: f"{START}\n{build_readme_table(docs, index, support, splunk_unsupported, kusto_unsupported)}\n{END}", + readme, + ) outputs = { DOCS / "rule-catalog.md": build_catalog(docs, index, support, overlap), diff --git a/scripts/policy.yml b/scripts/policy.yml index 0bd4f4f..ae3230f 100644 --- a/scripts/policy.yml +++ b/scripts/policy.yml @@ -1,6 +1,6 @@ # Explicit exceptions to the CI gates. Every entry needs a reason. # Anything not listed here is held to the full rule: ATT&CK technique tag, -# Splunk conversion succeeds. +# Splunk conversion succeeds, and Kusto conversion succeeds. # Rules allowed to carry no attack.tNNNN tag. The description of each must # contain the text "No ATT&CK" or "no ATT&CK" so the reader is told why. @@ -61,3 +61,16 @@ splunk_unsupported: reason: Splunk backend 2.1.0 lacks temporal_ordered correlation support. Sigma + SQLite tested, no SPL. - name: erp_new_vendor_paid_quickly reason: Splunk backend 2.1.0 lacks temporal_ordered correlation support. Sigma + SQLite tested, no SPL. + +# Rules the pySigma Kusto backend cannot convert. CI fails if a rule fails to +# convert and is not listed here, and also if a listed rule starts converting. +# Backend 1.0.1 has no Sigma correlation support at all. +kusto_unsupported: + - name: erp_vendor_bank_change_then_payment + reason: Kusto backend 1.0.1 does not convert correlation rules. Sigma + SQLite tested, no KQL. + - name: entra_anonymous_signin_then_inbox_rule + reason: Kusto backend 1.0.1 does not convert correlation rules. Sigma + SQLite tested, no KQL. + - name: erp_new_vendor_paid_quickly + reason: Kusto backend 1.0.1 does not convert correlation rules. Sigma + SQLite tested, no KQL. + - name: erp_vendor_created_and_payment_approved_by_same_user + reason: Kusto backend 1.0.1 does not convert correlation rules. Splunk still converts this temporal rule. Sigma + SQLite tested, no KQL. diff --git a/tests/test_gates.py b/tests/test_gates.py index 369490a..f75261d 100644 --- a/tests/test_gates.py +++ b/tests/test_gates.py @@ -17,6 +17,7 @@ SCRIPTS = Path(__file__).resolve().parents[1] / "scripts" sys.path.insert(0, str(SCRIPTS)) +import build_kql # noqa: E402 import build_spl # noqa: E402 import check_metadata # noqa: E402 import check_no_em_dash # noqa: E402 @@ -95,7 +96,7 @@ def test_metadata_gate_fails_on_missing_negative_sample(tree): def test_metadata_gate_fails_on_duplicate_id(tree): - other = tree / "rules" / "bec_payment_fraud" / "m365_inbox_rule_external_forward_finance.yml" + other = tree / "rules" / "bec_payment_fraud" / "microsoft365_inbox_rule_external_forward_finance.yml" _edit(other, "4b0f8f5e-2c6a-4d1e-9a47-3e5d7b1c9f20", "9c3a1e7d-5f42-4b8a-8d16-0a7e2b4c6d51") assert _meta(tree) != 0 @@ -117,6 +118,38 @@ def test_spl_build_fails_when_listed_rule_actually_converts(tmp_path): assert build_spl.main(["--out", str(tmp_path / "out"), "--policy", str(policy)]) != 0 +def test_kql_build_fails_when_unsupported_rule_is_not_listed(tmp_path): + empty = tmp_path / "policy.yml" + empty.write_text("no_technique: []\nsupport_rules: [erp_vendor_payment_released]\nkusto_unsupported: []\n") + assert build_kql.main(["--out", str(tmp_path / "out"), "--policy", str(empty)]) != 0 + + +def test_kql_build_fails_when_listed_rule_actually_converts(tmp_path): + policy = tmp_path / "policy.yml" + policy.write_text( + "no_technique: []\nsupport_rules: [erp_vendor_payment_released]\n" + "kusto_unsupported:\n" + " - {name: entra_anonymous_signin_then_inbox_rule, reason: x}\n" + " - {name: erp_vendor_bank_details_changed, reason: stale entry}\n" + ) + assert build_kql.main(["--out", str(tmp_path / "out"), "--policy", str(policy)]) != 0 + + +def test_kql_build_writes_queries_and_skips_unsupported(tmp_path): + out = tmp_path / "kql" + assert build_kql.main(["--out", str(out)]) == 0 + text = (out / "bec_payment_fraud" / "m365_inbox_rule_external_forward_finance.kql").read_text(encoding="utf-8") + assert text.startswith("OfficeActivity\n| where ") + assert "['Parameters.ForwardTo']" in text + bare = text.replace("['Parameters.ForwardTo']", "") + assert "'Parameters.ForwardTo'" not in bare + assert not (out / "bec_payment_fraud" / "entra_anonymous_signin_then_inbox_rule.kql").exists() + summary = (out / "SUMMARY.md").read_text(encoding="utf-8") + assert "| entra_anonymous_signin_then_inbox_rule | unsupported |" in summary + assert "| erp_vendor_created_and_payment_approved_by_same_user | unsupported |" in summary + assert "| erp_vendor_bank_details_changed | converted |" in summary + + def test_em_dash_gate_fails_on_em_dash(tmp_path): bad = tmp_path / "doc.md" bad.write_text("text " + chr(0x2014) + " text\n", encoding="utf-8")