Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
7bd2acd
Fix issues
saniyafatima07 Jun 10, 2026
f8d3848
fix: address PR review feedback (regex optimization, typos, duplicate…
EdoardoAllegrini Mar 18, 2026
bcfe22e
Update CHANGELOG.md
EdoardoAllegrini Mar 16, 2026
d86a44e
Fix outdated code
EdoardoAllegrini Mar 16, 2026
3ebf4bd
Fix outdated code
EdoardoAllegrini Mar 16, 2026
9b36aac
Modernize Tree-sitter: Replace local C-compilation with native PyPI w…
EdoardoAllegrini Mar 15, 2026
ddb701c
feat: revive script analysis ts feature
EdoardoAllegrini Mar 15, 2026
772e55d
Fix: CI builds
saniyafatima07 Jun 18, 2026
fcca9ad
Fix import errors
saniyafatima07 Jun 19, 2026
88a98f4
Fix CI: trial-1
saniyafatima07 Jun 19, 2026
18342bb
Fix tree-sitter packaging
saniyafatima07 Jun 20, 2026
14610dc
Address valid gemini reviews
saniyafatima07 Jun 22, 2026
8057248
Minor fixes
saniyafatima07 Jun 22, 2026
291975a
Fix tests
saniyafatima07 Jun 22, 2026
652b6cf
Address comments
saniyafatima07 Jun 25, 2026
af4fd99
Sort json files
saniyafatima07 Jun 26, 2026
2b25c67
Remove few unnecessary changes
saniyafatima07 Jun 28, 2026
87bb12c
Computer hashes for scripts
saniyafatima07 Jul 22, 2026
b76d79b
Cleanup: Revert the unrelated changes
saniyafatima07 Jul 22, 2026
019b260
Cleanup2: Revert the unrelated changes
saniyafatima07 Jul 22, 2026
c96f9e9
Update test data submodule
saniyafatima07 Jul 22, 2026
1288c40
Update test data submodule
saniyafatima07 Jul 22, 2026
d12e8d5
Cleanup3: Revert unrelated changes
saniyafatima07 Jul 22, 2026
459cd19
Cleanup4: Resolve unrelated changes
saniyafatima07 Jul 22, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/mypy/mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,6 @@ ignore_missing_imports = True

[mypy-ghidra.*]
ignore_missing_imports = True

[mypy-tree_sitter.*]
ignore_missing_imports = True
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from PyInstaller.utils.hooks import collect_data_files


# Tree-sitter signature lookups use importlib.resources, so PyInstaller must
# bundle the JSON files alongside the package.
datas = collect_data_files("capa.features.extractors.ts.signatures")
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ This release includes Ghidra PyGhidra support, performance improvements, depende

### New Features

- Tree-Sitter Script Analysis

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

TODO: expand this description to include contributions from previous developers.

- ghidra: support PyGhidra @mike-hunhoff #2788
- vmray: extract number features from whitelisted void_ptr parameters (hKey, hKeyRoot) @adeboyedn #2835

Expand Down
20 changes: 20 additions & 0 deletions capa/features/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,26 @@ def __hash__(self):
return int.__hash__(self)


class FileOffsetRangeAddress(Address):
"""an address range relative to the start of a file"""

def __init__(self, start_byte, end_byte):
self.start_byte = start_byte
self.end_byte = end_byte

def __eq__(self, other):
return (self.start_byte, self.end_byte) == (other.start_byte, other.end_byte)

def __lt__(self, other):
return (self.start_byte, self.end_byte) < (other.start_byte, other.end_byte)

def __hash__(self):
return hash((self.start_byte, self.end_byte))

def __repr__(self):
return f"file(0x{self.start_byte:x}, 0x{self.end_byte:x})"


class DNTokenAddress(int, Address):
"""a .NET token"""

Expand Down
10 changes: 9 additions & 1 deletion capa/features/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,10 +487,17 @@ def evaluate(self, features: "capa.engine.FeatureSet", short_circuit=True):
return Result(False, self, [])


class ScriptLanguage(Feature):
def __init__(self, value: str, description=None):
super().__init__(value, description=description)
self.name = "script language"


FORMAT_PE = "pe"
FORMAT_ELF = "elf"
FORMAT_DOTNET = "dotnet"
VALID_FORMAT = (FORMAT_PE, FORMAT_ELF, FORMAT_DOTNET)
FORMAT_SCRIPT = "script"
VALID_FORMAT = (FORMAT_PE, FORMAT_ELF, FORMAT_DOTNET, FORMAT_SCRIPT)
# internal only, not to be used in rules
FORMAT_AUTO = "auto"
FORMAT_SC32 = "sc32"
Expand All @@ -508,6 +515,7 @@ def evaluate(self, features: "capa.engine.FeatureSet", short_circuit=True):
FORMAT_PE,
FORMAT_ELF,
FORMAT_DOTNET,
FORMAT_SCRIPT,
FORMAT_FREEZE,
FORMAT_RESULT,
FORMAT_BINEXPORT2,
Expand Down
11 changes: 7 additions & 4 deletions capa/features/extractors/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import pefile

import capa.features
import capa.features.extractors.elf
import capa.features.extractors.pefile
import capa.features.extractors.strings
Expand All @@ -29,20 +30,20 @@
OS_ANY,
OS_AUTO,
ARCH_ANY,
VALID_OS,
FORMAT_PE,
FORMAT_ELF,
OS_WINDOWS,
VALID_ARCH,
FORMAT_FREEZE,
FORMAT_RESULT,
FORMAT_SCRIPT,
Arch,
Format,
String,
Feature,
)
from capa.features.freeze import is_freeze
from capa.features.address import NO_ADDRESS, Address, FileOffsetAddress
from capa.features.extractors.ts.autodetect import is_script

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -78,6 +79,8 @@ def extract_format(buf: bytes) -> Iterator[tuple[Feature, Address]]:
# we don't know what it is exactly, but may support it (e.g. a dynamic CAPE sandbox report)
# skip verdict here and let subsequent code analyze this further
return
elif is_script(buf):
yield Format(FORMAT_SCRIPT), NO_ADDRESS
else:
# we likely end up here:
# 1. handling a file format (e.g. macho)
Expand All @@ -98,7 +101,7 @@ def extract_arch(buf) -> Iterator[tuple[Feature, Address]]:
with contextlib.closing(io.BytesIO(buf)) as f:
arch = capa.features.extractors.elf.detect_elf_arch(f)

