Update args.sample type to Path and str vs as_posix comparisons

This commit is contained in:
Aayush Goel
2023-07-09 16:02:28 +05:30
parent e0ed8c6e04
commit 673af45c55
13 changed files with 124 additions and 131 deletions
+2 -2
View File
@@ -170,7 +170,7 @@ def main(argv=None):
samples = []
for file in Path(args.input).rglob("*"):
samples.append(file.as_posix())
samples.append(file)
def pmap(f, args, parallelism=multiprocessing.cpu_count()):
"""apply the given function f to the given args using subprocesses"""
@@ -205,7 +205,7 @@ def main(argv=None):
if result["status"] == "error":
logger.warning(result["error"])
elif result["status"] == "ok":
results[result["path"]] = rd.ResultDocument.parse_obj(result["ok"]).json(exclude_none=True)
results[result["path"].as_posix()] = rd.ResultDocument.parse_obj(result["ok"]).json(exclude_none=True)
else:
raise ValueError(f"unexpected status: {result['status']}")
+2 -2
View File
@@ -161,7 +161,7 @@ def render_dictionary(doc: rd.ResultDocument) -> Dict[str, Any]:
# ==== render dictionary helpers
def capa_details(rules_path, file_path, output_format="dictionary"):
def capa_details(rules_path: Path, file_path: Path, output_format="dictionary"):
# load rules from disk
rules = capa.main.get_rules([rules_path])
@@ -210,5 +210,5 @@ if __name__ == "__main__":
args = parser.parse_args()
if args.rules != RULES_PATH:
args.rules = Path(args.rules)
print(capa_details(args.rules, args.file, args.output))
print(capa_details(args.rules, Path(args.file), args.output))
sys.exit(0)
+3 -3
View File
@@ -51,13 +51,13 @@ def load_analysis(bv):
binaryninja.log_info(f"dirname: {dirname}\nshortname: {shortname}\n")
js_path = path = dirname / (shortname + ".js")
json_path = dirname / (shortname + ".json")
if os.access(js_path.as_posix(), os.R_OK):
if os.access(str(js_path), os.R_OK):
path = js_path
elif os.access(json_path.as_posix(), os.R_OK):
elif os.access(str(json_path), os.R_OK):
path = json_path
else:
path = binaryninja.interaction.get_open_filename_input("capa report:", "JSON (*.js *.json);;All Files (*)")
if not path or not os.access(path.as_posix(), os.R_OK):
if not path or not os.access(str(path), os.R_OK):
binaryninja.log_error("Invalid filename.")
return 0
binaryninja.log_info(f"Using capa file {path}")
+10 -10
View File
@@ -296,14 +296,14 @@ DEFAULT_SIGNATURES = capa.main.get_default_signatures()
def get_sample_capabilities(ctx: Context, path: Path) -> Set[str]:
nice_path = path.resolve().absolute().as_posix()
nice_path = path.resolve().absolute()
if path in ctx.capabilities_by_sample:
logger.debug("found cached results: %s: %d capabilities", nice_path, len(ctx.capabilities_by_sample[path]))
return ctx.capabilities_by_sample[path]
if nice_path.endswith(capa.helpers.EXTENSIONS_SHELLCODE_32):
if nice_path.name.endswith(capa.helpers.EXTENSIONS_SHELLCODE_32):
format_ = "sc32"
elif nice_path.endswith(capa.helpers.EXTENSIONS_SHELLCODE_64):
elif nice_path.name.endswith(capa.helpers.EXTENSIONS_SHELLCODE_64):
format_ = "sc64"
else:
format_ = capa.main.get_auto_format(nice_path)
@@ -356,7 +356,7 @@ class DoesntMatchExample(Lint):
try:
capabilities = get_sample_capabilities(ctx, path)
except Exception as e:
logger.error("failed to extract capabilities: %s %s %s", rule.name, str(path), e, exc_info=True)
logger.error("failed to extract capabilities: %s %s %s", rule.name, path, e, exc_info=True)
return True
if rule.name not in capabilities:
@@ -917,12 +917,12 @@ def main(argv=None):
if argv is None:
argv = sys.argv[1:]
samples_path = (Path(__file__).resolve().parent.parent / "tests" / "data").as_posix()
default_samples_path = str(Path(__file__).resolve().parent.parent / "tests" / "data")
parser = argparse.ArgumentParser(description="Lint capa rules.")
capa.main.install_common_args(parser, wanted={"tag"})
parser.add_argument("rules", type=str, action="append", help="Path to rules")
parser.add_argument("--samples", type=str, default=samples_path, help="Path to samples")
parser.add_argument("--samples", type=str, default=default_samples_path, help="Path to samples")
parser.add_argument(
"--thorough",
action="store_true",
@@ -953,12 +953,12 @@ def main(argv=None):
return -1
logger.info("collecting potentially referenced samples")
samplePath = Path(args.samples)
if not samplePath.exists():
logger.error("samples path %s does not exist", samplePath)
samples_path = Path(args.samples)
if not samples_path.exists():
logger.error("samples path %s does not exist", Path(samples_path))
return -1
samples = collect_samples(samplePath)
samples = collect_samples(Path(samples_path))
ctx = Context(samples=samples, rules=rules, is_thorough=args.thorough)
+1 -1
View File
@@ -187,7 +187,7 @@ if __name__ == "__main__":
"--output",
"-o",
type=str,
default=(Path(__file__).resolve().parent / "linter-data.json").as_posix(),
default=str(Path(__file__).resolve().parent / "linter-data.json"),
help="Path to output file (lint.py will be looking for linter-data.json)",
)
main(parser.parse_args(args=argv[1:]))