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 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 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/features/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/insn.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 get_printable_len_wide(s: bytes) -> int: """Return string length if all operand bytes are ascii or utf16-le printable""" if all(c == 0x00 for c in s[1::2]): return get_printable_len_ascii(s[::2]) return 0
Return string length if all operand bytes are ascii or utf16-le printable
get_printable_len_wide
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
def resolve_dotnet_token(pe: dnfile.dnPE, token: Token) -> Union[dnfile.base.MDTableRow, InvalidToken, str]: """map generic token to string or table row""" assert pe.net is not None assert pe.net.mdtables is not None if isinstance(token, StringToken): user_string: Optional[str] = read_dotnet_us...
map generic token to string or table row
resolve_dotnet_token
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def read_dotnet_user_string(pe: dnfile.dnPE, token: StringToken) -> Optional[str]: """read user string from #US stream""" assert pe.net is not None if pe.net.user_strings is None: # stream may not exist (seen in obfuscated .NET) logger.debug("#US stream does not exist for stream index 0x%08...
read user string from #US stream
read_dotnet_user_string
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def get_dotnet_managed_imports(pe: dnfile.dnPE) -> Iterator[DnType]: """get managed imports from MemberRef table see https://www.ntcore.com/files/dotnetformat.htm 10 - MemberRef Table Each row represents an imported method Class (index into the TypeRef, ModuleRef, MethodDef, TypeSpec o...
get managed imports from MemberRef table see https://www.ntcore.com/files/dotnetformat.htm 10 - MemberRef Table Each row represents an imported method Class (index into the TypeRef, ModuleRef, MethodDef, TypeSpec or TypeDef tables) Name (index into String heap) 01 - TypeRef...
get_dotnet_managed_imports
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def get_dotnet_methoddef_property_accessors(pe: dnfile.dnPE) -> Iterator[tuple[int, str]]: """get MethodDef methods used to access properties see https://www.ntcore.com/files/dotnetformat.htm 24 - MethodSemantics Table Links Events and Properties to specific methods. For example one Event can be a...
get MethodDef methods used to access properties see https://www.ntcore.com/files/dotnetformat.htm 24 - MethodSemantics Table Links Events and Properties to specific methods. For example one Event can be associated to more methods. A property uses this table to associate get/set methods. Se...
get_dotnet_methoddef_property_accessors
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def get_dotnet_managed_methods(pe: dnfile.dnPE) -> Iterator[DnType]: """get managed method names from TypeDef table see https://www.ntcore.com/files/dotnetformat.htm 02 - TypeDef Table Each row represents a class in the current assembly. TypeName (index into String heap) Ty...
get managed method names from TypeDef table see https://www.ntcore.com/files/dotnetformat.htm 02 - TypeDef Table Each row represents a class in the current assembly. TypeName (index into String heap) TypeNamespace (index into String heap) MethodList (index into Meth...
get_dotnet_managed_methods
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def get_dotnet_fields(pe: dnfile.dnPE) -> Iterator[DnType]: """get fields from TypeDef table see https://www.ntcore.com/files/dotnetformat.htm 02 - TypeDef Table Each row represents a class in the current assembly. TypeName (index into String heap) TypeNamespace (index into...
get fields from TypeDef table see https://www.ntcore.com/files/dotnetformat.htm 02 - TypeDef Table Each row represents a class in the current assembly. TypeName (index into String heap) TypeNamespace (index into String heap) FieldList (index into Field table; it mar...
get_dotnet_fields
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def get_dotnet_managed_method_bodies(pe: dnfile.dnPE) -> Iterator[tuple[int, CilMethodBody]]: """get managed methods from MethodDef table""" for rid, method_def in iter_dotnet_table(pe, dnfile.mdtable.MethodDef.number): assert isinstance(method_def, dnfile.mdtable.MethodDefRow) if not method_de...
get managed methods from MethodDef table
get_dotnet_managed_method_bodies
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def get_dotnet_unmanaged_imports(pe: dnfile.dnPE) -> Iterator[DnUnmanagedMethod]: """get unmanaged imports from ImplMap table see https://www.ntcore.com/files/dotnetformat.htm 28 - ImplMap Table ImplMap table holds information about unmanaged methods that can be reached from managed code, using PI...
get unmanaged imports from ImplMap table see https://www.ntcore.com/files/dotnetformat.htm 28 - ImplMap Table ImplMap table holds information about unmanaged methods that can be reached from managed code, using PInvoke dispatch MemberForwarded (index into the Field or MethodDef table; more...
get_dotnet_unmanaged_imports
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def resolve_nested_typedef_name( nested_class_table: dict, index: int, typedef: dnfile.mdtable.TypeDefRow, pe: dnfile.dnPE ) -> tuple[str, tuple[str, ...]]: """Resolves all nested TypeDef class names. Returns the namespace as a str and the nested TypeRef name as a tuple""" if index in nested_class_table: ...
Resolves all nested TypeDef class names. Returns the namespace as a str and the nested TypeRef name as a tuple
resolve_nested_typedef_name
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def resolve_nested_typeref_name( index: int, typeref: dnfile.mdtable.TypeRefRow, pe: dnfile.dnPE ) -> tuple[str, tuple[str, ...]]: """Resolves all nested TypeRef class names. Returns the namespace as a str and the nested TypeRef name as a tuple""" # If the ResolutionScope decodes to a typeRef type then it i...
Resolves all nested TypeRef class names. Returns the namespace as a str and the nested TypeRef name as a tuple
resolve_nested_typeref_name
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def get_dotnet_nested_class_table_index(pe: dnfile.dnPE) -> dict[int, int]: """Build index for EnclosingClass based off the NestedClass row index in the nestedclass table""" nested_class_table = {} # Used to find nested classes in typedef for _, nestedclass in iter_dotnet_table(pe, dnfile.mdtable.Neste...
Build index for EnclosingClass based off the NestedClass row index in the nestedclass table
get_dotnet_nested_class_table_index
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def get_dotnet_types(pe: dnfile.dnPE) -> Iterator[DnType]: """get .NET types from TypeDef and TypeRef tables""" nested_class_table = get_dotnet_nested_class_table_index(pe) for rid, typedef in iter_dotnet_table(pe, dnfile.mdtable.TypeDef.number): assert isinstance(typedef, dnfile.mdtable.TypeDefRow...
get .NET types from TypeDef and TypeRef tables
get_dotnet_types
python
mandiant/capa
capa/features/extractors/dnfile/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/helpers.py
Apache-2.0
def get_callee( pe: dnfile.dnPE, cache: DnFileFeatureExtractorCache, token: Token ) -> Optional[Union[DnType, DnUnmanagedMethod]]: """map .NET token to un/managed (generic) method""" token_: int if token.table == dnfile.mdtable.MethodSpec.number: # map MethodSpec to MethodDef or MemberRef ...
map .NET token to un/managed (generic) method
get_callee
python
mandiant/capa
capa/features/extractors/dnfile/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/insn.py
Apache-2.0
def extract_insn_namespace_class_features( fh: FunctionHandle, bh, ih: InsnHandle ) -> Iterator[tuple[Union[Namespace, Class], Address]]: """parse instruction namespace and class features""" type_: Optional[Union[DnType, DnUnmanagedMethod]] = None if ih.inner.opcode in ( OpCodes.Call, O...
parse instruction namespace and class features
extract_insn_namespace_class_features
python
mandiant/capa
capa/features/extractors/dnfile/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/dnfile/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/drakvuf/call.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/drakvuf/call.py
Apache-2.0
def get_processes(calls: dict[ProcessAddress, dict[ThreadAddress, list[Call]]]) -> Iterator[ProcessHandle]: """ Get all the created processes for a sample. """ for proc_addr, calls_per_thread in calls.items(): sample_call = next(iter(calls_per_thread.values()))[0] # get process name yie...
Get all the created processes for a sample.
get_processes
python
mandiant/capa
capa/features/extractors/drakvuf/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/drakvuf/file.py
Apache-2.0
def get_threads( calls: dict[ProcessAddress, dict[ThreadAddress, list[Call]]], ph: ProcessHandle ) -> Iterator[ThreadHandle]: """ Get the threads associated with a given process. """ for thread_addr in calls[ph.address]: yield ThreadHandle(address=thread_addr, inner={})
Get the threads associated with a given process.
get_threads
python
mandiant/capa
capa/features/extractors/drakvuf/process.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/drakvuf/process.py
Apache-2.0
def get_printable_len(op: ghidra.program.model.scalar.Scalar) -> int: """Return string length if all operand bytes are ascii or utf16-le printable""" op_bit_len = op.bitLength() op_byte_len = op_bit_len // 8 op_val = op.getValue() if op_bit_len == 8: chars = struct.pack("<B", op_val & 0xFF)...
Return string length if all operand bytes are ascii or utf16-le printable
get_printable_len
python
mandiant/capa
capa/features/extractors/ghidra/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/basicblock.py
Apache-2.0
def is_mov_imm_to_stack(insn: ghidra.program.database.code.InstructionDB) -> bool: """verify instruction moves immediate onto stack""" # Ghidra will Bitwise OR the OperandTypes to assign multiple # i.e., the first operand is a stackvar (dynamically allocated), # and the second is a scalar value (single...
verify instruction moves immediate onto stack
is_mov_imm_to_stack
python
mandiant/capa
capa/features/extractors/ghidra/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/basicblock.py
Apache-2.0
def bb_contains_stackstring(bb: ghidra.program.model.block.CodeBlock) -> bool: """check basic block for stackstring indicators true if basic block contains enough moves of constant bytes to the stack """ count = 0 for insn in currentProgram().getListing().getInstructions(bb, True): # type: ignore ...
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/ghidra/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/basicblock.py
Apache-2.0
def _bb_has_tight_loop(bb: ghidra.program.model.block.CodeBlock): """ parse tight loops, true if last instruction in basic block branches to bb start """ # Reverse Ordered, first InstructionDB last_insn = currentProgram().getListing().getInstructions(bb, False).next() # type: ignore [name-defined] ...
parse tight loops, true if last instruction in basic block branches to bb start
_bb_has_tight_loop
python
mandiant/capa
capa/features/extractors/ghidra/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/basicblock.py
Apache-2.0
def extract_bb_stackstring(fh: FunctionHandle, bbh: BBHandle) -> Iterator[tuple[Feature, Address]]: """extract stackstring indicators from basic block""" bb: ghidra.program.model.block.CodeBlock = bbh.inner if bb_contains_stackstring(bb): yield Characteristic("stack string"), bbh.address
extract stackstring indicators from basic block
extract_bb_stackstring
python
mandiant/capa
capa/features/extractors/ghidra/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/basicblock.py
Apache-2.0
def extract_bb_tight_loop(fh: FunctionHandle, bbh: BBHandle) -> Iterator[tuple[Feature, Address]]: """check basic block for tight loop indicators""" bb: ghidra.program.model.block.CodeBlock = bbh.inner if _bb_has_tight_loop(bb): yield Characteristic("tight loop"), bbh.address
check basic block for tight loop indicators
extract_bb_tight_loop
python
mandiant/capa
capa/features/extractors/ghidra/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/basicblock.py
Apache-2.0
def extract_features(fh: FunctionHandle, bbh: BBHandle) -> Iterator[tuple[Feature, Address]]: """ extract features from the given basic block. args: bb: the basic block to process. yields: tuple[Feature, int]: the features and their location found in this basic block. """ yield B...
extract features from the given basic block. args: bb: the basic block to process. yields: tuple[Feature, int]: the features and their location found in this basic block.
extract_features
python
mandiant/capa
capa/features/extractors/ghidra/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/basicblock.py
Apache-2.0
def find_embedded_pe(block_bytez: bytes, mz_xor: list[tuple[bytes, bytes, int]]) -> Iterator[tuple[int, int]]: """check segment for embedded PE adapted for Ghidra from: https://github.com/vivisect/vivisect/blob/91e8419a861f4977https://github.com/vivisect/vivisect/blob/91e8419a861f49779f18316f155311967e6968...
check segment for embedded PE adapted for Ghidra from: https://github.com/vivisect/vivisect/blob/91e8419a861f4977https://github.com/vivisect/vivisect/blob/91e8419a861f49779f18316f155311967e696836/PE/carve.py#L259f18316f155311967e696836/PE/carve.py#L25
find_embedded_pe
python
mandiant/capa
capa/features/extractors/ghidra/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/file.py
Apache-2.0
def extract_file_import_names() -> 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 """ for f in c...
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/ghidra/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/file.py
Apache-2.0
def extract_file_strings() -> Iterator[tuple[Feature, Address]]: """extract ASCII and UTF-16 LE strings""" for block in currentProgram().getMemory().getBlocks(): # type: ignore [name-defined] # noqa: F821 if not block.isInitialized(): continue p_bytes = capa.features.extractors.gh...
extract ASCII and UTF-16 LE strings
extract_file_strings
python
mandiant/capa
capa/features/extractors/ghidra/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/file.py
Apache-2.0
def extract_file_function_names() -> Iterator[tuple[Feature, Address]]: """ extract the names of statically-linked library functions. """ for sym in currentProgram().getSymbolTable().getAllSymbols(True): # type: ignore [name-defined] # noqa: F821 # .isExternal() misses more than this config fo...
extract the names of statically-linked library functions.
extract_file_function_names
python
mandiant/capa
capa/features/extractors/ghidra/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/file.py
Apache-2.0
def find_byte_sequence(addr: ghidra.program.model.address.Address, seq: bytes) -> Iterator[int]: """yield all ea of a given byte sequence args: addr: start address seq: bytes to search e.g. b"\x01\x03" """ seqstr = "".join([f"\\x{b:02x}" for b in seq]) eas = findBytes(addr, seqstr, ...
yield all ea of a given byte sequence args: addr: start address seq: bytes to search e.g. b""
find_byte_sequence
python
mandiant/capa
capa/features/extractors/ghidra/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/helpers.py
Apache-2.0