code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def __init_yaml():
"""Lazy init yaml because canmatrix might not be fully loaded when loading this format."""
global _yaml_initialized
if not _yaml_initialized:
_yaml_initialized = True
yaml.add_constructor(u'tag:yaml.org,2002:Frame', _frame_constructor)
yaml.add_constructor(u'tag:ya... | Lazy init yaml because canmatrix might not be fully loaded when loading this format. | __init_yaml | python | ebroecker/canmatrix | src/canmatrix/formats/yaml.py | https://github.com/ebroecker/canmatrix/blob/master/src/canmatrix/formats/yaml.py | BSD-2-Clause |
def test_sym():
"""Test signal and frame encoding based on a .sym file
The symbol file was created using the PCAN Symbol Editor. The reference
transmissions were created using PCAN Explorer. The result message bytes
were observed in PCAN-View.
PCAN Symbol Editor v3.1.6.342
PCAN Explorer v5.3... | Test signal and frame encoding based on a .sym file
The symbol file was created using the PCAN Symbol Editor. The reference
transmissions were created using PCAN Explorer. The result message bytes
were observed in PCAN-View.
PCAN Symbol Editor v3.1.6.342
PCAN Explorer v5.3.4.823
PCAN-View v4... | test_sym | python | ebroecker/canmatrix | tests/test_frame_encoding.py | https://github.com/ebroecker/canmatrix/blob/master/tests/test_frame_encoding.py | BSD-2-Clause |
def test_export_with_jsonall(default_matrix):
"""Check the jsonExportAll doesn't raise and export some additional field."""
matrix = default_matrix
out_file = io.BytesIO()
canmatrix.formats.dump(matrix, out_file, "json", jsonExportAll=True)
data = out_file.getvalue().decode("utf-8")
assert "my_v... | Check the jsonExportAll doesn't raise and export some additional field. | test_export_with_jsonall | python | ebroecker/canmatrix | tests/test_json.py | https://github.com/ebroecker/canmatrix/blob/master/tests/test_json.py | BSD-2-Clause |
def index_rule_matches(features: FeatureSet, rule: "capa.rules.Rule", locations: Iterable[Address]):
"""
record into the given featureset that the given rule matched at the given locations.
naively, this is just adding a MatchedRule feature;
however, we also want to record matches for the rule's namesp... |
record into the given featureset that the given rule matched at the given locations.
naively, this is just adding a MatchedRule feature;
however, we also want to record matches for the rule's namespaces.
updates `features` in-place. doesn't modify the remaining arguments.
| index_rule_matches | python | mandiant/capa | capa/engine.py | https://github.com/mandiant/capa/blob/master/capa/engine.py | Apache-2.0 |
def match(rules: list["capa.rules.Rule"], features: FeatureSet, addr: Address) -> tuple[FeatureSet, MatchResults]:
"""
match the given rules against the given features,
returning an updated set of features and the matches.
the updated features are just like the input,
but extended to include the ma... |
match the given rules against the given features,
returning an updated set of features and the matches.
the updated features are just like the input,
but extended to include the match features (e.g. names of rules that matched).
the given feature set is not modified; an updated copy is returned.
... | match | python | mandiant/capa | capa/engine.py | https://github.com/mandiant/capa/blob/master/capa/engine.py | Apache-2.0 |
def hex(n: int) -> str:
"""render the given number using upper case hex, like: 0x123ABC"""
if n < 0:
return f"-0x{(-n):X}"
else:
return f"0x{(n):X}" | render the given number using upper case hex, like: 0x123ABC | hex | python | mandiant/capa | capa/helpers.py | https://github.com/mandiant/capa/blob/master/capa/helpers.py | Apache-2.0 |
def stdout_redirector(stream):
"""
Redirect stdout at the C runtime level,
which lets us handle native libraries that spam stdout.
*But*, this only works on Linux! Otherwise will silently still write to stdout.
So, try to upstream the fix when possible.
Via: https://eli.thegreenplace.net/2015... |
Redirect stdout at the C runtime level,
which lets us handle native libraries that spam stdout.
*But*, this only works on Linux! Otherwise will silently still write to stdout.
So, try to upstream the fix when possible.
Via: https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-py... | stdout_redirector | python | mandiant/capa | capa/helpers.py | https://github.com/mandiant/capa/blob/master/capa/helpers.py | Apache-2.0 |
def _redirect_stdout(to_fd):
"""Redirect stdout to the given file descriptor."""
# Flush the C-level buffer stdout
LIBC.fflush(C_STDOUT)
# Flush and close sys.stdout - also closes the file descriptor (fd)
sys.stdout.close()
# Make original_stdout_fd point to the same file... | Redirect stdout to the given file descriptor. | _redirect_stdout | python | mandiant/capa | capa/helpers.py | https://github.com/mandiant/capa/blob/master/capa/helpers.py | Apache-2.0 |
def is_running_standalone() -> bool:
"""
are we running from a PyInstaller'd executable?
if so, then we'll be able to access `sys._MEIPASS` for the packaged resources.
"""
# typically we only expect capa.main to be packaged via PyInstaller.
# therefore, this *should* be in capa.main; however,
... |
are we running from a PyInstaller'd executable?
if so, then we'll be able to access `sys._MEIPASS` for the packaged resources.
| is_running_standalone | python | mandiant/capa | capa/helpers.py | https://github.com/mandiant/capa/blob/master/capa/helpers.py | Apache-2.0 |
def is_cache_newer_than_rule_code(cache_dir: Path) -> bool:
"""
basic check to prevent issues if the rules cache is older than relevant rules code
args:
cache_dir: the cache directory containing cache files
returns:
True if latest cache file is newer than relevant rule cache code
"""
... |
basic check to prevent issues if the rules cache is older than relevant rules code
args:
cache_dir: the cache directory containing cache files
returns:
True if latest cache file is newer than relevant rule cache code
| is_cache_newer_than_rule_code | python | mandiant/capa | capa/helpers.py | https://github.com/mandiant/capa/blob/master/capa/helpers.py | Apache-2.0 |
def is_supported_format(sample: Path) -> bool:
"""
Return if this is a supported file based on magic header values
"""
taste = sample.open("rb").read(0x100)
return len(list(capa.features.extractors.common.extract_format(taste))) == 1 |
Return if this is a supported file based on magic header values
| is_supported_format | python | mandiant/capa | capa/loader.py | https://github.com/mandiant/capa/blob/master/capa/loader.py | Apache-2.0 |
def get_workspace(path: Path, input_format: str, sigpaths: list[Path]):
"""
load the program at the given path into a vivisect workspace using the given format.
also apply the given FLIRT signatures.
supported formats:
- pe
- elf
- shellcode 32-bit
- shellcode 64-bit
- aut... |
load the program at the given path into a vivisect workspace using the given format.
also apply the given FLIRT signatures.
supported formats:
- pe
- elf
- shellcode 32-bit
- shellcode 64-bit
- auto
this creates and analyzes the workspace; however, it does *not* save the... | get_workspace | python | mandiant/capa | capa/loader.py | https://github.com/mandiant/capa/blob/master/capa/loader.py | Apache-2.0 |
def compute_dynamic_layout(
rules: RuleSet, extractor: DynamicFeatureExtractor, capabilities: MatchResults
) -> rdoc.DynamicLayout:
"""
compute a metadata structure that links threads
to the processes in which they're found.
only collect the threads at which some rule matched.
otherwise, we may... |
compute a metadata structure that links threads
to the processes in which they're found.
only collect the threads at which some rule matched.
otherwise, we may pollute the json document with
a large amount of un-referenced data.
| compute_dynamic_layout | python | mandiant/capa | capa/loader.py | https://github.com/mandiant/capa/blob/master/capa/loader.py | Apache-2.0 |
def compute_static_layout(rules: RuleSet, extractor: StaticFeatureExtractor, capabilities) -> rdoc.StaticLayout:
"""
compute a metadata structure that links basic blocks
to the functions in which they're found.
only collect the basic blocks at which some rule matched.
otherwise, we may pollute the ... |
compute a metadata structure that links basic blocks
to the functions in which they're found.
only collect the basic blocks at which some rule matched.
otherwise, we may pollute the json document with
a large amount of un-referenced data.
| compute_static_layout | python | mandiant/capa | capa/loader.py | https://github.com/mandiant/capa/blob/master/capa/loader.py | Apache-2.0 |
def get_default_root() -> Path:
"""
get the file system path to the default resources directory.
under PyInstaller, this comes from _MEIPASS.
under source, this is the root directory of the project.
"""
# we only expect capa.main to be packaged within PyInstaller,
# so we don't put this in a... |
get the file system path to the default resources directory.
under PyInstaller, this comes from _MEIPASS.
under source, this is the root directory of the project.
| get_default_root | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def get_default_signatures() -> list[Path]:
"""
compute a list of file system paths to the default FLIRT signatures.
"""
sigs_path = get_default_root() / "sigs"
logger.debug("signatures path: %s", sigs_path)
ret = []
for file in sigs_path.rglob("*"):
if file.is_file() and file.suffi... |
compute a list of file system paths to the default FLIRT signatures.
| get_default_signatures | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def simple_message_exception_handler(
exctype: type[BaseException], value: BaseException, traceback: TracebackType | None
):
"""
prints friendly message on unexpected exceptions to regular users (debug mode shows regular stack trace)
"""
if exctype is KeyboardInterrupt:
print("KeyboardInter... |
prints friendly message on unexpected exceptions to regular users (debug mode shows regular stack trace)
| simple_message_exception_handler | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def install_common_args(parser, wanted=None):
"""
register a common set of command line arguments for re-use by main & scripts.
these are things like logging/coloring/etc.
also enable callers to opt-in to common arguments, like specifying the input file.
this routine lets many script use the same l... |
register a common set of command line arguments for re-use by main & scripts.
these are things like logging/coloring/etc.
also enable callers to opt-in to common arguments, like specifying the input file.
this routine lets many script use the same language for cli arguments.
see `handle_common_arg... | install_common_args | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def handle_common_args(args):
"""
handle the global config specified by `install_common_args`,
such as configuring logging/coloring/etc.
the following fields will be overwritten when present:
- rules: file system path to rule files.
- signatures: file system path to signature files.
the... |
handle the global config specified by `install_common_args`,
such as configuring logging/coloring/etc.
the following fields will be overwritten when present:
- rules: file system path to rule files.
- signatures: file system path to signature files.
the following fields may be added:
... | handle_common_args | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def ensure_input_exists_from_cli(args):
"""
args:
args: The parsed command line arguments from `install_common_args`.
raises:
ShouldExitError: if the program is invoked incorrectly and should exit.
"""
try:
_ = get_file_taste(args.input_file)
except IOError as e:
# p... |
args:
args: The parsed command line arguments from `install_common_args`.
raises:
ShouldExitError: if the program is invoked incorrectly and should exit.
| ensure_input_exists_from_cli | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def get_input_format_from_cli(args) -> str:
"""
Determine the format of the input file.
Note: this may not be the same as the format of the sample.
Cape, Freeze, etc. formats describe a sample without being the sample itself.
args:
args: The parsed command line arguments from `install_common... |
Determine the format of the input file.
Note: this may not be the same as the format of the sample.
Cape, Freeze, etc. formats describe a sample without being the sample itself.
args:
args: The parsed command line arguments from `install_common_args`.
raises:
ShouldExitError: if the ... | get_input_format_from_cli | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def get_backend_from_cli(args, input_format: str) -> str:
"""
Determine the backend that should be used for the given input file.
Respects an override provided by the user, otherwise, use a good default.
args:
args: The parsed command line arguments from `install_common_args`.
input_format:... |
Determine the backend that should be used for the given input file.
Respects an override provided by the user, otherwise, use a good default.
args:
args: The parsed command line arguments from `install_common_args`.
input_format: The file format of the input file.
raises:
ShouldExit... | get_backend_from_cli | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def get_sample_path_from_cli(args, backend: str) -> Optional[Path]:
"""
Determine the path to the underlying sample, if it exists.
Note: this may not be the same as the input file.
Cape, Freeze, etc. formats describe a sample without being the sample itself.
args:
args: The parsed command li... |
Determine the path to the underlying sample, if it exists.
Note: this may not be the same as the input file.
Cape, Freeze, etc. formats describe a sample without being the sample itself.
args:
args: The parsed command line arguments from `install_common_args`.
backend: The backend that wi... | get_sample_path_from_cli | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def get_os_from_cli(args, backend) -> str:
"""
Determine the OS for the given sample.
Respects an override provided by the user, otherwise, use heuristics and
algorithms to detect the OS.
args:
args: The parsed command line arguments from `install_common_args`.
backend: The backend that... |
Determine the OS for the given sample.
Respects an override provided by the user, otherwise, use heuristics and
algorithms to detect the OS.
args:
args: The parsed command line arguments from `install_common_args`.
backend: The backend that will handle the input file.
raises:
Sh... | get_os_from_cli | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def get_file_extractors_from_cli(args, input_format: str) -> list[FeatureExtractor]:
"""
args:
args: The parsed command line arguments from `install_common_args`.
input_format: The file format of the input file.
raises:
ShouldExitError: if the program is invoked incorrectly and should exi... |
args:
args: The parsed command line arguments from `install_common_args`.
input_format: The file format of the input file.
raises:
ShouldExitError: if the program is invoked incorrectly and should exit.
| get_file_extractors_from_cli | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def find_static_limitations_from_cli(args, rules: RuleSet, file_extractors: list[FeatureExtractor]) -> bool:
"""
args:
args: The parsed command line arguments from `install_common_args`.
Only file-scoped feature extractors like pefile are used.
Dynamic feature extractors can handle packed samples... |
args:
args: The parsed command line arguments from `install_common_args`.
Only file-scoped feature extractors like pefile are used.
Dynamic feature extractors can handle packed samples and do not need to be considered here.
raises:
ShouldExitError: if the program is invoked incorrectly an... | find_static_limitations_from_cli | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def find_dynamic_limitations_from_cli(args, rules: RuleSet, file_extractors: list[FeatureExtractor]) -> bool:
"""
Does the dynamic analysis describe some trace that we may not support well?
For example, .NET samples detonated in a sandbox, which may rely on different API patterns than we currently describe ... |
Does the dynamic analysis describe some trace that we may not support well?
For example, .NET samples detonated in a sandbox, which may rely on different API patterns than we currently describe in our rules.
args:
args: The parsed command line arguments from `install_common_args`.
raises:
... | find_dynamic_limitations_from_cli | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def get_extractor_from_cli(args, input_format: str, backend: str) -> FeatureExtractor:
"""
args:
args: The parsed command line arguments from `install_common_args`.
input_format: The file format of the input file.
backend: The backend that will handle the input file.
raises:
ShouldE... |
args:
args: The parsed command line arguments from `install_common_args`.
input_format: The file format of the input file.
backend: The backend that will handle the input file.
raises:
ShouldExitError: if the program is invoked incorrectly and should exit.
| get_extractor_from_cli | python | mandiant/capa | capa/main.py | https://github.com/mandiant/capa/blob/master/capa/main.py | Apache-2.0 |
def find_call_capabilities(
ruleset: RuleSet, extractor: DynamicFeatureExtractor, ph: ProcessHandle, th: ThreadHandle, ch: CallHandle
) -> CallCapabilities:
"""
find matches for the given rules for the given call.
"""
# all features found for the call.
features: FeatureSet = collections.defaultd... |
find matches for the given rules for the given call.
| find_call_capabilities | python | mandiant/capa | capa/capabilities/dynamic.py | https://github.com/mandiant/capa/blob/master/capa/capabilities/dynamic.py | Apache-2.0 |
def find_thread_capabilities(
ruleset: RuleSet, extractor: DynamicFeatureExtractor, ph: ProcessHandle, th: ThreadHandle
) -> ThreadCapabilities:
"""
find matches for the given rules within the given thread,
which includes matches for all the spans and calls within it.
"""
# all features found wi... |
find matches for the given rules within the given thread,
which includes matches for all the spans and calls within it.
| find_thread_capabilities | python | mandiant/capa | capa/capabilities/dynamic.py | https://github.com/mandiant/capa/blob/master/capa/capabilities/dynamic.py | Apache-2.0 |
def find_process_capabilities(
ruleset: RuleSet, extractor: DynamicFeatureExtractor, ph: ProcessHandle
) -> ProcessCapabilities:
"""
find matches for the given rules within the given process.
"""
# all features found within this process,
# includes features found within threads (and calls).
... |
find matches for the given rules within the given process.
| find_process_capabilities | python | mandiant/capa | capa/capabilities/dynamic.py | https://github.com/mandiant/capa/blob/master/capa/capabilities/dynamic.py | Apache-2.0 |
def find_instruction_capabilities(
ruleset: RuleSet, extractor: StaticFeatureExtractor, f: FunctionHandle, bb: BBHandle, insn: InsnHandle
) -> InstructionCapabilities:
"""
find matches for the given rules for the given instruction.
"""
# all features found for the instruction.
features: FeatureS... |
find matches for the given rules for the given instruction.
| find_instruction_capabilities | python | mandiant/capa | capa/capabilities/static.py | https://github.com/mandiant/capa/blob/master/capa/capabilities/static.py | Apache-2.0 |
def find_basic_block_capabilities(
ruleset: RuleSet, extractor: StaticFeatureExtractor, f: FunctionHandle, bb: BBHandle
) -> BasicBlockCapabilities:
"""
find matches for the given rules within the given basic block.
"""
# all features found within this basic block,
# includes features found with... |
find matches for the given rules within the given basic block.
| find_basic_block_capabilities | python | mandiant/capa | capa/capabilities/static.py | https://github.com/mandiant/capa/blob/master/capa/capabilities/static.py | Apache-2.0 |
def find_code_capabilities(ruleset: RuleSet, extractor: StaticFeatureExtractor, fh: FunctionHandle) -> CodeCapabilities:
"""
find matches for the given rules within the given function.
"""
# all features found within this function,
# includes features found within basic blocks (and instructions).
... |
find matches for the given rules within the given function.
| find_code_capabilities | python | mandiant/capa | capa/capabilities/static.py | https://github.com/mandiant/capa/blob/master/capa/capabilities/static.py | Apache-2.0 |
def __init__(
self,
value: Union[str, int, float, bytes],
description: Optional[str] = None,
):
"""
Args:
value (any): the value of the feature, such as the number or string.
description (str): a human-readable description that explains the feature value.
... |
Args:
value (any): the value of the feature, such as the number or string.
description (str): a human-readable description that explains the feature value.
| __init__ | python | mandiant/capa | capa/features/common.py | https://github.com/mandiant/capa/blob/master/capa/features/common.py | Apache-2.0 |
def __init__(self, substring: Substring, matches: dict[str, set[Address]]):
"""
args:
substring: the substring feature that matches.
match: mapping from matching string to its locations.
"""
super().__init__(str(substring.value), description=substring.description)
... |
args:
substring: the substring feature that matches.
match: mapping from matching string to its locations.
| __init__ | python | mandiant/capa | capa/features/common.py | https://github.com/mandiant/capa/blob/master/capa/features/common.py | Apache-2.0 |
def __init__(self, regex: Regex, matches: dict[str, set[Address]]):
"""
args:
regex: the regex feature that matches.
matches: mapping from matching string to its locations.
"""
super().__init__(str(regex.value), description=regex.description)
# we want this to... |
args:
regex: the regex feature that matches.
matches: mapping from matching string to its locations.
| __init__ | python | mandiant/capa | capa/features/common.py | https://github.com/mandiant/capa/blob/master/capa/features/common.py | Apache-2.0 |
def __init__(self, index: int, value: Union[int, float], description=None):
"""
args:
value (int or float): positive or negative integer, or floating point number.
the range of the value is:
- if positive, the range of u64
- if negative, the range of i64
... |
args:
value (int or float): positive or negative integer, or floating point number.
the range of the value is:
- if positive, the range of u64
- if negative, the range of i64
- if floating, the range and precision of double
| __init__ | python | mandiant/capa | capa/features/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/insn.py | Apache-2.0 |
def __init__(self, index: int, value: int, description=None):
"""
args:
value (int): the offset, which can be positive or negative.
the range of the value is:
- if positive, the range of u64
- if negative, the range of i64
"""
super().__init__(index... |
args:
value (int): the offset, which can be positive or negative.
the range of the value is:
- if positive, the range of u64
- if negative, the range of i64
| __init__ | python | mandiant/capa | capa/features/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/insn.py | Apache-2.0 |
def extract_insn_features(
self, f: FunctionHandle, bb: BBHandle, insn: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""
extract instruction-scope features.
the arguments are opaque values previously provided by `.get_functions()`, etc.
example::
extractor... |
extract instruction-scope features.
the arguments are opaque values previously provided by `.get_functions()`, etc.
example::
extractor = VivisectFeatureExtractor(vw, path)
for function in extractor.get_functions():
for bb in extractor.get_basic_blocks(... | extract_insn_features | python | mandiant/capa | capa/features/extractors/base_extractor.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/base_extractor.py | Apache-2.0 |
def extract_call_features(
self, ph: ProcessHandle, th: ThreadHandle, ch: CallHandle
) -> Iterator[tuple[Feature, Address]]:
"""
Yields all features of a call. These include:
- api name
- bytes/strings/numbers extracted from arguments
"""
raise NotImplementedE... |
Yields all features of a call. These include:
- api name
- bytes/strings/numbers extracted from arguments
| extract_call_features | python | mandiant/capa | capa/features/extractors/base_extractor.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/base_extractor.py | Apache-2.0 |
def extract_file_strings(buf: bytes, **kwargs) -> Iterator[tuple[String, Address]]:
"""
extract ASCII and UTF-16 LE strings from file
"""
for s in capa.features.extractors.strings.extract_ascii_strings(buf):
yield String(s.s), FileOffsetAddress(s.offset)
for s in capa.features.extractors.st... |
extract ASCII and UTF-16 LE strings from file
| extract_file_strings | python | mandiant/capa | capa/features/extractors/common.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/common.py | Apache-2.0 |
def dynamic_entries(self) -> Iterator[tuple[int, int]]:
"""
read the entries from the dynamic section,
yielding the tag and value for each entry.
"""
DT_NULL = 0x0
PT_DYNAMIC = 0x2
for phdr in self.program_headers:
if phdr.type != PT_DYNAMIC:
... |
read the entries from the dynamic section,
yielding the tag and value for each entry.
| dynamic_entries | python | mandiant/capa | capa/features/extractors/elf.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/elf.py | Apache-2.0 |
def strtab(self) -> Optional[bytes]:
"""
fetch the bytes of the string table
referenced by the dynamic section.
"""
DT_STRTAB = 0x5
DT_STRSZ = 0xA
strtab_addr = None
strtab_size = None
for d_tag, d_val in self.dynamic_entries:
if d_ta... |
fetch the bytes of the string table
referenced by the dynamic section.
| strtab | python | mandiant/capa | capa/features/extractors/elf.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/elf.py | Apache-2.0 |
def needed(self) -> Iterator[str]:
"""
read the names of DT_NEEDED entries from the dynamic section,
which correspond to dependencies on other shared objects,
like: `libpthread.so.0`
"""
DT_NEEDED = 0x1
strtab = self.strtab
if not strtab:
retur... |
read the names of DT_NEEDED entries from the dynamic section,
which correspond to dependencies on other shared objects,
like: `libpthread.so.0`
| needed | python | mandiant/capa | capa/features/extractors/elf.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/elf.py | Apache-2.0 |
def symtab(self) -> Optional[tuple[Shdr, Shdr]]:
"""
fetch the Shdr for the symtab and the associated strtab.
"""
SHT_SYMTAB = 0x2
for shdr in self.section_headers:
if shdr.type != SHT_SYMTAB:
continue
# the linked section contains strings... |
fetch the Shdr for the symtab and the associated strtab.
| symtab | python | mandiant/capa | capa/features/extractors/elf.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/elf.py | Apache-2.0 |
def _parse(self, endian: str, bitness: int, symtab_buf: bytes) -> None:
"""
return the symbol's information in
the order specified by sys/elf32.h
"""
if self.symtab.entsize == 0:
return
for i in range(int(len(self.symtab.buf) / self.symtab.entsize)):
... |
return the symbol's information in
the order specified by sys/elf32.h
| _parse | python | mandiant/capa | capa/features/extractors/elf.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/elf.py | Apache-2.0 |
def get_name(self, symbol: Symbol) -> str:
"""
fetch a symbol's name from symtab's
associated strings' section (SHT_STRTAB)
"""
if not self.strtab:
raise ValueError("no strings found")
for i in range(symbol.name_offset, self.strtab.size):
if self.... |
fetch a symbol's name from symtab's
associated strings' section (SHT_STRTAB)
| get_name | python | mandiant/capa | capa/features/extractors/elf.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/elf.py | Apache-2.0 |
def guess_os_from_go_buildinfo(elf: ELF) -> Optional[OS]:
"""
In a binary compiled by Go, the buildinfo structure may contain
metadata about the build environment, including the configured
GOOS, which specifies the target operating system.
Search for and parse the buildinfo structure,
which may... |
In a binary compiled by Go, the buildinfo structure may contain
metadata about the build environment, including the configured
GOOS, which specifies the target operating system.
Search for and parse the buildinfo structure,
which may be found in the .go.buildinfo section,
and often contains th... | guess_os_from_go_buildinfo | python | mandiant/capa | capa/features/extractors/elf.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/elf.py | Apache-2.0 |
def guess_os_from_go_source(elf: ELF) -> Optional[OS]:
"""
In a binary compiled by Go, runtime metadata may contain
references to the source filenames, including the
src/runtime/os_* files, whose name indicates the
target operating system.
Confirm the given ELF seems to be built by Go,
and ... |
In a binary compiled by Go, runtime metadata may contain
references to the source filenames, including the
src/runtime/os_* files, whose name indicates the
target operating system.
Confirm the given ELF seems to be built by Go,
and then look for strings that look like
Go source filenames.
... | guess_os_from_go_source | python | mandiant/capa | capa/features/extractors/elf.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/elf.py | Apache-2.0 |
def guess_os_from_vdso_strings(elf: ELF) -> Optional[OS]:
"""
The "vDSO" (virtual dynamic shared object) is a small shared
library that the kernel automatically maps into the address space
of all user-space applications.
Some statically linked executables include small dynamic linker
routines t... |
The "vDSO" (virtual dynamic shared object) is a small shared
library that the kernel automatically maps into the address space
of all user-space applications.
Some statically linked executables include small dynamic linker
routines that finds these vDSO symbols, using the ASCII
symbol name and... | guess_os_from_vdso_strings | python | mandiant/capa | capa/features/extractors/elf.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/elf.py | Apache-2.0 |
def is_aw_function(symbol: str) -> bool:
"""
is the given function name an A/W function?
these are variants of functions that, on Windows, accept either a narrow or wide string.
"""
if len(symbol) < 2:
return False
# last character should be 'A' or 'W'
if symbol[-1] not in ("A", "W"... |
is the given function name an A/W function?
these are variants of functions that, on Windows, accept either a narrow or wide string.
| is_aw_function | python | mandiant/capa | capa/features/extractors/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/helpers.py | Apache-2.0 |
def is_ordinal(symbol: str) -> bool:
"""
is the given symbol an ordinal that is prefixed by "#"?
"""
if symbol:
return symbol[0] == "#"
return False |
is the given symbol an ordinal that is prefixed by "#"?
| is_ordinal | python | mandiant/capa | capa/features/extractors/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/helpers.py | Apache-2.0 |
def generate_symbols(dll: str, symbol: str, include_dll=False) -> Iterator[str]:
"""
for a given dll and symbol name, generate variants.
we over-generate features to make matching easier.
these include:
- CreateFileA
- CreateFile
- ws2_32.#1
note that since capa v7 only `import` f... |
for a given dll and symbol name, generate variants.
we over-generate features to make matching easier.
these include:
- CreateFileA
- CreateFile
- ws2_32.#1
note that since capa v7 only `import` features and APIs called via ordinal include DLL names:
- kernel32.CreateFileA
... | generate_symbols | python | mandiant/capa | capa/features/extractors/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/helpers.py | Apache-2.0 |
def reformat_forwarded_export_name(forwarded_name: str) -> str:
"""
a forwarded export has a DLL name/path and symbol name.
we want the former to be lowercase, and the latter to be verbatim.
"""
# use rpartition so we can split on separator between dll and name.
# the dll name can be a full pat... |
a forwarded export has a DLL name/path and symbol name.
we want the former to be lowercase, and the latter to be verbatim.
| reformat_forwarded_export_name | python | mandiant/capa | capa/features/extractors/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/helpers.py | Apache-2.0 |
def twos_complement(val: int, bits: int) -> int:
"""
compute the 2's complement of int value val
from: https://stackoverflow.com/a/9147327/87207
"""
# if sign bit is set e.g., 8bit: 128-255
if (val & (1 << (bits - 1))) != 0:
# compute negative value
return val - (1 << bits)
... |
compute the 2's complement of int value val
from: https://stackoverflow.com/a/9147327/87207
| twos_complement | python | mandiant/capa | capa/features/extractors/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/helpers.py | Apache-2.0 |
def carve_pe(pbytes: bytes, offset: int = 0) -> Iterator[tuple[int, int]]:
"""
Generate (offset, key) tuples of embedded PEs
Based on the version from vivisect:
https://github.com/vivisect/vivisect/blob/7be4037b1cecc4551b397f840405a1fc606f9b53/PE/carve.py#L19
And its IDA adaptation:
capa/fe... |
Generate (offset, key) tuples of embedded PEs
Based on the version from vivisect:
https://github.com/vivisect/vivisect/blob/7be4037b1cecc4551b397f840405a1fc606f9b53/PE/carve.py#L19
And its IDA adaptation:
capa/features/extractors/ida/file.py
| carve_pe | python | mandiant/capa | capa/features/extractors/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/helpers.py | Apache-2.0 |
def has_loop(edges, threshold=2):
"""check if a list of edges representing a directed graph contains a loop
args:
edges: list of edge sets representing a directed graph i.e. [(1, 2), (2, 1)]
threshold: min number of nodes contained in loop
returns:
bool
"""
g = networkx.DiG... | check if a list of edges representing a directed graph contains a loop
args:
edges: list of edge sets representing a directed graph i.e. [(1, 2), (2, 1)]
threshold: min number of nodes contained in loop
returns:
bool
| has_loop | python | mandiant/capa | capa/features/extractors/loops.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/loops.py | Apache-2.0 |
def extract_file_import_names(pe, **kwargs):
"""
extract imported function names
1. imports by ordinal:
- modulename.#ordinal
2. imports by name, results in two features to support importname-only matching:
- modulename.importname
- importname
"""
if hasattr(pe, "DIRECTORY_ENTRY_I... |
extract imported function names
1. imports by ordinal:
- modulename.#ordinal
2. imports by name, results in two features to support importname-only matching:
- modulename.importname
- importname
| extract_file_import_names | python | mandiant/capa | capa/features/extractors/pefile.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/pefile.py | Apache-2.0 |
def extract_file_features(pe, buf):
"""
extract file features from given workspace
args:
pe (pefile.PE): the parsed PE
buf: the raw sample bytes
yields:
tuple[Feature, VA]: a feature and its location.
"""
for file_handler in FILE_HANDLERS:
# file_handler: type: (pe, ... |
extract file features from given workspace
args:
pe (pefile.PE): the parsed PE
buf: the raw sample bytes
yields:
tuple[Feature, VA]: a feature and its location.
| extract_file_features | python | mandiant/capa | capa/features/extractors/pefile.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/pefile.py | Apache-2.0 |
def extract_global_features(pe, buf):
"""
extract global features from given workspace
args:
pe (pefile.PE): the parsed PE
buf: the raw sample bytes
yields:
tuple[Feature, VA]: a feature and its location.
"""
for handler in GLOBAL_HANDLERS:
# file_handler: type: (pe, ... |
extract global features from given workspace
args:
pe (pefile.PE): the parsed PE
buf: the raw sample bytes
yields:
tuple[Feature, VA]: a feature and its location.
| extract_global_features | python | mandiant/capa | capa/features/extractors/pefile.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/pefile.py | Apache-2.0 |
def buf_filled_with(buf: bytes, character: int) -> bool:
"""Check if the given buffer is filled with the given character, repeatedly.
Args:
buf: The bytes buffer to check
character: The byte value (0-255) to check for
Returns:
True if all bytes in the buffer match the character, Fa... | Check if the given buffer is filled with the given character, repeatedly.
Args:
buf: The bytes buffer to check
character: The byte value (0-255) to check for
Returns:
True if all bytes in the buffer match the character, False otherwise.
The empty buffer contains no bytes, there... | buf_filled_with | python | mandiant/capa | capa/features/extractors/strings.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/strings.py | Apache-2.0 |
def extract_ascii_strings(buf: bytes, n: int = 4) -> Iterator[String]:
"""
Extract ASCII strings from the given binary data.
Params:
buf: the bytes from which to extract strings
n: minimum string length
"""
if not buf:
return
if n < 1:
raise ValueError("minimum str... |
Extract ASCII strings from the given binary data.
Params:
buf: the bytes from which to extract strings
n: minimum string length
| extract_ascii_strings | python | mandiant/capa | capa/features/extractors/strings.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/strings.py | Apache-2.0 |
def extract_unicode_strings(buf: bytes, n: int = 4) -> Iterator[String]:
"""
Extract naive UTF-16 strings from the given binary data.
Params:
buf: the bytes from which to extract strings
n: minimum string length
"""
if not buf:
return
if n < 1:
raise ValueError("mi... |
Extract naive UTF-16 strings from the given binary data.
Params:
buf: the bytes from which to extract strings
n: minimum string length
| extract_unicode_strings | python | mandiant/capa | capa/features/extractors/strings.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/strings.py | Apache-2.0 |
def is_address_mapped(be2: BinExport2, address: int) -> bool:
"""return True if the given address is mapped"""
sections_with_perms: Iterator[BinExport2.Section] = filter(lambda s: s.flag_r or s.flag_w or s.flag_x, be2.section)
return any(section.address <= address < section.address + section.size for sectio... | return True if the given address is mapped | is_address_mapped | python | mandiant/capa | capa/features/extractors/binexport2/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binexport2/helpers.py | Apache-2.0 |
def _fill_operand_expression_list(
be2: BinExport2,
operand: BinExport2.Operand,
expression_tree: list[list[int]],
tree_index: int,
expression_list: list[BinExport2.Expression],
):
"""
Walk the given expression tree and collect the expression nodes in-order.
"""
expression_index = op... |
Walk the given expression tree and collect the expression nodes in-order.
| _fill_operand_expression_list | python | mandiant/capa | capa/features/extractors/binexport2/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binexport2/helpers.py | Apache-2.0 |
def from_str(cls, query: str):
"""
Parse a pattern string into a Pattern instance.
The supported syntax is like this:
br reg
br reg ; capture reg
br reg(stack) ; capture reg
br reg(not... |
Parse a pattern string into a Pattern instance.
The supported syntax is like this:
br reg
br reg ; capture reg
br reg(stack) ; capture reg
br reg(not-stack) ; capture reg
... | from_str | python | mandiant/capa | capa/features/extractors/binexport2/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binexport2/helpers.py | Apache-2.0 |
def match(
self, mnemonic: str, operand_expressions: list[list[BinExport2.Expression]]
) -> Optional["BinExport2InstructionPattern.MatchResult"]:
"""
Match the given BinExport2 data against this pattern.
The BinExport2 expression tree must have been flattened, such as with
c... |
Match the given BinExport2 data against this pattern.
The BinExport2 expression tree must have been flattened, such as with
capa.features.extractors.binexport2.helpers.get_operand_expressions.
If there's a match, the captured Expression instance is returned.
Otherwise, you get... | match | python | mandiant/capa | capa/features/extractors/binexport2/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binexport2/helpers.py | Apache-2.0 |
def extract_function_calls_from(fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]:
"""extract functions calls from features
most relevant at the function scope;
however, its most efficient to extract at the instruction scope.
"""
fhi: FunctionContext = fh.inner... | extract functions calls from features
most relevant at the function scope;
however, its most efficient to extract at the instruction scope.
| extract_function_calls_from | python | mandiant/capa | capa/features/extractors/binexport2/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binexport2/insn.py | Apache-2.0 |
def get_sample_from_binexport2(input_file: Path, be2: BinExport2, search_paths: list[Path]) -> Path:
"""attempt to find the sample file, given a BinExport2 file.
searches in the same directory as the BinExport2 file, and then in search_paths.
"""
def filename_similarity_key(p: Path) -> tuple[int, str]... | attempt to find the sample file, given a BinExport2 file.
searches in the same directory as the BinExport2 file, and then in search_paths.
| get_sample_from_binexport2 | python | mandiant/capa | capa/features/extractors/binexport2/__init__.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binexport2/__init__.py | Apache-2.0 |
def instruction_indices(basic_block: BinExport2.BasicBlock) -> Iterator[int]:
"""
For a given basic block, enumerate the instruction indices.
"""
for index_range in basic_block.instruction_index:
if not index_range.HasField("end_index"):
yield index_range.begi... |
For a given basic block, enumerate the instruction indices.
| instruction_indices | python | mandiant/capa | capa/features/extractors/binexport2/__init__.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binexport2/__init__.py | Apache-2.0 |
def basic_block_instructions(
self, basic_block: BinExport2.BasicBlock
) -> Iterator[tuple[int, BinExport2.Instruction, int]]:
"""
For a given basic block, enumerate the instruction indices,
the instruction instances, and their addresses.
"""
for instruction_index in ... |
For a given basic block, enumerate the instruction indices,
the instruction instances, and their addresses.
| basic_block_instructions | python | mandiant/capa | capa/features/extractors/binexport2/__init__.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binexport2/__init__.py | Apache-2.0 |
def is_security_cookie(
fhi: FunctionContext,
bbi: BasicBlockContext,
instruction_address: int,
instruction: BinExport2.Instruction,
) -> bool:
"""
check if an instruction is related to security cookie checks.
"""
be2: BinExport2 = fhi.ctx.be2
idx: BinExport2Index = fhi.ctx.idx
... |
check if an instruction is related to security cookie checks.
| is_security_cookie | python | mandiant/capa | capa/features/extractors/binexport2/arch/intel/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binexport2/arch/intel/insn.py | Apache-2.0 |
def extract_insn_nzxor_characteristic_features(
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""
parse non-zeroing XOR instruction from the given instruction.
ignore expected non-zeroing XORs, e.g. security cookies.
"""
fhi: FunctionContext = fh.inner... |
parse non-zeroing XOR instruction from the given instruction.
ignore expected non-zeroing XORs, e.g. security cookies.
| extract_insn_nzxor_characteristic_features | python | mandiant/capa | capa/features/extractors/binexport2/arch/intel/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binexport2/arch/intel/insn.py | Apache-2.0 |
def extract_bb_tight_loop(fh: FunctionHandle, bbh: BBHandle) -> Iterator[tuple[Feature, Address]]:
"""extract tight loop indicators from a basic block"""
bb: BinjaBasicBlock = bbh.inner
for edge in bb.outgoing_edges:
if edge.target.start == bb.start:
yield Characteristic("tight loop"), b... | extract tight loop indicators from a basic block | extract_bb_tight_loop | python | mandiant/capa | capa/features/extractors/binja/basicblock.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/basicblock.py | Apache-2.0 |
def extract_file_import_names(bv: BinaryView) -> Iterator[tuple[Feature, Address]]:
"""extract function imports
1. imports by ordinal:
- modulename.#ordinal
2. imports by name, results in two features to support importname-only
matching:
- modulename.importname
- importname
"""
... | extract function imports
1. imports by ordinal:
- modulename.#ordinal
2. imports by name, results in two features to support importname-only
matching:
- modulename.importname
- importname
| extract_file_import_names | python | mandiant/capa | capa/features/extractors/binja/file.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/file.py | Apache-2.0 |
def extract_file_strings(bv: BinaryView) -> Iterator[tuple[Feature, Address]]:
"""extract ASCII and UTF-16 LE strings"""
for s in bv.strings:
yield String(s.value), FileOffsetAddress(s.start) | extract ASCII and UTF-16 LE strings | extract_file_strings | python | mandiant/capa | capa/features/extractors/binja/file.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/file.py | Apache-2.0 |
def extract_file_function_names(bv: BinaryView) -> Iterator[tuple[Feature, Address]]:
"""
extract the names of statically-linked library functions.
"""
for sym_name in bv.symbols:
for sym in bv.symbols[sym_name]:
if sym.type not in [SymbolType.LibraryFunctionSymbol, SymbolType.Functi... |
extract the names of statically-linked library functions.
| extract_file_function_names | python | mandiant/capa | capa/features/extractors/binja/file.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/file.py | Apache-2.0 |
def get_desktop_entry(name: str) -> Optional[Path]:
"""
Find the path for the given XDG Desktop Entry name.
Like:
>> get_desktop_entry("com.vector35.binaryninja.desktop")
Path("~/.local/share/applications/com.vector35.binaryninja.desktop")
"""
assert sys.platform in ("linux", "linu... |
Find the path for the given XDG Desktop Entry name.
Like:
>> get_desktop_entry("com.vector35.binaryninja.desktop")
Path("~/.local/share/applications/com.vector35.binaryninja.desktop")
| get_desktop_entry | python | mandiant/capa | capa/features/extractors/binja/find_binja_api.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/find_binja_api.py | Apache-2.0 |
def is_binaryninja_installed() -> bool:
"""Is the binaryninja module ready to import?"""
try:
return importlib.util.find_spec("binaryninja") is not None
except ModuleNotFoundError:
return False | Is the binaryninja module ready to import? | is_binaryninja_installed | python | mandiant/capa | capa/features/extractors/binja/find_binja_api.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/find_binja_api.py | Apache-2.0 |
def get_printable_len_ascii(s: bytes) -> int:
"""Return string length if all operand bytes are ascii or utf16-le printable"""
count = 0
for c in s:
if c == 0:
return count
if c < 127 and chr(c) in string.printable:
count += 1
return count | Return string length if all operand bytes are ascii or utf16-le printable | get_printable_len_ascii | python | mandiant/capa | capa/features/extractors/binja/function.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/function.py | Apache-2.0 |
def bb_contains_stackstring(f: Function, bb: MediumLevelILBasicBlock) -> bool:
"""check basic block for stackstring indicators
true if basic block contains enough moves of constant bytes to the stack
"""
count = 0
for il in bb:
count += get_stack_string_len(f, il)
if count > MIN_STA... | check basic block for stackstring indicators
true if basic block contains enough moves of constant bytes to the stack
| bb_contains_stackstring | python | mandiant/capa | capa/features/extractors/binja/function.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/function.py | Apache-2.0 |
def extract_insn_api_features(fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]:
"""
parse instruction API features
example:
call dword [0x00473038]
"""
func: Function = fh.inner
bv: BinaryView = func.view
for llil in func.get_llils_at(ih.addres... |
parse instruction API features
example:
call dword [0x00473038]
| extract_insn_api_features | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_insn_number_features(
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""
parse instruction number features
example:
push 3136B0h ; dwControlCode
"""
func: Function = fh.inner
results: list[tuple[Any[Number, OperandNum... |
parse instruction number features
example:
push 3136B0h ; dwControlCode
| extract_insn_number_features | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_insn_bytes_features(fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]:
"""
parse referenced byte sequences
example:
push offset iid_004118d4_IShellLinkA ; riid
"""
func: Function = fh.inner
bv: BinaryView = func.view
candidate_add... |
parse referenced byte sequences
example:
push offset iid_004118d4_IShellLinkA ; riid
| extract_insn_bytes_features | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_insn_string_features(
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""
parse instruction string features
example:
push offset aAcr ; "ACR > "
"""
func: Function = fh.inner
bv: BinaryView = func.view
candidate_addrs =... |
parse instruction string features
example:
push offset aAcr ; "ACR > "
| extract_insn_string_features | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_insn_offset_features(
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""
parse instruction structure offset features
example:
.text:0040112F cmp [esi+4], ebx
"""
func: Function = fh.inner
results: list[tuple[Any[Offset, Operand... |
parse instruction structure offset features
example:
.text:0040112F cmp [esi+4], ebx
| extract_insn_offset_features | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def is_nzxor_stack_cookie(f: Function, bb: bn.BasicBlock, llil: LowLevelILInstruction) -> bool:
"""check if nzxor exists within stack cookie delta"""
# TODO(xusheng): use LLIL SSA to do more accurate analysis
# https://github.com/mandiant/capa/issues/1609
reg_names = []
if llil.left.operation == Lo... | check if nzxor exists within stack cookie delta | is_nzxor_stack_cookie | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_insn_nzxor_characteristic_features(
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""
parse instruction non-zeroing XOR instruction
ignore expected non-zeroing XORs, e.g. security cookies
"""
func: Function = fh.inner
results = []
... |
parse instruction non-zeroing XOR instruction
ignore expected non-zeroing XORs, e.g. security cookies
| extract_insn_nzxor_characteristic_features | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_insn_obfs_call_plus_5_characteristic_features(
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""
parse call $+5 instruction from the given instruction.
"""
insn: DisassemblyInstruction = ih.inner
if insn.text[0].text == "call" and insn.text... |
parse call $+5 instruction from the given instruction.
| extract_insn_obfs_call_plus_5_characteristic_features | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_insn_peb_access_characteristic_features(
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""parse instruction peb access
fs:[0x30] on x86, gs:[0x60] on x64
"""
func: Function = fh.inner
results = []
def llil_checker(il: LowLevelILInstr... | parse instruction peb access
fs:[0x30] on x86, gs:[0x60] on x64
| extract_insn_peb_access_characteristic_features | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_insn_segment_access_features(
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""parse instruction fs or gs access"""
func: Function = fh.inner
results = []
def llil_checker(il: LowLevelILInstruction, parent: LowLevelILInstruction, index: int) ... | parse instruction fs or gs access | extract_insn_segment_access_features | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_insn_cross_section_cflow(
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""inspect the instruction for a CALL or JMP that crosses section boundaries"""
func: Function = fh.inner
bv: BinaryView = func.view
if bv is None:
return
seg... | inspect the instruction for a CALL or JMP that crosses section boundaries | extract_insn_cross_section_cflow | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_function_calls_from(fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]:
"""extract functions calls from features
most relevant at the function scope, however, its most efficient to extract at the instruction scope
"""
func: Function = fh.inner
bv: Bi... | extract functions calls from features
most relevant at the function scope, however, its most efficient to extract at the instruction scope
| extract_function_calls_from | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_function_indirect_call_characteristic_features(
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
) -> Iterator[tuple[Feature, Address]]:
"""extract indirect function calls (e.g., call eax or call dword ptr [edx+4])
does not include calls like => call ds:dword_ABD4974
most relevant at the f... | extract indirect function calls (e.g., call eax or call dword ptr [edx+4])
does not include calls like => call ds:dword_ABD4974
most relevant at the function or basic block scope;
however, its most efficient to extract at the instruction scope
| extract_function_indirect_call_characteristic_features | python | mandiant/capa | capa/features/extractors/binja/insn.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/binja/insn.py | Apache-2.0 |
def extract_call_features(ph: ProcessHandle, th: ThreadHandle, ch: CallHandle) -> Iterator[tuple[Feature, Address]]:
"""
this method extracts the given call's features (such as API name and arguments),
and returns them as API, Number, and String features.
args:
ph: process handle (for defining th... |
this method extracts the given call's features (such as API name and arguments),
and returns them as API, Number, and String features.
args:
ph: process handle (for defining the extraction scope)
th: thread handle (for defining the extraction scope)
ch: call handle (for defining the extr... | extract_call_features | python | mandiant/capa | capa/features/extractors/cape/call.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/cape/call.py | Apache-2.0 |
def get_processes(report: CapeReport) -> Iterator[ProcessHandle]:
"""
get all the created processes for a sample
"""
seen_processes = {}
for process in report.behavior.processes:
addr = ProcessAddress(pid=process.process_id, ppid=process.parent_id)
yield ProcessHandle(address=addr, i... |
get all the created processes for a sample
| get_processes | python | mandiant/capa | capa/features/extractors/cape/file.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/cape/file.py | Apache-2.0 |
def find_process(processes: list[dict[str, Any]], ph: ProcessHandle) -> dict[str, Any]:
"""
find a specific process identified by a process handler.
args:
processes: a list of processes extracted by CAPE
ph: handle of the sought process
return:
a CAPE-defined dictionary for the sough... |
find a specific process identified by a process handler.
args:
processes: a list of processes extracted by CAPE
ph: handle of the sought process
return:
a CAPE-defined dictionary for the sought process' information
| find_process | python | mandiant/capa | capa/features/extractors/cape/helpers.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/cape/helpers.py | Apache-2.0 |
def get_threads(ph: ProcessHandle) -> Iterator[ThreadHandle]:
"""
get the threads associated with a given process
"""
process: Process = ph.inner
threads: list[int] = process.threads
for thread in threads:
address: ThreadAddress = ThreadAddress(process=ph.address, tid=thread)
yi... |
get the threads associated with a given process
| get_threads | python | mandiant/capa | capa/features/extractors/cape/process.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/cape/process.py | Apache-2.0 |
def extract_environ_strings(ph: ProcessHandle) -> Iterator[tuple[Feature, Address]]:
"""
extract strings from a process' provided environment variables.
"""
process: Process = ph.inner
for value in (value for value in process.environ.values() if value):
yield String(value), ph.address |
extract strings from a process' provided environment variables.
| extract_environ_strings | python | mandiant/capa | capa/features/extractors/cape/process.py | https://github.com/mandiant/capa/blob/master/capa/features/extractors/cape/process.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.