if arch not in VALID_ARCH:
if arch not in capa.features.common.VALID_ARCH:
logger.debug("unsupported arch: %s", arch)
return

Expand Down Expand Up @@ -135,7 +138,7 @@ def extract_os(buf, os=OS_AUTO) -> Iterator[tuple[Feature, Address]]:
with contextlib.closing(io.BytesIO(buf)) as f:
os = capa.features.extractors.elf.detect_elf_os(f)

if os not in VALID_OS:
if os not in capa.features.common.VALID_OS:
logger.debug("unsupported os: %s", os)
return

Expand Down
55 changes: 55 additions & 0 deletions capa/features/extractors/script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Tuple, Iterator

from capa.features.common import OS, OS_ANY, ARCH_ANY, FORMAT_SCRIPT, Arch, Format, Feature, ScriptLanguage
from capa.features.address import NO_ADDRESS, Address, FileOffsetRangeAddress

# Can be used to instantiate tree_sitter Language objects (see ts/query.py)
LANG_CS = "c_sharp"
LANG_HTML = "html"
LANG_JS = "javascript"
LANG_PY = "python"
LANG_TEM = "embedded_template"

EXT_ASPX = ("aspx", "aspx_")
EXT_CS = ("cs", "cs_")
EXT_HTML = ("html", "html_")
EXT_PY = ("py", "py_")


LANGUAGE_FEATURE_FORMAT = {
LANG_CS: "C#",
LANG_HTML: "HTML",
LANG_JS: "JavaScript",
LANG_PY: "Python",
LANG_TEM: "Embedded Template",
}


