From 17aad56800f0da671091a471663428c4622aaaa3 Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Sun, 6 Aug 2023 22:53:50 +0530 Subject: [PATCH 01/11] Script to get unused features Used show_features.py script --- capa/engine.py | 16 ++ scripts/detect_duplicate_features.py | 42 ++--- scripts/show-unused-features.py | 223 +++++++++++++++++++++++++++ 3 files changed, 252 insertions(+), 29 deletions(-) create mode 100644 scripts/show-unused-features.py diff --git a/capa/engine.py b/capa/engine.py index 8ae36d3ea..ba1993647 100644 --- a/capa/engine.py +++ b/capa/engine.py @@ -88,6 +88,22 @@ def replace_child(self, existing, new): if child is existing: children[i] = new + def get_all_features(self) -> Set[Feature]: + """ + recursively extracts all feature statements from a given rule statement. + + returns: + set: A set of all feature statements contained within the given feature statement. + """ + feature_set: set = set() + + for child in self.get_children(): + if isinstance(child, Statement): + feature_set.update(child.get_all_features()) + else: + feature_set.add(child) + return feature_set + class And(Statement): """ diff --git a/scripts/detect_duplicate_features.py b/scripts/detect_duplicate_features.py index dd9b98384..e48e2ade4 100644 --- a/scripts/detect_duplicate_features.py +++ b/scripts/detect_duplicate_features.py @@ -8,38 +8,18 @@ import sys import logging import argparse +from typing import Set from pathlib import Path import capa.main import capa.rules import capa.engine as ceng +from capa.features.common import Feature logger = logging.getLogger("detect_duplicate_features") -def get_child_features(feature: ceng.Statement) -> list: - """ - Recursively extracts all feature statements from a given rule statement. - - Args: - feature (capa.engine.Statement): The feature statement to extract features from. - - Returns: - list: A list of all feature statements contained within the given feature statement. - """ - children = [] - - if isinstance(feature, (ceng.And, ceng.Or, ceng.Some)): - for child in feature.children: - children.extend(get_child_features(child)) - elif isinstance(feature, (ceng.Subscope, ceng.Range, ceng.Not)): - children.extend(get_child_features(feature.child)) - else: - children.append(feature) - return children - - -def get_features(rule_path: str) -> list: +def get_features(rule_path: str) -> Set[Feature]: """ Extracts all features from a given rule file. @@ -47,17 +27,18 @@ def get_features(rule_path: str) -> list: rule_path (str): The path to the rule file to extract features from. Returns: - list: A list of all feature statements contained within the rule file. + set: A set of all feature statements contained within the rule file. """ - feature_list = [] with Path(rule_path).open("r", encoding="utf-8") as f: try: new_rule = capa.rules.Rule.from_yaml(f.read()) - feature_list = get_child_features(new_rule.statement) + if isinstance(new_rule.statement, ceng.Statement): + return new_rule.statement.get_all_features() + else: + return (new_rule.statement,) except Exception as e: logger.error("Error: New rule %s %s %s", rule_path, str(type(e)), str(e)) sys.exit(-1) - return feature_list def find_overlapping_rules(new_rule_path, rules_path): @@ -67,7 +48,6 @@ def find_overlapping_rules(new_rule_path, rules_path): # Loads features of new rule in a list. new_rule_features = get_features(new_rule_path) - count = 0 overlapping_rules = [] @@ -75,7 +55,11 @@ def find_overlapping_rules(new_rule_path, rules_path): ruleset = capa.main.get_rules(rules_path) for rule_name, rule in ruleset.rules.items(): - rule_features = get_child_features(rule.statement) + rule_features = set() + if isinstance(rule.statement, ceng.Statement): + rule_features = rule.statement.get_all_features() + else: + rule_features.add(rule.statement) if not len(rule_features): continue diff --git a/scripts/show-unused-features.py b/scripts/show-unused-features.py new file mode 100644 index 000000000..56f00c6a8 --- /dev/null +++ b/scripts/show-unused-features.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python2 +""" +Copyright (C) 2023 Mandiant, Inc. All Rights Reserved. +Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. +You may obtain a copy of the License at: [package root]/LICENSE.txt +Unless required by applicable law or agreed to in writing, software distributed under the License + is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and limitations under the License. +""" +import os +import sys +import logging +import argparse +from typing import Set, Tuple +from pathlib import Path + +import tabulate +from termcolor import colored + +import capa.main +import capa.rules +import capa.engine as ceng +import capa.helpers +import capa.features +import capa.exceptions +import capa.render.verbose as v +import capa.features.freeze +import capa.features.address +import capa.features.extractors.pefile +import capa.features.extractors.base_extractor +from capa.helpers import log_unsupported_runtime_error +from capa.features.common import Feature +from capa.features.extractors.base_extractor import FunctionHandle + +logger = logging.getLogger("capa.show-features") + + +def format_address(addr: capa.features.address.Address) -> str: + return v.format_address(capa.features.freeze.Address.from_capa((addr))) + + +def get_rules_feature_set(rules_path) -> Set[Feature]: + ruleset = capa.main.get_rules(rules_path) + rules_feature_set = set() + for _, rule in ruleset.rules.items(): + rule_features: set = set() + if isinstance(rule.statement, ceng.Statement): + rule_features.update(rule.statement.get_all_features()) + else: + rule_features.add(rule.statement) + + rules_feature_set.update(rule_features) + return rules_feature_set + + +def get_file_features(functions, extractor: capa.features.extractors.base_extractor.FeatureExtractor): + feature_map: dict = {} + + for f in functions: + if extractor.is_library_function(f.address): + function_name = extractor.get_function_name(f.address) + logger.debug("skipping library function %s (%s)", format_address(f.address), function_name) + continue + + for feature, _ in extractor.extract_function_features(f): + if capa.features.common.is_global_feature(feature): + continue + feature_map[feature] = feature_map.get(feature, 0) + 1 + + for bb in extractor.get_basic_blocks(f): + for feature, _ in extractor.extract_basic_block_features(f, bb): + if capa.features.common.is_global_feature(feature): + continue + feature_map[feature] = feature_map.get(feature, 0) + 1 + + for insn in extractor.get_instructions(f, bb): + for feature, _ in extractor.extract_insn_features(f, bb, insn): + if capa.features.common.is_global_feature(feature): + continue + feature_map[feature] = feature_map.get(feature, 0) + 1 + return feature_map + + +def main(argv=None): + if argv is None: + argv = sys.argv[1:] + + parser = argparse.ArgumentParser(description="Show the features that capa extracts from the given sample") + capa.main.install_common_args(parser, wanted={"format", "os", "sample", "signatures", "backend", "rules"}) + + parser.add_argument("-F", "--function", type=str, help="Show features for specific function") + args = parser.parse_args(args=argv) + capa.main.handle_common_args(args) + + if args.function and args.backend == "pefile": + print("pefile backend does not support extracting function features") + return -1 + + try: + taste = capa.helpers.get_file_taste(Path(args.sample)) + except IOError as e: + logger.error("%s", str(e)) + return -1 + + try: + sig_paths = capa.main.get_signatures(args.signatures) + except IOError as e: + logger.error("%s", str(e)) + return -1 + + if (args.format == "freeze") or ( + args.format == capa.features.common.FORMAT_AUTO and capa.features.freeze.is_freeze(taste) + ): + extractor = capa.features.freeze.load(Path(args.sample).read_bytes()) + else: + should_save_workspace = os.environ.get("CAPA_SAVE_WORKSPACE") not in ("0", "no", "NO", "n", None) + try: + extractor = capa.main.get_extractor( + args.sample, args.format, args.os, args.backend, sig_paths, should_save_workspace + ) + except capa.exceptions.UnsupportedFormatError: + capa.helpers.log_unsupported_format_error() + return -1 + except capa.exceptions.UnsupportedRuntimeError: + log_unsupported_runtime_error() + return -1 + + feature_map: dict = {} + + for feature, _ in extractor.extract_global_features(): + feature_map[feature] = feature_map.get(feature, 0) + 1 + + function_handles: Tuple[FunctionHandle, ...] + if isinstance(extractor, capa.features.extractors.pefile.PefileFeatureExtractor): + # pefile extractor doesn't extract function features + function_handles = () + else: + function_handles = tuple(extractor.get_functions()) + + if args.function: + if args.format == "freeze": + function_handles = tuple(filter(lambda fh: fh.address == args.function, function_handles)) + else: + function_handles = tuple(filter(lambda fh: format_address(fh.address) == args.function, function_handles)) + + if args.function not in [format_address(fh.address) for fh in function_handles]: + print(f"{args.function} not a function") + return -1 + + if len(function_handles) == 0: + print(f"{args.function} not a function") + return -1 + + feature_map.update(get_file_features(function_handles, extractor)) + + rules_feature_set = get_rules_feature_set(args.rules) + + highlight_unused_features(feature_map, rules_feature_set) + return 0 + + +def ida_main(): + import idc + + import capa.main + import capa.features.extractors.ida.extractor + + function = idc.get_func_attr(idc.here(), idc.FUNCATTR_START) + print(f"getting features for current function {hex(function)}") + + extractor = capa.features.extractors.ida.extractor.IdaFeatureExtractor() + feature_map: dict = {} + + if not function: + for feature, _ in extractor.extract_file_features(): + feature_map[feature] = feature_map.get(feature, 0) + 1 + return + + function_handles = tuple(extractor.get_functions()) + + if function: + function_handles = tuple(filter(lambda fh: fh.inner.start_ea == function, function_handles)) + + if len(function_handles) == 0: + print(f"{hex(function)} not a function") + return -1 + + feature_map.update(get_file_features(function_handles, extractor)) + + rules_path = capa.main.get_default_root() / "rules" + rules_feature_set = get_rules_feature_set([rules_path]) + + highlight_unused_features(feature_map, rules_feature_set) + + return 0 + + +def highlight_unused_features(feature_map: dict, rules_feature_set: set): + unused_features = [] + for feature, count in feature_map.items(): + if feature in rules_feature_set: + continue + unused_features.append((get_colored(str(count)), get_colored(feature.__str__()))) + print("\n") + print(tabulate.tabulate(unused_features, headers=["Count", "Feature"], tablefmt="plain")) + print("\n") + + +def get_colored(s: str): + if "(" in s: + s_split = s.split("(") + s_split[0] = colored(s_split[0], "cyan") + return "(".join(s_split) + else: + return colored(s, "cyan") + + +if __name__ == "__main__": + if capa.helpers.is_runtime_ida(): + ida_main() + else: + sys.exit(main()) From a2254852b02e68f853d908269895fc06bbc9dc76 Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Sun, 6 Aug 2023 22:55:54 +0530 Subject: [PATCH 02/11] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f285d59e8..0e7a99b3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### New Features - ELF: implement file import and export name extractor #1607 @Aayush-Goel-04 +- develop script to highlight the features that are not used during matching #331 @Aayush-Goel-04 ### Breaking Changes From 0fdc1dd3f595ef1e1218226bd81a1d3937a57e70 Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Mon, 7 Aug 2023 21:00:29 +0530 Subject: [PATCH 03/11] Type Hints done , get_all_feature to Rule class --- capa/engine.py | 16 ------- capa/rules/__init__.py | 27 ++++++++++++ scripts/detect_duplicate_features.py | 12 +----- scripts/show-unused-features.py | 62 ++++++++++++++-------------- 4 files changed, 59 insertions(+), 58 deletions(-) diff --git a/capa/engine.py b/capa/engine.py index ba1993647..8ae36d3ea 100644 --- a/capa/engine.py +++ b/capa/engine.py @@ -88,22 +88,6 @@ def replace_child(self, existing, new): if child is existing: children[i] = new - def get_all_features(self) -> Set[Feature]: - """ - recursively extracts all feature statements from a given rule statement. - - returns: - set: A set of all feature statements contained within the given feature statement. - """ - feature_set: set = set() - - for child in self.get_children(): - if isinstance(child, Statement): - feature_set.update(child.get_all_features()) - else: - feature_set.add(child) - return feature_set - class And(Statement): """ diff --git a/capa/rules/__init__.py b/capa/rules/__init__.py index 45d822a56..2fe7ea500 100644 --- a/capa/rules/__init__.py +++ b/capa/rules/__init__.py @@ -738,6 +738,33 @@ def extract_subscope_rules(self): yield from self._extract_subscope_rules_rec(self.statement) + def extract_all_features_rec(self, statement) -> Set[Feature]: + """ + recursively extracts all feature statements from a given rule statement. + + returns: + set: A set of all feature statements contained within the given feature statement. + """ + feature_set: Set[Feature] = set() + + for child in statement.get_children(): + if isinstance(child, Statement): + feature_set.update(self.extract_all_features_rec(child)) + else: + feature_set.add(child) + return feature_set + + def extract_all_features(self) -> Set[Feature]: + if not isinstance(self.statement, ceng.Statement): + # For rules with single feature like + # anti-analysis\obfuscation\obfuscated-with-advobfuscator.yml + # contains a single feature - substring , which is of type String + return { + self.statement, + } + + return self.extract_all_features_rec(self.statement) + def evaluate(self, features: FeatureSet, short_circuit=True): capa.perf.counters["evaluate.feature"] += 1 capa.perf.counters["evaluate.feature.rule"] += 1 diff --git a/scripts/detect_duplicate_features.py b/scripts/detect_duplicate_features.py index e48e2ade4..6737d7fa9 100644 --- a/scripts/detect_duplicate_features.py +++ b/scripts/detect_duplicate_features.py @@ -13,7 +13,6 @@ import capa.main import capa.rules -import capa.engine as ceng from capa.features.common import Feature logger = logging.getLogger("detect_duplicate_features") @@ -32,10 +31,7 @@ def get_features(rule_path: str) -> Set[Feature]: with Path(rule_path).open("r", encoding="utf-8") as f: try: new_rule = capa.rules.Rule.from_yaml(f.read()) - if isinstance(new_rule.statement, ceng.Statement): - return new_rule.statement.get_all_features() - else: - return (new_rule.statement,) + return new_rule.extract_all_features() except Exception as e: logger.error("Error: New rule %s %s %s", rule_path, str(type(e)), str(e)) sys.exit(-1) @@ -55,11 +51,7 @@ def find_overlapping_rules(new_rule_path, rules_path): ruleset = capa.main.get_rules(rules_path) for rule_name, rule in ruleset.rules.items(): - rule_features = set() - if isinstance(rule.statement, ceng.Statement): - rule_features = rule.statement.get_all_features() - else: - rule_features.add(rule.statement) + rule_features = rule.extract_all_features() if not len(rule_features): continue diff --git a/scripts/show-unused-features.py b/scripts/show-unused-features.py index 56f00c6a8..c3020d571 100644 --- a/scripts/show-unused-features.py +++ b/scripts/show-unused-features.py @@ -12,7 +12,7 @@ import sys import logging import argparse -from typing import Set, Tuple +from typing import Set, Dict, Tuple from pathlib import Path import tabulate @@ -20,11 +20,11 @@ import capa.main import capa.rules -import capa.engine as ceng import capa.helpers import capa.features import capa.exceptions import capa.render.verbose as v +import capa.features.common import capa.features.freeze import capa.features.address import capa.features.extractors.pefile @@ -42,20 +42,17 @@ def format_address(addr: capa.features.address.Address) -> str: def get_rules_feature_set(rules_path) -> Set[Feature]: ruleset = capa.main.get_rules(rules_path) - rules_feature_set = set() + rules_feature_set: Set[Feature] = set() for _, rule in ruleset.rules.items(): - rule_features: set = set() - if isinstance(rule.statement, ceng.Statement): - rule_features.update(rule.statement.get_all_features()) - else: - rule_features.add(rule.statement) + rules_feature_set.update(rule.extract_all_features()) - rules_feature_set.update(rule_features) return rules_feature_set -def get_file_features(functions, extractor: capa.features.extractors.base_extractor.FeatureExtractor): - feature_map: dict = {} +def get_file_features( + functions: Tuple[FunctionHandle, ...], extractor: capa.features.extractors.base_extractor.FeatureExtractor +) -> Dict[Feature, int]: + feature_map: Dict[Feature, int] = {} for f in functions: if extractor.is_library_function(f.address): @@ -82,11 +79,32 @@ def get_file_features(functions, extractor: capa.features.extractors.base_extrac return feature_map +def get_colored(s: str): + if "(" in s and ")" in s: + s_split = s.split("(", 1) + s_color = colored(s_split[1][:-1], "cyan") + return f"{s_split[0]}({s_color})" + else: + return colored(s, "cyan") + + +def highlight_unused_features(feature_map: Dict[Feature, int], rules_feature_set: Set[Feature]): + unused_features = [] + for feature, count in feature_map.items(): + if feature in rules_feature_set: + continue + unused_features.append((get_colored(str(count)), get_colored(str(feature)))) + unused_features = sorted(unused_features, key=lambda x: x[0]) + print("\n") + print(tabulate.tabulate(unused_features, headers=["Count", "Feature"], tablefmt="plain")) + print("\n") + + def main(argv=None): if argv is None: argv = sys.argv[1:] - parser = argparse.ArgumentParser(description="Show the features that capa extracts from the given sample") + parser = argparse.ArgumentParser(description="Show the features that capa doesn't have rules for yet") capa.main.install_common_args(parser, wanted={"format", "os", "sample", "signatures", "backend", "rules"}) parser.add_argument("-F", "--function", type=str, help="Show features for specific function") @@ -196,26 +214,6 @@ def ida_main(): return 0 -def highlight_unused_features(feature_map: dict, rules_feature_set: set): - unused_features = [] - for feature, count in feature_map.items(): - if feature in rules_feature_set: - continue - unused_features.append((get_colored(str(count)), get_colored(feature.__str__()))) - print("\n") - print(tabulate.tabulate(unused_features, headers=["Count", "Feature"], tablefmt="plain")) - print("\n") - - -def get_colored(s: str): - if "(" in s: - s_split = s.split("(") - s_split[0] = colored(s_split[0], "cyan") - return "(".join(s_split) - else: - return colored(s, "cyan") - - if __name__ == "__main__": if capa.helpers.is_runtime_ida(): ida_main() From 232c9ce35c29911e30883bf939ce7869798254ee Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Mon, 7 Aug 2023 22:43:25 +0530 Subject: [PATCH 04/11] Add test for script & output rendered --- scripts/show-unused-features.py | 6 ++++-- tests/test_scripts.py | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/scripts/show-unused-features.py b/scripts/show-unused-features.py index c3020d571..1a84f5bb9 100644 --- a/scripts/show-unused-features.py +++ b/scripts/show-unused-features.py @@ -93,8 +93,10 @@ def highlight_unused_features(feature_map: Dict[Feature, int], rules_feature_set for feature, count in feature_map.items(): if feature in rules_feature_set: continue - unused_features.append((get_colored(str(count)), get_colored(str(feature)))) - unused_features = sorted(unused_features, key=lambda x: x[0]) + unused_features.append((count, get_colored(str(feature)))) + unused_features = [ + (get_colored(str(count)), feature) for count, feature in sorted(unused_features, key=lambda x: x[0]) + ] print("\n") print(tabulate.tabulate(unused_features, headers=["Count", "Feature"], tablefmt="plain")) print("\n") diff --git a/tests/test_scripts.py b/tests/test_scripts.py index 4baa96a97..7c91bc573 100644 --- a/tests/test_scripts.py +++ b/tests/test_scripts.py @@ -45,6 +45,7 @@ def get_rule_path(): pytest.param("show-capabilities-by-function.py", [get_file_path()]), pytest.param("show-features.py", [get_file_path()]), pytest.param("show-features.py", ["-F", "0x407970", get_file_path()]), + pytest.param("show-unused-features.py", [get_file_path()]), pytest.param("capa_as_library.py", [get_file_path()]), ], ) From fb3ae0267e176d623278c3fdc5dd962fa194fd3b Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Tue, 8 Aug 2023 17:04:23 +0530 Subject: [PATCH 05/11] Update scripts/show-unused-features.py Co-authored-by: Moritz --- scripts/show-unused-features.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/show-unused-features.py b/scripts/show-unused-features.py index 1a84f5bb9..f1c3b9ec4 100644 --- a/scripts/show-unused-features.py +++ b/scripts/show-unused-features.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python3 """ Copyright (C) 2023 Mandiant, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); From 9c1aa2fc5d7043f210bdbeba0f7ba2925a1a6d18 Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Tue, 8 Aug 2023 18:35:04 +0530 Subject: [PATCH 06/11] Update show-unused-features.py --- scripts/show-unused-features.py | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/scripts/show-unused-features.py b/scripts/show-unused-features.py index f1c3b9ec4..8b42cf430 100644 --- a/scripts/show-unused-features.py +++ b/scripts/show-unused-features.py @@ -12,8 +12,9 @@ import sys import logging import argparse -from typing import Set, Dict, Tuple +from typing import Set, Tuple from pathlib import Path +from collections import Counter import tabulate from termcolor import colored @@ -33,7 +34,7 @@ from capa.features.common import Feature from capa.features.extractors.base_extractor import FunctionHandle -logger = logging.getLogger("capa.show-features") +logger = logging.getLogger("show-unused-feature") def format_address(addr: capa.features.address.Address) -> str: @@ -51,8 +52,8 @@ def get_rules_feature_set(rules_path) -> Set[Feature]: def get_file_features( functions: Tuple[FunctionHandle, ...], extractor: capa.features.extractors.base_extractor.FeatureExtractor -) -> Dict[Feature, int]: - feature_map: Dict[Feature, int] = {} +) -> Counter[Feature]: + feature_map: Counter[Feature] = Counter() for f in functions: if extractor.is_library_function(f.address): @@ -63,19 +64,19 @@ def get_file_features( for feature, _ in extractor.extract_function_features(f): if capa.features.common.is_global_feature(feature): continue - feature_map[feature] = feature_map.get(feature, 0) + 1 + feature_map.update([feature]) for bb in extractor.get_basic_blocks(f): for feature, _ in extractor.extract_basic_block_features(f, bb): if capa.features.common.is_global_feature(feature): continue - feature_map[feature] = feature_map.get(feature, 0) + 1 + feature_map.update([feature]) for insn in extractor.get_instructions(f, bb): for feature, _ in extractor.extract_insn_features(f, bb, insn): if capa.features.common.is_global_feature(feature): continue - feature_map[feature] = feature_map.get(feature, 0) + 1 + feature_map.update([feature]) return feature_map @@ -88,7 +89,7 @@ def get_colored(s: str): return colored(s, "cyan") -def highlight_unused_features(feature_map: Dict[Feature, int], rules_feature_set: Set[Feature]): +def print_unused_features(feature_map: Counter[Feature], rules_feature_set: Set[Feature]): unused_features = [] for feature, count in feature_map.items(): if feature in rules_feature_set: @@ -146,10 +147,9 @@ def main(argv=None): log_unsupported_runtime_error() return -1 - feature_map: dict = {} + feature_map: Counter[Feature] = Counter() - for feature, _ in extractor.extract_global_features(): - feature_map[feature] = feature_map.get(feature, 0) + 1 + feature_map.update([feature for feature, _ in extractor.extract_global_features()]) function_handles: Tuple[FunctionHandle, ...] if isinstance(extractor, capa.features.extractors.pefile.PefileFeatureExtractor): @@ -176,7 +176,7 @@ def main(argv=None): rules_feature_set = get_rules_feature_set(args.rules) - highlight_unused_features(feature_map, rules_feature_set) + print_unused_features(feature_map, rules_feature_set) return 0 @@ -190,12 +190,9 @@ def ida_main(): print(f"getting features for current function {hex(function)}") extractor = capa.features.extractors.ida.extractor.IdaFeatureExtractor() - feature_map: dict = {} + feature_map: Counter[Feature] = Counter() - if not function: - for feature, _ in extractor.extract_file_features(): - feature_map[feature] = feature_map.get(feature, 0) + 1 - return + feature_map.update([feature for feature, _ in extractor.extract_file_features()]) function_handles = tuple(extractor.get_functions()) @@ -211,7 +208,7 @@ def ida_main(): rules_path = capa.main.get_default_root() / "rules" rules_feature_set = get_rules_feature_set([rules_path]) - highlight_unused_features(feature_map, rules_feature_set) + print_unused_features(feature_map, rules_feature_set) return 0 From c497ad82536ea879623483cbbef38fe018a4620e Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Tue, 8 Aug 2023 18:36:25 +0530 Subject: [PATCH 07/11] Update show-unused-features.py --- scripts/show-unused-features.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/show-unused-features.py b/scripts/show-unused-features.py index 8b42cf430..dde77b4cd 100644 --- a/scripts/show-unused-features.py +++ b/scripts/show-unused-features.py @@ -34,7 +34,7 @@ from capa.features.common import Feature from capa.features.extractors.base_extractor import FunctionHandle -logger = logging.getLogger("show-unused-feature") +logger = logging.getLogger("show-unused-features") def format_address(addr: capa.features.address.Address) -> str: From d81f3a461e6e5ba4e13d1a49f1250cd3979bad06 Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Wed, 9 Aug 2023 14:20:53 +0530 Subject: [PATCH 08/11] Update show-unused-features.py --- scripts/show-unused-features.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/scripts/show-unused-features.py b/scripts/show-unused-features.py index dde77b4cd..dc5ce72a7 100644 --- a/scripts/show-unused-features.py +++ b/scripts/show-unused-features.py @@ -10,6 +10,7 @@ """ import os import sys +import typing import logging import argparse from typing import Set, Tuple @@ -52,8 +53,8 @@ def get_rules_feature_set(rules_path) -> Set[Feature]: def get_file_features( functions: Tuple[FunctionHandle, ...], extractor: capa.features.extractors.base_extractor.FeatureExtractor -) -> Counter[Feature]: - feature_map: Counter[Feature] = Counter() +) -> typing.Counter[Feature]: + feature_map: typing.Counter[Feature] = Counter() for f in functions: if extractor.is_library_function(f.address): @@ -89,7 +90,7 @@ def get_colored(s: str): return colored(s, "cyan") -def print_unused_features(feature_map: Counter[Feature], rules_feature_set: Set[Feature]): +def print_unused_features(feature_map: typing.Counter[Feature], rules_feature_set: Set[Feature]): unused_features = [] for feature, count in feature_map.items(): if feature in rules_feature_set: @@ -147,7 +148,7 @@ def main(argv=None): log_unsupported_runtime_error() return -1 - feature_map: Counter[Feature] = Counter() + feature_map: typing.Counter[Feature] = Counter() feature_map.update([feature for feature, _ in extractor.extract_global_features()]) @@ -190,7 +191,7 @@ def ida_main(): print(f"getting features for current function {hex(function)}") extractor = capa.features.extractors.ida.extractor.IdaFeatureExtractor() - feature_map: Counter[Feature] = Counter() + feature_map: typing.Counter[Feature] = Counter() feature_map.update([feature for feature, _ in extractor.extract_file_features()]) From df9828dd7fe74275d0512d42f487dc39df375ec9 Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Wed, 9 Aug 2023 15:32:12 +0530 Subject: [PATCH 09/11] Update capa/rules/__init__.py Co-authored-by: Willi Ballenthin --- capa/rules/__init__.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/capa/rules/__init__.py b/capa/rules/__init__.py index 2fe7ea500..688b1733a 100644 --- a/capa/rules/__init__.py +++ b/capa/rules/__init__.py @@ -738,23 +738,23 @@ def extract_subscope_rules(self): yield from self._extract_subscope_rules_rec(self.statement) - def extract_all_features_rec(self, statement) -> Set[Feature]: - """ - recursively extracts all feature statements from a given rule statement. - - returns: - set: A set of all feature statements contained within the given feature statement. - """ + def _extract_all_features_rec(self, statement) -> Set[Feature]: feature_set: Set[Feature] = set() for child in statement.get_children(): if isinstance(child, Statement): - feature_set.update(self.extract_all_features_rec(child)) + feature_set.update(self._extract_all_features_rec(child)) else: feature_set.add(child) return feature_set def extract_all_features(self) -> Set[Feature]: + """ + recursively extracts all feature statements in this rule. + + returns: + set: A set of all feature statements contained within this rule. + """ if not isinstance(self.statement, ceng.Statement): # For rules with single feature like # anti-analysis\obfuscation\obfuscated-with-advobfuscator.yml @@ -763,7 +763,7 @@ def extract_all_features(self) -> Set[Feature]: self.statement, } - return self.extract_all_features_rec(self.statement) + return self._extract_all_features_rec(self.statement) def evaluate(self, features: FeatureSet, short_circuit=True): capa.perf.counters["evaluate.feature"] += 1 From 57486733e795f08fe4444a64664b0b45e519193b Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Wed, 9 Aug 2023 15:33:03 +0530 Subject: [PATCH 10/11] Update scripts/show-unused-features.py Co-authored-by: Willi Ballenthin --- scripts/show-unused-features.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/show-unused-features.py b/scripts/show-unused-features.py index dc5ce72a7..d8b32d397 100644 --- a/scripts/show-unused-features.py +++ b/scripts/show-unused-features.py @@ -97,7 +97,7 @@ def print_unused_features(feature_map: typing.Counter[Feature], rules_feature_se continue unused_features.append((count, get_colored(str(feature)))) unused_features = [ - (get_colored(str(count)), feature) for count, feature in sorted(unused_features, key=lambda x: x[0]) + (str(count), feature) for count, feature in sorted(unused_features, key=lambda x: x[0]) ] print("\n") print(tabulate.tabulate(unused_features, headers=["Count", "Feature"], tablefmt="plain")) From a383022cffca6669710789dd5e72ed49d650a9de Mon Sep 17 00:00:00 2001 From: Aayush Goel <81844215+Aayush-Goel-04@users.noreply.github.com> Date: Wed, 9 Aug 2023 15:37:38 +0530 Subject: [PATCH 11/11] Update show-unused-features.py --- scripts/show-unused-features.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/scripts/show-unused-features.py b/scripts/show-unused-features.py index d8b32d397..dbd6c8c89 100644 --- a/scripts/show-unused-features.py +++ b/scripts/show-unused-features.py @@ -92,13 +92,10 @@ def get_colored(s: str): def print_unused_features(feature_map: typing.Counter[Feature], rules_feature_set: Set[Feature]): unused_features = [] - for feature, count in feature_map.items(): + for feature, count in reversed(feature_map.most_common()): if feature in rules_feature_set: continue - unused_features.append((count, get_colored(str(feature)))) - unused_features = [ - (str(count), feature) for count, feature in sorted(unused_features, key=lambda x: x[0]) - ] + unused_features.append((str(count), get_colored(str(feature)))) print("\n") print(tabulate.tabulate(unused_features, headers=["Count", "Feature"], tablefmt="plain")) print("\n")