mandiant / mandiant/capa

tree-sitter: extract string features at file scope

Open Beginner friendly
#3,152 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement gsoc tree-sitter
Dominant language
Python
Stars
6.2k
Forks
726
Avg merge
11d 11h
Merged PRs (30d)
7

Description

String literals are only extracted at `function` scope (in functions and `PSEUDO MAIN`).

Because no `string` features are emitted at the `file` scope:
- Rules written with `scope: file` that look for string matches (`string: "..."` or `substring: "..."`) fail to match when analyzing script files.
- Running `show-features.py` at `file` scope lists top-level module imports but omits string constants defined in the file.

### Proposed Solution

1. **Extract Strings at File Scope**:
Add `extract_file_strings` to `FILE_HANDLERS` in `capa/features/extractors/ts/file.py`.

2. **Use Tree-Sitter AST String Literals & `FileOffsetRangeAddress`**:
Extract string literals across the script module root node using Tree-Sitter AST string nodes:
```python
def extract_file_strings(engine: TreeSitterExtractorEngine) -> Iterator[Tuple[Feature, Address]]:
for node in engine.get_string_literals(engine.tree.root_node):
yield String(engine.language_toolkit.parse_string(engine.get_str(node))), engine.get_address(node)
```
* Using Tree-Sitter AST nodes leverages exact character start/end byte offsets (`FileOffsetRangeAddress(start, end)`).
* This maintains address type consistency (`FileOffsetRangeAddress`) across the script analysis engine and ensures `scope: file` string rules match natively without breaking any output formats (`-v`, `-vv`, JSON).

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in capa/features/extractors/ts/file.py, reviewing FILE_HANDLERS and the existing function-scope string extraction. Check how TreeSitterExtractorEngine exposes the script module root and addresses, then verify that file-scope string and substring rules match and that show-features.py lists top-level string constants without changing -v, -vv, or JSON output.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
reverse-engineering
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
76/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.