def extract_arch() -> Iterator[Tuple[Feature, Address]]:
yield Arch(ARCH_ANY), NO_ADDRESS


def extract_language(language: str, addr: FileOffsetRangeAddress) -> Iterator[Tuple[Feature, Address]]:
yield ScriptLanguage(LANGUAGE_FEATURE_FORMAT[language]), addr


def extract_os() -> Iterator[Tuple[Feature, Address]]:
yield OS(OS_ANY), NO_ADDRESS


def extract_format() -> Iterator[Tuple[Feature, Address]]:
yield Format(FORMAT_SCRIPT), NO_ADDRESS
Empty file.
80 changes: 80 additions & 0 deletions capa/features/extractors/ts/autodetect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Optional
from pathlib import Path

from tree_sitter import Node, Tree, Query, Parser, Language, QueryCursor
Comment thread
mr-tz marked this conversation as resolved.

from capa.features.extractors.script import EXT_CS, EXT_PY, LANG_CS, LANG_PY, EXT_ASPX, EXT_HTML, LANG_TEM, LANG_HTML
from capa.features.extractors.ts.query import TS_LANGUAGES


def is_script(buf: bytes) -> bool:
try:
return bool(get_language_ts(buf))
except ValueError:
return False


def _parse(ts_language: Language, buf: bytes) -> Optional[Tree]:
try:
parser = Parser(ts_language)
return parser.parse(buf)
except ValueError:
return None
Comment thread
mr-tz marked this conversation as resolved.


def _contains_errors(ts_language, node: Node) -> bool:
query = Query(ts_language, "(ERROR) @error")
return bool(QueryCursor(query).captures(node))
Comment thread
mr-tz marked this conversation as resolved.


def get_language_ts(buf: bytes) -> str:
for language, ts_language in TS_LANGUAGES.items():
tree = _parse(ts_language, buf)
if tree and not _contains_errors(ts_language, tree.root_node):
return language
raise ValueError("failed to parse the language")


def get_template_language_ts(buf: bytes) -> str:
for language, ts_language in TS_LANGUAGES.items():
if language in [LANG_TEM, LANG_HTML]:
continue
tree = _parse(ts_language, buf)
if tree and not _contains_errors(ts_language, tree.root_node):
return language
raise ValueError("failed to parse the language")


def get_language_from_ext(path: str) -> str:
if path.endswith(EXT_ASPX):
return LANG_TEM

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Embedded template is not immediately clear to me, some doc on that would be good (maybe it is further down).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I haven’t added documentation yet, but I’ll add a section describing the script analysis feature in the near future.

if path.endswith(EXT_CS):
return LANG_CS
if path.endswith(EXT_HTML):
return LANG_HTML
if path.endswith(EXT_PY):
return LANG_PY
raise ValueError(f"{path} has an unrecognized or an unsupported extension.")


def get_language(path: Path) -> str:
try:
with path.open("rb") as f:
buf = f.read()
return get_language_ts(buf)
except ValueError:
return get_language_from_ext(str(path))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I guess the order is debatable here, so flagging for further discussion

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

My thinking here was to prefer Tree-sitter’s language detection when possible, since it can inspect the file contents rather than relying only on the extension. The extension fallback is mainly for cases where content-based detection fails.

That said, I agree that the order is debatable. Happy to discuss more on this!

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What's the performance difference if we switch the order? My concern is that Tree-sitter's language detection could be slow for large or heavily obfuscated scripts, while simply checking the extension won't be bogged down by script size or complexity.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I ran a small benchmark test with simple Python scripts of different file sizes. There is actually a huge difference in the time taken by content-based detection compared to extension-based detection.

  • Extension-based: 0.0005 ms
  • Content-based: 7.3845 ms

So, it would be optimal for us to have extension-based detection first. Thank you for pointing it out @mr-tz and @mike-hunhoff.

I will correct it in the next commit.

Loading
Loading