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 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 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_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 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
def get_bytes(addr: ghidra.program.model.address.Address, length: int) -> bytes: """yield length bytes at addr args: addr: Address to begin pull from length: length of bytes to pull """ try: return ints_to_bytes(getBytes(addr, length)) # type: ignore [name-defined] # noqa: F821...
yield length bytes at addr args: addr: Address to begin pull from length: length of bytes to pull
get_bytes
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
def get_function_blocks(fh: FunctionHandle) -> Iterator[BBHandle]: """yield BBHandle for each bb in a given function""" func: ghidra.program.database.function.FunctionDB = fh.inner for bb in SimpleBlockIterator(BasicBlockModel(currentProgram()), func.getBody(), monitor()): # type: ignore [name-defined] # ...
yield BBHandle for each bb in a given function
get_function_blocks
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
def get_insn_in_range(bbh: BBHandle) -> Iterator[InsnHandle]: """yield InshHandle for each insn in a given basicblock""" for insn in currentProgram().getListing().getInstructions(bbh.inner, True): # type: ignore [name-defined] # noqa: F821 yield InsnHandle(address=AbsoluteVirtualAddress(insn.getAddress...
yield InshHandle for each insn in a given basicblock
get_insn_in_range
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
def get_file_externs() -> dict[int, list[str]]: """ Gets function names & addresses of statically-linked library functions Ghidra's external namespace is mostly reserved for dynamically-linked imports. Statically-linked functions are part of the global namespace. Filtering on the type, source, and ...
Gets function names & addresses of statically-linked library functions Ghidra's external namespace is mostly reserved for dynamically-linked imports. Statically-linked functions are part of the global namespace. Filtering on the type, source, and namespace of the symbols yield more statically-link...
get_file_externs
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
def map_fake_import_addrs() -> dict[int, list[int]]: """ Map ghidra's fake import entrypoints to their real addresses Helps as many Ghidra Scripting API calls end up returning these external (fake) addresses. Undocumented but intended Ghidra behavior: - Import entryPoint fields are stored...
Map ghidra's fake import entrypoints to their real addresses Helps as many Ghidra Scripting API calls end up returning these external (fake) addresses. Undocumented but intended Ghidra behavior: - Import entryPoint fields are stored in the 'EXTERNAL:' AddressSpace. 'getEntryPoint()' r...
map_fake_import_addrs
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
def is_stack_referenced(insn: ghidra.program.database.code.InstructionDB) -> bool: """generic catch-all for stack references""" for i in range(insn.getNumOperands()): if insn.getOperandType(i) == OperandType.REGISTER: if "BP" in insn.getRegister(i).getName(): return True ...
generic catch-all for stack references
is_stack_referenced
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
def handle_thunk(addr: ghidra.program.model.address.Address): """Follow thunk chains down to a reasonable depth""" ref = addr for _ in range(THUNK_CHAIN_DEPTH_DELTA): thunk_jmp = getInstructionAt(ref) # type: ignore [name-defined] # noqa: F821 if thunk_jmp and is_call_or_jmp(thunk_jmp): ...
Follow thunk chains down to a reasonable depth
handle_thunk
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
def find_data_references_from_insn(insn, max_depth: int = 10): """yield data references from given instruction""" for reference in insn.getReferencesFrom(): if not reference.getReferenceType().isData(): # only care about data references continue to_addr = reference.getTo...
yield data references from given instruction
find_data_references_from_insn
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
def get_imports(ctx: dict[str, Any]) -> dict[int, Any]: """Populate the import cache for this context""" if "imports_cache" not in ctx: ctx["imports_cache"] = capa.features.extractors.ghidra.helpers.get_file_imports() return ctx["imports_cache"]
Populate the import cache for this context
get_imports
python
mandiant/capa
capa/features/extractors/ghidra/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/insn.py
Apache-2.0
def get_externs(ctx: dict[str, Any]) -> dict[int, Any]: """Populate the externs cache for this context""" if "externs_cache" not in ctx: ctx["externs_cache"] = capa.features.extractors.ghidra.helpers.get_file_externs() return ctx["externs_cache"]
Populate the externs cache for this context
get_externs
python
mandiant/capa
capa/features/extractors/ghidra/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/insn.py
Apache-2.0
def get_fakes(ctx: dict[str, Any]) -> dict[int, Any]: """Populate the fake import addrs cache for this context""" if "fakes_cache" not in ctx: ctx["fakes_cache"] = capa.features.extractors.ghidra.helpers.map_fake_import_addrs() return ctx["fakes_cache"]
Populate the fake import addrs cache for this context
get_fakes
python
mandiant/capa
capa/features/extractors/ghidra/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/insn.py
Apache-2.0
def check_for_api_call( insn, externs: dict[int, Any], fakes: dict[int, Any], imports: dict[int, Any], imp_or_ex: bool ) -> Iterator[Any]: """check instruction for API call params: externs - external library functions cache fakes - mapped fake import addresses cache imports - import...
check instruction for API call params: externs - external library functions cache fakes - mapped fake import addresses cache imports - imported functions cache imp_or_ex - flag to check imports or externs yields: matched api calls
check_for_api_call
python
mandiant/capa
capa/features/extractors/ghidra/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/insn.py
Apache-2.0
def extract_insn_bytes_features(fh: FunctionHandle, bb: BBHandle, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]: """ parse referenced byte sequences example: push offset iid_004118d4_IShellLinkA ; riid """ for addr in capa.features.extractors.ghidra.helpers.find_data_references_fr...
parse referenced byte sequences example: push offset iid_004118d4_IShellLinkA ; riid
extract_insn_bytes_features
python
mandiant/capa
capa/features/extractors/ghidra/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/insn.py
Apache-2.0
def extract_insn_peb_access_characteristic_features( fh: FunctionHandle, bb: BBHandle, ih: InsnHandle ) -> Iterator[tuple[Feature, Address]]: """parse instruction peb access fs:[0x30] on x86, gs:[0x60] on x64 """ insn: ghidra.program.database.code.InstructionDB = ih.inner insn_str = insn.toSt...
parse instruction peb access fs:[0x30] on x86, gs:[0x60] on x64
extract_insn_peb_access_characteristic_features
python
mandiant/capa
capa/features/extractors/ghidra/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/insn.py
Apache-2.0
def check_nzxor_security_cookie_delta( fh: ghidra.program.database.function.FunctionDB, insn: ghidra.program.database.code.InstructionDB ): """ Get the first and last blocks of the function Check if insn within first addr of first bb + delta Check if insn within last addr of last bb - delta """ ...
Get the first and last blocks of the function Check if insn within first addr of first bb + delta Check if insn within last addr of last bb - delta
check_nzxor_security_cookie_delta
python
mandiant/capa
capa/features/extractors/ghidra/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ghidra/insn.py
Apache-2.0
def check_segment_for_pe(seg: idaapi.segment_t) -> Iterator[tuple[int, int]]: """check segment for embedded PE adapted for IDA from: https://github.com/vivisect/vivisect/blob/91e8419a861f49779f18316f155311967e696836/PE/carve.py#L25 """ seg_max = seg.end_ea mz_xor = [ ( capa....
check segment for embedded PE adapted for IDA from: https://github.com/vivisect/vivisect/blob/91e8419a861f49779f18316f155311967e696836/PE/carve.py#L25
check_segment_for_pe
python
mandiant/capa
capa/features/extractors/ida/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/file.py
Apache-2.0
def extract_file_embedded_pe() -> Iterator[tuple[Feature, Address]]: """extract embedded PE features IDA must load resource sections for this to be complete - '-R' from console - Check 'Load resource sections' when opening binary in IDA manually """ for seg in capa.features.extractors.i...
extract embedded PE features IDA must load resource sections for this to be complete - '-R' from console - Check 'Load resource sections' when opening binary in IDA manually
extract_file_embedded_pe
python
mandiant/capa
capa/features/extractors/ida/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/file.py
Apache-2.0
def extract_file_section_names() -> Iterator[tuple[Feature, Address]]: """extract section names IDA must load resource sections for this to be complete - '-R' from console - Check 'Load resource sections' when opening binary in IDA manually """ for seg in capa.features.extractors.ida.he...
extract section names IDA must load resource sections for this to be complete - '-R' from console - Check 'Load resource sections' when opening binary in IDA manually
extract_file_section_names
python
mandiant/capa
capa/features/extractors/ida/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/file.py
Apache-2.0
def extract_file_strings() -> Iterator[tuple[Feature, Address]]: """extract ASCII and UTF-16 LE strings IDA must load resource sections for this to be complete - '-R' from console - Check 'Load resource sections' when opening binary in IDA manually """ for seg in capa.features.extractor...
extract ASCII and UTF-16 LE strings IDA must load resource sections for this to be complete - '-R' from console - Check 'Load resource sections' when opening binary in IDA manually
extract_file_strings
python
mandiant/capa
capa/features/extractors/ida/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/file.py
Apache-2.0
def find_byte_sequence(start: int, end: int, seq: bytes) -> Iterator[int]: """yield all ea of a given byte sequence args: start: min virtual address end: max virtual address seq: bytes to search e.g. b"\x01\x03" """ patterns = ida_bytes.compiled_binpa...
yield all ea of a given byte sequence args: start: min virtual address end: max virtual address seq: bytes to search e.g. b""
find_byte_sequence
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def get_functions( start: Optional[int] = None, end: Optional[int] = None, skip_thunks: bool = False, skip_libs: bool = False ) -> Iterator[FunctionHandle]: """get functions, range optional args: start: min virtual address end: max virtual address """ for ea in idautils.Functions(st...
get functions, range optional args: start: min virtual address end: max virtual address
get_functions
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def get_segments(skip_header_segments=False) -> Iterator[idaapi.segment_t]: """get list of segments (sections) in the binary image args: skip_header_segments: IDA may load header segments - skip if set """ for n in range(idaapi.get_segm_qty()): seg = idaapi.getnseg(n) if seg and...
get list of segments (sections) in the binary image args: skip_header_segments: IDA may load header segments - skip if set
get_segments
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def get_segment_buffer(seg: idaapi.segment_t) -> bytes: """return bytes stored in a given segment decrease buffer size until IDA is able to read bytes from the segment """ buff = b"" sz = seg.end_ea - seg.start_ea while sz > 0: buff = idaapi.get_bytes(seg.start_ea, sz) if buff:...
return bytes stored in a given segment decrease buffer size until IDA is able to read bytes from the segment
get_segment_buffer
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def get_instructions_in_range(start: int, end: int) -> Iterator[idaapi.insn_t]: """yield instructions in range args: start: virtual address (inclusive) end: virtual address (exclusive) """ for head in idautils.Heads(start, end): insn = idautils.DecodeInstruction(head) if...
yield instructions in range args: start: virtual address (inclusive) end: virtual address (exclusive)
get_instructions_in_range
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def find_string_at(ea: int, min_: int = 4) -> str: """check if ASCII string exists at a given virtual address""" found = idaapi.get_strlit_contents(ea, -1, idaapi.STRTYPE_C) if found and len(found) >= min_: try: found = found.decode("ascii") # hacky check for IDA bug; get_str...
check if ASCII string exists at a given virtual address
find_string_at
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def get_op_phrase_info(op: idaapi.op_t) -> dict: """parse phrase features from operand Pretty much dup of sark's implementation: https://github.com/tmr232/Sark/blob/master/sark/code/instruction.py#L28-L73 """ if op.type not in (idaapi.o_phrase, idaapi.o_displ): return {} scale = 1 ...
parse phrase features from operand Pretty much dup of sark's implementation: https://github.com/tmr232/Sark/blob/master/sark/code/instruction.py#L28-L73
get_op_phrase_info
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def is_op_offset(insn: idaapi.insn_t, op: idaapi.op_t) -> bool: """Check is an operand has been marked as an offset (by auto-analysis or manually)""" flags = idaapi.get_flags(insn.ea) return ida_bytes.is_off(flags, op.n)
Check is an operand has been marked as an offset (by auto-analysis or manually)
is_op_offset
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def is_sp_modified(insn: idaapi.insn_t) -> bool: """determine if instruction modifies SP, ESP, RSP""" return any( op.reg == idautils.procregs.sp.reg and is_op_write(insn, op) for op in get_insn_ops(insn, target_ops=(idaapi.o_reg,)) )
determine if instruction modifies SP, ESP, RSP
is_sp_modified
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def is_bp_modified(insn: idaapi.insn_t) -> bool: """check if instruction modifies BP, EBP, RBP""" return any( op.reg == idautils.procregs.bp.reg and is_op_write(insn, op) for op in get_insn_ops(insn, target_ops=(idaapi.o_reg,)) )
check if instruction modifies BP, EBP, RBP
is_bp_modified
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def get_insn_ops(insn: idaapi.insn_t, target_ops: Optional[tuple[Any]] = None) -> idaapi.op_t: """yield op_t for instruction, filter on type if specified""" for op in insn.ops: if op.type == idaapi.o_void: # avoid looping all 6 ops if only subset exists break if target_op...
yield op_t for instruction, filter on type if specified
get_insn_ops
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def mask_op_val(op: idaapi.op_t) -> int: """mask value by data type necessary due to a bug in AMD64 Example: .rsrc:0054C12C mov [ebp+var_4], 0FFFFFFFFh insn.Op2.dtype == idaapi.dt_dword insn.Op2.value == 0xffffffffffffffff """ masks = { idaapi.dt_byte: 0xFF, ...
mask value by data type necessary due to a bug in AMD64 Example: .rsrc:0054C12C mov [ebp+var_4], 0FFFFFFFFh insn.Op2.dtype == idaapi.dt_dword insn.Op2.value == 0xffffffffffffffff
mask_op_val
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def is_basic_block_tight_loop(bb: idaapi.BasicBlock) -> bool: """check basic block loops to self true if last instruction in basic block branches to basic block start """ bb_end = idc.prev_head(bb.end_ea) if bb.start_ea < bb_end: for ref in idautils.CodeRefsFrom(bb_end, True): i...
check basic block loops to self true if last instruction in basic block branches to basic block start
is_basic_block_tight_loop
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def find_data_reference_from_insn(insn: idaapi.insn_t, max_depth: int = 10) -> int: """search for data reference from instruction, return address of instruction if no reference exists""" depth = 0 ea = insn.ea while True: data_refs = list(idautils.DataRefsFrom(ea)) if len(data_refs) !=...
search for data reference from instruction, return address of instruction if no reference exists
find_data_reference_from_insn
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def get_function_blocks(f: idaapi.func_t) -> Iterator[idaapi.BasicBlock]: """yield basic blocks contained in specified function""" # leverage idaapi.FC_NOEXT flag to ignore useless external blocks referenced by the function yield from idaapi.FlowChart(f, flags=(idaapi.FC_PREDS | idaapi.FC_NOEXT))
yield basic blocks contained in specified function
get_function_blocks
python
mandiant/capa
capa/features/extractors/ida/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/helpers.py
Apache-2.0
def get_idalib_user_config_path() -> Optional[Path]: """Get the path to the user's config file based on platform following IDA's user directories.""" # derived from `py-activate-idalib.py` from IDA v9.0 Beta 4 if sys.platform == "win32": # On Windows, use the %APPDATA%\Hex-Rays\IDA Pro directory ...
Get the path to the user's config file based on platform following IDA's user directories.
get_idalib_user_config_path
python
mandiant/capa
capa/features/extractors/ida/idalib.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/idalib.py
Apache-2.0
def contains_stack_cookie_keywords(s: str) -> bool: """ check if string contains stack cookie keywords Examples: xor ecx, ebp ; StackCookie mov eax, ___security_cookie """ if not s: return False s = s.strip().lower() if "cookie" not in s: return False...
check if string contains stack cookie keywords Examples: xor ecx, ebp ; StackCookie mov eax, ___security_cookie
contains_stack_cookie_keywords
python
mandiant/capa
capa/features/extractors/ida/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/insn.py
Apache-2.0
def bb_stack_cookie_registers(bb: idaapi.BasicBlock) -> Iterator[int]: """scan basic block for stack cookie operations yield registers ids that may have been used for stack cookie operations assume instruction that sets stack cookie and nzxor exist in same block and stack cookie register is not modifi...
scan basic block for stack cookie operations yield registers ids that may have been used for stack cookie operations assume instruction that sets stack cookie and nzxor exist in same block and stack cookie register is not modified prior to nzxor Example: .text:004062DA mov eax, ___securit...
bb_stack_cookie_registers
python
mandiant/capa
capa/features/extractors/ida/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/insn.py
Apache-2.0
def is_nzxor_stack_cookie(f: idaapi.func_t, bb: idaapi.BasicBlock, insn: idaapi.insn_t) -> bool: """check if nzxor is related to stack cookie""" if contains_stack_cookie_keywords(idaapi.get_cmt(insn.ea, False)): # Example: # xor ecx, ebp ; StackCookie return True if is_n...
check if nzxor is related to stack cookie
is_nzxor_stack_cookie
python
mandiant/capa
capa/features/extractors/ida/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/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 TODO: IDA should be able to do this.. """ insn: idaapi.insn_t = ih.inner ...
parse instruction peb access fs:[0x30] on x86, gs:[0x60] on x64 TODO: IDA should be able to do this..
extract_insn_peb_access_characteristic_features
python
mandiant/capa
capa/features/extractors/ida/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/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 TODO: IDA should be able to do this... """ insn: idaapi.insn_t = ih.inner if all(op.type != idaapi.o_mem for op in in...
parse instruction fs or gs access TODO: IDA should be able to do this...
extract_insn_segment_access_features
python
mandiant/capa
capa/features/extractors/ida/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/ida/insn.py
Apache-2.0
def _bb_has_stackstring(f, bb): """ extract potential stackstring creation, using the following heuristics: - basic block contains enough moves of constant bytes to the stack """ count = 0 for instr in bb.instructions: if is_mov_imm_to_stack(instr): # add number of operand ...
extract potential stackstring creation, using the following heuristics: - basic block contains enough moves of constant bytes to the stack
_bb_has_stackstring
python
mandiant/capa
capa/features/extractors/viv/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/basicblock.py
Apache-2.0
def extract_stackstring(f: FunctionHandle, bb: BBHandle) -> Iterator[tuple[Feature, Address]]: """check basic block for stackstring indicators""" if _bb_has_stackstring(f, bb.inner): yield Characteristic("stack string"), bb.address
check basic block for stackstring indicators
extract_stackstring
python
mandiant/capa
capa/features/extractors/viv/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/basicblock.py
Apache-2.0
def is_mov_imm_to_stack(instr: envi.archs.i386.disasm.i386Opcode) -> bool: """ Return if instruction moves immediate onto stack """ if not instr.mnem.startswith("mov"): return False try: dst, src = instr.getOperands() except ValueError: # not two operands return ...
Return if instruction moves immediate onto stack
is_mov_imm_to_stack
python
mandiant/capa
capa/features/extractors/viv/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/basicblock.py
Apache-2.0
def get_printable_len(oper: envi.archs.i386.disasm.i386ImmOper) -> int: """ Return string length if all operand bytes are ascii or utf16-le printable """ if oper.tsize == 1: chars = struct.pack("<B", oper.imm) elif oper.tsize == 2: chars = struct.pack("<H", oper.imm) elif oper.ts...
Return string length if all operand bytes are ascii or utf16-le printable
get_printable_len
python
mandiant/capa
capa/features/extractors/viv/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/basicblock.py
Apache-2.0
def extract_features(f: FunctionHandle, bb: BBHandle) -> Iterator[tuple[Feature, Address]]: """ extract features from the given basic block. args: f (viv_utils.Function): the function from which to extract features bb (viv_utils.BasicBlock): the basic block to process. yields: tuple[...
extract features from the given basic block. args: f (viv_utils.Function): the function from which to extract features bb (viv_utils.BasicBlock): 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/viv/basicblock.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/basicblock.py
Apache-2.0
def is_viv_ord_impname(impname: str) -> bool: """ return if import name matches vivisect's ordinal naming scheme `'ord%d' % ord` """ if not impname.startswith("ord"): return False try: int(impname[len("ord") :]) except ValueError: return False else: return Tru...
return if import name matches vivisect's ordinal naming scheme `'ord%d' % ord`
is_viv_ord_impname
python
mandiant/capa
capa/features/extractors/viv/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/file.py
Apache-2.0
def extract_features(vw, buf: bytes) -> Iterator[tuple[Feature, Address]]: """ extract file features from given workspace args: vw (vivisect.VivWorkspace): the vivisect workspace buf: the raw input file bytes yields: tuple[Feature, Address]: a feature and its location. """ f...
extract file features from given workspace args: vw (vivisect.VivWorkspace): the vivisect workspace buf: the raw input file bytes yields: tuple[Feature, Address]: a feature and its location.
extract_features
python
mandiant/capa
capa/features/extractors/viv/file.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/file.py
Apache-2.0
def extract_features(fh: FunctionHandle) -> Iterator[tuple[Feature, Address]]: """ extract features from the given function. args: fh: the function handle from which to extract features yields: tuple[Feature, int]: the features and their location found in this function. """ for fun...
extract features from the given function. args: fh: the function handle from which to extract features yields: tuple[Feature, int]: the features and their location found in this function.
extract_features
python
mandiant/capa
capa/features/extractors/viv/function.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/function.py
Apache-2.0
def get_coderef_from(vw: VivWorkspace, va: int) -> Optional[int]: """ return first code `tova` whose origin is the specified va return None if no code reference is found """ xrefs = vw.getXrefsFrom(va, REF_CODE) if len(xrefs) > 0: return xrefs[0][XR_TO] else: return None
return first code `tova` whose origin is the specified va return None if no code reference is found
get_coderef_from
python
mandiant/capa
capa/features/extractors/viv/helpers.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/helpers.py
Apache-2.0
def get_previous_instructions(vw: VivWorkspace, va: int) -> list[int]: """ collect the instructions that flow to the given address, local to the current function. args: vw (vivisect.Workspace) va (int): the virtual address to inspect returns: list[int]: the prior instructions, which ...
collect the instructions that flow to the given address, local to the current function. args: vw (vivisect.Workspace) va (int): the virtual address to inspect returns: list[int]: the prior instructions, which may fallthrough and/or jump here
get_previous_instructions
python
mandiant/capa
capa/features/extractors/viv/indirect_calls.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/indirect_calls.py
Apache-2.0
def find_definition(vw: VivWorkspace, va: int, reg: int) -> tuple[int, Optional[int]]: """ scan backwards from the given address looking for assignments to the given register. if a constant, return that value. args: vw (vivisect.Workspace) va (int): the virtual address at which to start ana...
scan backwards from the given address looking for assignments to the given register. if a constant, return that value. args: vw (vivisect.Workspace) va (int): the virtual address at which to start analysis reg (int): the vivisect register to study returns: (va: int, value?: in...
find_definition
python
mandiant/capa
capa/features/extractors/viv/indirect_calls.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/indirect_calls.py
Apache-2.0
def resolve_indirect_call(vw: VivWorkspace, va: int, insn: envi.Opcode) -> tuple[int, Optional[int]]: """ inspect the given indirect call instruction and attempt to resolve the target address. args: vw (vivisect.Workspace) va (int): the virtual address at which to start analysis returns: ...
inspect the given indirect call instruction and attempt to resolve the target address. args: vw (vivisect.Workspace) va (int): the virtual address at which to start analysis returns: (va: int, value?: int|None): the address of the assignment and the value, if a constant. raises: ...
resolve_indirect_call
python
mandiant/capa
capa/features/extractors/viv/indirect_calls.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/indirect_calls.py
Apache-2.0
def interface_extract_instruction_XXX( fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle ) -> Iterator[tuple[Feature, Address]]: """ parse features from the given instruction. args: fh: the function handle to process. bbh: the basic block handle to process. ih: the instruction handle ...
parse features from the given instruction. args: fh: the function handle to process. bbh: the basic block handle to process. ih: the instruction handle to process. yields: (Feature, Address): the feature and the address at which its found.
interface_extract_instruction_XXX
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def get_imports(vw): """ caching accessor to vivisect workspace imports avoids performance issues in vivisect when collecting locations returns: dict[int, tuple[str, str]] """ if "imports" in vw.metadata: return vw.metadata["imports"] else: imports = { p[0]: (p[3...
caching accessor to vivisect workspace imports avoids performance issues in vivisect when collecting locations returns: dict[int, tuple[str, str]]
get_imports
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def extract_insn_api_features(fh: FunctionHandle, bb, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]: """ parse API features from the given instruction. example: call dword [0x00473038] """ insn: envi.Opcode = ih.inner f: viv_utils.Function = fh.inner if insn.mnem not in ("call...
parse API features from the given instruction. example: call dword [0x00473038]
extract_insn_api_features
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def derefs(vw, p): """ recursively follow the given pointer, yielding the valid memory addresses along the way. useful when you may have a pointer to string, or pointer to pointer to string, etc. this is a "do what i mean" type of helper function. """ depth = 0 while True: if not vw...
recursively follow the given pointer, yielding the valid memory addresses along the way. useful when you may have a pointer to string, or pointer to pointer to string, etc. this is a "do what i mean" type of helper function.
derefs
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def read_bytes(vw, va: int) -> bytes: """ read up to MAX_BYTES_FEATURE_SIZE from the given address. raises: envi.SegmentationViolation: if the given address is not valid. """ segm = vw.getSegment(va) if not segm: raise envi.exc.SegmentationViolation(va) segm_end = segm[0] + s...
read up to MAX_BYTES_FEATURE_SIZE from the given address. raises: envi.SegmentationViolation: if the given address is not valid.
read_bytes
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def extract_insn_bytes_features(fh: FunctionHandle, bb, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]: """ parse byte sequence features from the given instruction. example: # push offset iid_004118d4_IShellLinkA ; riid """ insn: envi.Opcode = ih.inner f: viv_utils.Function ...
parse byte sequence features from the given instruction. example: # push offset iid_004118d4_IShellLinkA ; riid
extract_insn_bytes_features
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def is_security_cookie(f, bb, insn) -> bool: """ check if an instruction is related to security cookie checks """ # security cookie check should use SP or BP oper = insn.opers[1] if oper.isReg() and oper.reg not in [ envi.archs.i386.regs.REG_ESP, envi.archs.i386.regs.REG_EBP, ...
check if an instruction is related to security cookie checks
is_security_cookie
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def extract_insn_peb_access_characteristic_features(f, bb, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]: """ parse peb access from the given function. fs:[0x30] on x86, gs:[0x60] on x64 """ insn: envi.Opcode = ih.inner if insn.mnem not in ["push", "mov"]: return prefix = insn.g...
parse peb access from the given function. fs:[0x30] on x86, gs:[0x60] on x64
extract_insn_peb_access_characteristic_features
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def extract_insn_segment_access_features(f, bb, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]: """parse the instruction for access to fs or gs""" insn: envi.Opcode = ih.inner prefix = insn.getPrefixName() if prefix == "fs": yield Characteristic("fs access"), ih.address if prefix ==...
parse the instruction for access to fs or gs
extract_insn_segment_access_features
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def extract_insn_cross_section_cflow(fh: FunctionHandle, bb, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]: """ inspect the instruction for a CALL or JMP that crosses section boundaries. """ insn: envi.Opcode = ih.inner f: viv_utils.Function = fh.inner for va, flags in insn.getBranches()...
inspect the instruction for a CALL or JMP that crosses section boundaries.
extract_insn_cross_section_cflow
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def extract_function_indirect_call_characteristic_features(f, bb, ih: InsnHandle) -> Iterator[tuple[Feature, Address]]: """ extract indirect function call characteristic (e.g., call eax or call dword ptr [edx+4]) does not include calls like => call ds:dword_ABD4974 """ insn: envi.Opcode = ih.inner ...
extract indirect function call characteristic (e.g., call eax or call dword ptr [edx+4]) does not include calls like => call ds:dword_ABD4974
extract_function_indirect_call_characteristic_features
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def extract_op_number_features( fh: FunctionHandle, bb, ih: InsnHandle, i, oper: envi.Operand ) -> Iterator[tuple[Feature, Address]]: """parse number features from the given operand. example: push 3136B0h ; dwControlCode """ insn: envi.Opcode = ih.inner f: viv_utils.Function ...
parse number features from the given operand. example: push 3136B0h ; dwControlCode
extract_op_number_features
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def extract_op_offset_features( fh: FunctionHandle, bb, ih: InsnHandle, i, oper: envi.Operand ) -> Iterator[tuple[Feature, Address]]: """parse structure offset features from the given operand.""" # example: # # .text:0040112F cmp [esi+4], ebx insn: envi.Opcode = ih.inner f: viv_ut...
parse structure offset features from the given operand.
extract_op_offset_features
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def extract_op_string_features( fh: FunctionHandle, bb, ih: InsnHandle, i, oper: envi.Operand ) -> Iterator[tuple[Feature, Address]]: """parse string features from the given operand.""" # example: # # push offset aAcr ; "ACR > " insn: envi.Opcode = ih.inner f: viv_utils.Function ...
parse string features from the given operand.
extract_op_string_features
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def extract_features(f, bb, insn) -> Iterator[tuple[Feature, Address]]: """ extract features from the given insn. args: f (viv_utils.Function): the function from which to extract features bb (viv_utils.BasicBlock): the basic block to process. insn (vivisect...Instruction): the instruction...
extract features from the given insn. args: f (viv_utils.Function): the function from which to extract features bb (viv_utils.BasicBlock): the basic block to process. insn (vivisect...Instruction): the instruction to process. yields: tuple[Feature, Address]: the features and their...
extract_features
python
mandiant/capa
capa/features/extractors/viv/insn.py
https://github.com/mandiant/capa/blob/master/capa/features/extractors/viv/insn.py
Apache-2.0
def dumps_static(extractor: StaticFeatureExtractor) -> str: """ serialize the given extractor to a string """ global_features: list[GlobalFeature] = [] for feature, _ in extractor.extract_global_features(): global_features.append( GlobalFeature( feature=feature_fr...
serialize the given extractor to a string
dumps_static
python
mandiant/capa
capa/features/freeze/__init__.py
https://github.com/mandiant/capa/blob/master/capa/features/freeze/__init__.py
Apache-2.0
def loads_static(s: str) -> StaticFeatureExtractor: """deserialize a set of features (as a NullStaticFeatureExtractor) from a string.""" freeze = Freeze.model_validate_json(s) if freeze.version != CURRENT_VERSION: raise ValueError(f"unsupported freeze format version: {freeze.version}") assert f...
deserialize a set of features (as a NullStaticFeatureExtractor) from a string.
loads_static
python
mandiant/capa
capa/features/freeze/__init__.py
https://github.com/mandiant/capa/blob/master/capa/features/freeze/__init__.py
Apache-2.0
def loads_dynamic(s: str) -> DynamicFeatureExtractor: """deserialize a set of features (as a NullDynamicFeatureExtractor) from a string.""" freeze = Freeze.model_validate_json(s) if freeze.version != CURRENT_VERSION: raise ValueError(f"unsupported freeze format version: {freeze.version}") asser...
deserialize a set of features (as a NullDynamicFeatureExtractor) from a string.
loads_dynamic
python
mandiant/capa
capa/features/freeze/__init__.py
https://github.com/mandiant/capa/blob/master/capa/features/freeze/__init__.py
Apache-2.0
def dumps(extractor: FeatureExtractor) -> str: """serialize the given extractor to a string.""" if isinstance(extractor, StaticFeatureExtractor): doc = dumps_static(extractor) elif isinstance(extractor, DynamicFeatureExtractor): doc = dumps_dynamic(extractor) else: raise ValueErr...
serialize the given extractor to a string.
dumps
python
mandiant/capa
capa/features/freeze/__init__.py
https://github.com/mandiant/capa/blob/master/capa/features/freeze/__init__.py
Apache-2.0
def load(buf: bytes): """deserialize a set of features (as a NullFeatureExtractor) from a byte array.""" if not is_freeze(buf): raise ValueError("missing magic header") s = zlib.decompress(buf[len(MAGIC) :]).decode("utf-8") return loads(s)
deserialize a set of features (as a NullFeatureExtractor) from a byte array.
load
python
mandiant/capa
capa/features/freeze/__init__.py
https://github.com/mandiant/capa/blob/master/capa/features/freeze/__init__.py
Apache-2.0
def create_namespace(namespace_str): """create new Ghidra namespace for each capa namespace""" cmd = CreateNamespacesCmd(namespace_str, SourceType.USER_DEFINED) cmd.applyTo(currentProgram()) # type: ignore [name-defined] # noqa: F821 return cmd.getNamespace()
create new Ghidra namespace for each capa namespace
create_namespace
python
mandiant/capa
capa/ghidra/capa_explorer.py
https://github.com/mandiant/capa/blob/master/capa/ghidra/capa_explorer.py
Apache-2.0
def create_label(ghidra_addr, name, capa_namespace): """custom label cmd to overlay symbols under capa-generated namespaces""" # prevent duplicate labels under the same capa-generated namespace symbol_table = currentProgram().getSymbolTable() # type: ignore [name-defined] # noqa: F821 for sym in symbo...
custom label cmd to overlay symbols under capa-generated namespaces
create_label
python
mandiant/capa
capa/ghidra/capa_explorer.py
https://github.com/mandiant/capa/blob/master/capa/ghidra/capa_explorer.py
Apache-2.0
def set_plate_comment(self, ghidra_addr): """set plate comments at matched functions""" comment = getPlateComment(ghidra_addr) # type: ignore [name-defined] # noqa: F821 rule_path = self.namespace.replace(Namespace.DELIMITER, "/") # 2 calls to avoid duplicate comments via subsequent scr...
set plate comments at matched functions
set_plate_comment
python
mandiant/capa
capa/ghidra/capa_explorer.py
https://github.com/mandiant/capa/blob/master/capa/ghidra/capa_explorer.py
Apache-2.0
def set_pre_comment(self, ghidra_addr, sub_type, description): """set pre comments at subscoped matches of main rules""" comment = getPreComment(ghidra_addr) # type: ignore [name-defined] # noqa: F821 if comment is None: comment = "capa: " + sub_type + "(" + description + ")" + ' ma...
set pre comments at subscoped matches of main rules
set_pre_comment
python
mandiant/capa
capa/ghidra/capa_explorer.py
https://github.com/mandiant/capa/blob/master/capa/ghidra/capa_explorer.py
Apache-2.0