Skip to content

add sequence statement for ordered matching#2816

Draft
mike-hunhoff wants to merge 1 commit intomasterfrom
feature/sequence
Draft

add sequence statement for ordered matching#2816
mike-hunhoff wants to merge 1 commit intomasterfrom
feature/sequence

Conversation

@mike-hunhoff
Copy link
Collaborator

This PR, thanks to vibe coding, introduces a sequence statement to capa's rule language, enabling the enforcement of strict temporal or spatial ordering for matched features. Unlike and, which requires only the presence of features, sequence mandates that child statements occur in increasing address order (e.g., sequential API calls in dynamic analysis or ordered instructions in static analysis). The implementation leverages a greedy matching strategy to satisfy constraints.

In practice, a rule looks like:

rule:
  meta:
    name: persist via Run registry key
    namespace: persistence/registry/run
[...]
  features:
    - sequence:
      - call:
        - and:
          - match: create or open registry key
          - or:
            - string: /Software\\Microsoft\\Windows\\CurrentVersion\\Run/i
            - string: /Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders/i
            - string: /Software\\Microsoft\\Windows\\CurrentVersion\\User Shell Folders/i
            - string: /Software\\Microsoft\\Windows\\CurrentVersion\\RunServices/i
            - string: /Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run/i
            - string: /Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\Load/i
            - string: /System\\(ControlSet\d{3}|CurrentControlSet)\\Control\\Session Manager\\BootExecute/i
      - match: set registry value

and matches like:

persist via Run registry key (2 matches)
namespace  persistence/registry/run                                                                      
author     moritz.raabe@mandiant.com, mehunhoff@google.com                                               
scope      span of calls                                                                                 
att&ck     Persistence::Boot or Logon Autostart Execution::Registry Run Keys / Startup Folder [T1547.001]
mbc        Persistence::Registry Run Keys / Startup Folder [F0012]                                       
span of calls @ webcam_plugin.exe (C:\Users\38lTTV5Kii\AppData\Roaming\Microsot_Centre\webcam_plugin.exe){pid:2464,tid:5512,calls:{4756,4757}}
  sequence:
    call:
      and:
        match: create or open registry key
          or:
            api: RegCreateKeyEx @ call:4756
              RegCreateKeyExA(
                hKey: 0x80000002,
                lpSubKey: "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run",
                Reserved: 0x0,
                lpClass: 0x0,
                dwOptions: 0x0,
                samDesired: 0x20006,
                lpSecurityAttributes: 0x0,
                phkResult: 0x19fe88,
                lpdwDisposition: 0x19fe8c,
              ) -> phkResult: 0x178, lpdwDisposition: 0x2, ret_val: 0x0
        or:
          regex: /Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run/i
            - "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run" @ call:4756
              RegCreateKeyExA(
                hKey: 0x80000002,
                lpSubKey: "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run",
                Reserved: 0x0,
                lpClass: 0x0,
                dwOptions: 0x0,
                samDesired: 0x20006,
                lpSecurityAttributes: 0x0,
                phkResult: 0x19fe88,
                lpdwDisposition: 0x19fe8c,
              ) -> phkResult: 0x178, lpdwDisposition: 0x2, ret_val: 0x0
    match: set registry value
      or:
        or:
          api: RegSetValueEx @ call:4757
            RegSetValueExA(
              hKey: 0x178,
              lpValueName: "IExploreupdate",
              Reserved: 0x0,
              dwType: 0x1,
              lpData: "C:\\Users\\38lTTV5Kii\\AppData\\Roaming\\Microsot_Centre\\kscribexq.exe",
              cbData: 0x42,
            ) -> lpData: "C:\\Users\\38lTTV5Kii\\AppData\\Roaming\\Microsot_Centre\\kscribexq.exe", ret_val: 0x0

versus current results:

persist via Run registry key (2 matches)
namespace  persistence/registry/run                                                                      
author     moritz.raabe@mandiant.com, mehunhoff@google.com                                               
scope      span of calls                                                                                 
att&ck     Persistence::Boot or Logon Autostart Execution::Registry Run Keys / Startup Folder [T1547.001]
mbc        Persistence::Registry Run Keys / Startup Folder [F0012]                                       
span of calls @ webcam_plugin.exe (C:\Users\38lTTV5Kii\AppData\Roaming\Microsot_Centre\webcam_plugin.exe){pid:2464,tid:5512,calls:{4742,4756}}
  and:
    or:
      match: set registry value
        or:
          and:
            or:
              api: RegSetValueEx @ call:4742
                RegSetValueExA(
                  hKey: 0x178,
                  lpValueName: "KeyData",
                  Reserved: 0x0,
                  dwType: 0x1,
                  lpData: "1768590918",
                  cbData: 0xb,
                ) -> lpData: "1768590918", ret_val: 0x0
    or:
      regex: /Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run/i
        - "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run" @ call:4756
          RegCreateKeyExA(
            hKey: 0x80000002,
            lpSubKey: "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run",
            Reserved: 0x0,
            lpClass: 0x0,
            dwOptions: 0x0,
            samDesired: 0x20006,
            lpSecurityAttributes: 0x0,
            phkResult: 0x19fe88,
            lpdwDisposition: 0x19fe8c,
          ) -> phkResult: 0x178, lpdwDisposition: 0x2, ret_val: 0x0

@mike-hunhoff mike-hunhoff requested review from a team and williballenthin January 16, 2026 23:40
Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add bug fixes, new features, breaking changes and anything else you think is worthwhile mentioning to the master (unreleased) section of CHANGELOG.md. If no CHANGELOG update is needed add the following to the PR description: [x] No CHANGELOG update needed

@mike-hunhoff mike-hunhoff marked this pull request as draft January 16, 2026 23:40
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @mike-hunhoff, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the expressiveness of capa's rule engine by introducing the sequence statement. This new capability allows rule authors to define patterns where the order of observed features is critical, enabling the detection of multi-step malicious behaviors that require specific temporal or spatial progression. The changes ensure that the rule engine can accurately identify and report such ordered sequences, providing more precise and context-aware threat intelligence.

Highlights

  • New sequence statement introduced: A new sequence statement has been added to capa's rule language, allowing for the enforcement of strict temporal or spatial ordering of matched features. This differs from the and statement by requiring children statements to occur in increasing address order.
  • Greedy Matching Strategy: The sequence statement is implemented using a greedy matching strategy to efficiently satisfy ordering constraints, picking the smallest valid location for each child to maximize room for subsequent matches.
  • Location Propagation in Logical Statements: The evaluate methods for And, Or, and Some statements have been updated to correctly propagate match locations within their Result objects. This change is critical for the sequence statement to accurately track and enforce feature ordering.
  • Integration into Rule Parsing and Rendering: The new sequence statement has been integrated into the rule parsing logic (capa/rules/__init__.py) and the result rendering (capa/render/result_document.py), ensuring it can be defined in YAML rules and displayed correctly in output.
  • Comprehensive Test Coverage: New unit tests have been added to validate the sequence statement's logic, including various ordering scenarios, greedy matching behavior, and its interaction with subscopes in a dynamic analysis context. Regression tests for location propagation in other logical statements were also added.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a sequence statement to enforce ordered matching, which is a valuable addition for creating more precise rules. The implementation is well-structured and includes good test coverage. I've identified a couple of potential issues: a duplicated enum member and the use of unique() on sequence children, which could lead to incorrect behavior. I've also suggested a refactoring to improve code clarity in the new Sequence class and pointed out a duplicated test case. Overall, this is a solid contribution.

AND = "and"
OR = "or"
NOT = "not"
NOT = "not"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The NOT enum member is duplicated. Please remove the redundant line to avoid potential issues.

elif key == "or":
return ceng.Or(unique(build_statements(dd, scopes) for dd in d[key]), description=description)
elif key == "sequence":
return ceng.Sequence(unique(build_statements(dd, scopes) for dd in d[key]), description=description)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using unique() on the children of a sequence statement prevents a rule from specifying a sequence of identical features (e.g., two consecutive push instructions). Since the order and multiplicity of features are significant in a sequence, unique() should not be used here. This allows rules to match patterns with repeated elements in a specific order.

Suggested change
return ceng.Sequence(unique(build_statements(dd, scopes) for dd in d[key]), description=description)
return ceng.Sequence([build_statements(dd, scopes) for dd in d[key]], description=description)

Comment on lines +371 to +386
if min_location is None:
min_location = valid_locations[0]
# Filter result to only include this location
results[-1] = Result(True, child, result.children, locations={min_location})
else:
# Find the first location that is strictly greater than min_location
found = False
for loc in valid_locations:
if loc > min_location:
min_location = loc
found = True
results[-1] = Result(True, child, result.children, locations={min_location})
break

if not found:
return Result(False, self, results)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The logic for finding the next valid location can be simplified to be more readable and concise by using a generator expression with next(). This avoids the use of a boolean flag (found) and repeated code, making the implementation easier to maintain.

            if min_location is None:
                # first child, pick the smallest location.
                min_location = valid_locations[0]
                results[-1] = Result(True, child, result.children, locations={min_location})
            else:
                # subsequent children, find the smallest location that is greater than the previous one.
                new_min_location = next((loc for loc in valid_locations if loc > min_location), None)
                if new_min_location is None:
                    return Result(False, self, results)

                min_location = new_min_location
                results[-1] = Result(True, child, result.children, locations={min_location})

Comment on lines +178 to +196
# 1 before 2 before 3 (fail, 3 is early)
assert (
bool(
Sequence([Number(1), Number(2), Number(3)]).evaluate(
{Number(1): {ADDR1}, Number(2): {ADDR4}, Number(3): {ADDR3}}
)
)
is False
)

# 1 before 2 before 3 (fail, 2 is late)
assert (
bool(
Sequence([Number(1), Number(2), Number(3)]).evaluate(
{Number(1): {ADDR1}, Number(2): {ADDR4}, Number(3): {ADDR3}}
)
)
is False
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This test case is duplicated. Additionally, the comment fail, 3 is early is a bit misleading for the provided data. I suggest replacing the duplicated blocks with a single, clearer test case that accurately reflects the scenario of an out-of-order feature.

Suggested change
# 1 before 2 before 3 (fail, 3 is early)
assert (
bool(
Sequence([Number(1), Number(2), Number(3)]).evaluate(
{Number(1): {ADDR1}, Number(2): {ADDR4}, Number(3): {ADDR3}}
)
)
is False
)
# 1 before 2 before 3 (fail, 2 is late)
assert (
bool(
Sequence([Number(1), Number(2), Number(3)]).evaluate(
{Number(1): {ADDR1}, Number(2): {ADDR4}, Number(3): {ADDR3}}
)
)
is False
)
# 1 before 2, but 3 is before 2 (fail)
assert (
bool(
Sequence([Number(1), Number(2), Number(3)]).evaluate(
{Number(1): {ADDR1}, Number(2): {ADDR3}, Number(3): {ADDR2}}
)
)
is False
)

@williballenthin
Copy link
Collaborator

neat experiment!

i think this is a great excuse for us all to have a call to catch up 😀

@mr-tz
Copy link
Collaborator

mr-tz commented Jan 19, 2026

good idea!

@mike-hunhoff
Copy link
Collaborator Author

@williballenthin @mr-tz this is an effort to address FPs highlighted in mandiant/capa-rules#1037 and #2627 (comment). It'd be great to discuss what's good or bad about this PR, and/or, alternative solutions that may be a better fit for capa. The end goal is to reduce FPs, primarily for dynamic scope, and enable downstream workflows that are presently blocked by the FP rate.

@williballenthin agree this is a good excuse for us all to chat 😄

@williballenthin
Copy link
Collaborator

As discussed yesterday, I think we should make this work for static scope, too. And, before that, make span (of calls? of features?) work for static scope, first. So we'll need to do some work to figure that out (including performance implications).

We also need to nail down whether sequences can match sequences, which might be a little tricky to reason about (how do sequences overlap?). We can start with a very strict and limited implementation (like sequence can only have call-scoped children) and then loosen it as we figure things out/have a need.

Ultimately, we should move forward with this research because it brings us closer to directly extracting indicators with capa, not just capabilities.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants