blint 3.0.1__tar.gz → 3.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. {blint-3.0.1 → blint-3.0.2}/PKG-INFO +1 -1
  2. {blint-3.0.1 → blint-3.0.2}/blint/cli.py +3 -1
  3. {blint-3.0.1 → blint-3.0.2}/blint/config.py +71 -2
  4. {blint-3.0.1 → blint-3.0.2}/blint/lib/binary.py +56 -40
  5. {blint-3.0.1 → blint-3.0.2}/blint/lib/disassembler.py +359 -169
  6. {blint-3.0.1 → blint-3.0.2}/blint/lib/utils.py +4 -0
  7. {blint-3.0.1 → blint-3.0.2}/pyproject.toml +1 -1
  8. {blint-3.0.1 → blint-3.0.2}/LICENSE +0 -0
  9. {blint-3.0.1 → blint-3.0.2}/README.md +0 -0
  10. {blint-3.0.1 → blint-3.0.2}/blint/__init__.py +0 -0
  11. {blint-3.0.1 → blint-3.0.2}/blint/cyclonedx/README.md +0 -0
  12. {blint-3.0.1 → blint-3.0.2}/blint/cyclonedx/__init__.py +0 -0
  13. {blint-3.0.1 → blint-3.0.2}/blint/cyclonedx/spdx.py +0 -0
  14. {blint-3.0.1 → blint-3.0.2}/blint/cyclonedx/spec.py +0 -0
  15. {blint-3.0.1 → blint-3.0.2}/blint/data/__init__.py +0 -0
  16. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/__init__.py +0 -0
  17. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_entries_generic.yml +0 -0
  18. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_entries_pe.yml +0 -0
  19. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_exe_go.yml +0 -0
  20. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_functions_generic.yml +0 -0
  21. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_imports_pe.yml +0 -0
  22. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_methods_generic.yml +0 -0
  23. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_methods_mips.yml +0 -0
  24. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_monero_generic.yml +0 -0
  25. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_monero_go.yml +0 -0
  26. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_monero_rust.yml +0 -0
  27. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_rootkits_win.yml +0 -0
  28. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_symbols_antiforensic.yml +0 -0
  29. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_symbols_generic.yml +0 -0
  30. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_symbols_hooka.yml +0 -0
  31. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_symbols_macho.yml +0 -0
  32. {blint-3.0.1 → blint-3.0.2}/blint/data/annotations/review_symbols_rust.yml +0 -0
  33. {blint-3.0.1 → blint-3.0.2}/blint/data/rules.yml +0 -0
  34. {blint-3.0.1 → blint-3.0.2}/blint/db.py +0 -0
  35. {blint-3.0.1 → blint-3.0.2}/blint/lib/__init__.py +0 -0
  36. {blint-3.0.1 → blint-3.0.2}/blint/lib/analysis.py +0 -0
  37. {blint-3.0.1 → blint-3.0.2}/blint/lib/android.py +0 -0
  38. {blint-3.0.1 → blint-3.0.2}/blint/lib/checks.py +0 -0
  39. {blint-3.0.1 → blint-3.0.2}/blint/lib/runners.py +0 -0
  40. {blint-3.0.1 → blint-3.0.2}/blint/lib/sbom.py +0 -0
  41. {blint-3.0.1 → blint-3.0.2}/blint/logger.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: blint
3
- Version: 3.0.1
3
+ Version: 3.0.2
4
4
  Summary: Linter and SBOM generator for binary files.
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -130,7 +130,7 @@ def build_parser():
130
130
  "--src",
131
131
  dest="src_dir_image",
132
132
  action="extend",
133
- default=[os.getcwd()],
133
+ default=[],
134
134
  nargs="+",
135
135
  help="Source directories, container images or binary files. Defaults to current directory.",
136
136
  )
@@ -238,6 +238,8 @@ def handle_args():
238
238
  args = build_args()
239
239
  if not args.no_banner and args.subcommand_name != "sbom":
240
240
  print(BLINT_LOGO)
241
+ if not args.src_dir_image:
242
+ args.src_dir_image = [os.getcwd()]
241
243
  blint_options = BlintOptions(
242
244
  deep_mode=args.deep_mode,
243
245
  exports_prefix=args.exports_prefix,
@@ -1402,14 +1402,14 @@ CRYPTO_INDICATORS = [
1402
1402
  'movdqa', 'movdqu', 'vmovdqa', 'vmovdqu',
1403
1403
  'padd', 'psub', 'pmul',
1404
1404
  'psll', 'psrl', 'psra',
1405
- 'vpaddd', 'vpsubd', 'vpmulld',
1405
+ 'vpaddd', 'vpsubd', 'vpmulld', 'pmaddwd'
1406
1406
  ]
1407
1407
  GPU_INDICATORS = [
1408
1408
  'glbind', 'glvertex', 'glcolor', 'glbegin', 'glend', 'glenable', 'gldisable', 'glget', 'glset', 'glload', 'glsave', 'gluniform', 'gluseprogram', 'glattachshader', 'gldraw', 'glclear', 'glviewport', 'glmatrix', 'glpushmatrix', 'glpopmatrix',
1409
1409
  'cuda', 'cuinit', 'cucontext', 'cudriver', 'cugpu', 'cudevice', 'cumem', 'cuptr', 'cukernel', 'culaunch', 'cugrid', 'cublock', 'cuthread', 'cufree', 'cucopy',
1410
1410
  'clgetplatform', 'clgetdevice', 'clcreatecontext', 'clcreatecommandqueue', 'clcreateshared', 'clcreatekernel', 'clsetkernelarg', 'clenqueuendrange', 'clfinish', 'clrelease', 'clbuildprogram',
1411
1411
  'd3d', 'd3d11', 'd3d12', 'create', 'device', 'swapchain', 'rendertarget', 'shaders', 'ps_', 'vs_', 'gs_', 'cs_', 'hs_', 'ds_',
1412
- 'vk', 'vkcreate', 'vkdestroy', 'vkallocate', 'vkfree', 'vkqueue', 'vksubmit', 'vkwait', 'vkacquire', 'vkpresent', 'vkcmd', 'vkbegin', 'vkend', 'vkbind', 'vkdraw', 'vkdispatch', 'vkcopy', 'vkblit', 'vkclear', 'vkfill', 'vkupdate',
1412
+ 'vkcreate', 'vkdestroy', 'vkallocate', 'vkfree', 'vkqueue', 'vksubmit', 'vkwait', 'vkacquire', 'vkpresent', 'vkcmd', 'vkbegin', 'vkend', 'vkbind', 'vkdraw', 'vkdispatch', 'vkcopy', 'vkblit', 'vkclear', 'vkfill', 'vkupdate',
1413
1413
  'mtl', 'metal', 'mtldevice', 'mtlcommand', 'mtlrender', 'mtlcompute', 'mtlbuffer', 'mtltexture', 'mtlfunction', 'mtllibrary', 'mtlencoder', 'mtlpass',
1414
1414
  'gpu', 'compute', 'shader', 'vertex', 'fragment', 'pixel', 'kernel', 'workgroup', 'local', 'global', 'buffer', 'texture', 'surface',
1415
1415
  ]
@@ -1476,3 +1476,72 @@ IMPLICIT_REGS_X64 = {
1476
1476
  'cpuid': {'read': {'eax', 'ecx'}, 'write': {'eax', 'ebx', 'ecx', 'edx'}},
1477
1477
  'syscall':{'read': {'rcx', 'r11'}, 'write': {'rcx', 'r11'}},
1478
1478
  }
1479
+
1480
+ IMPLICIT_REGS_ARM64 = {
1481
+ 'bl': {'write': {'x30'}},
1482
+ 'blr': {'write': {'x30'}},
1483
+ 'ret': {'read': {'x30'}},
1484
+ 'mrs': {'write': {'x0'}},
1485
+ 'msr': {'read': {'x0'}},
1486
+ 'svc': {'read': {'x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x8'}, 'write': {'x0'}},
1487
+ 'hvc': {'read': {'x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x8'}, 'write': {'x0'}},
1488
+ 'smc': {'read': {'x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x8'}, 'write': {'x0'}},
1489
+ 'brk': {'read': {'x0'}},
1490
+ }
1491
+
1492
+ # https://github.com/AsahiLinux/docs/blob/main/docs/hw/cpu/apple-instructions.md
1493
+ APPLE_PROPRIETARY_INSTRUCTION_RANGES = {
1494
+ "AMX": (0x00201000, 0x002012df),
1495
+ "WKDM": (0x00200800, 0x00200cff),
1496
+ "GuardedMode": (0x00201400, 0x00201420),
1497
+ "AddressTranslation": (0x00201440, 0x00201440),
1498
+ "SyncBarrier": (0x00201460, 0x00201463),
1499
+ }
1500
+
1501
+ APPLE_PROPRIETARY_SREGS = {
1502
+ "GXF_CONTROL": {
1503
+ "S3_6_C15_C1_2",
1504
+ "S3_6_C15_C8_1",
1505
+ },
1506
+ "SPRR_CONTROL": {
1507
+ "S3_6_C15_C1_0",
1508
+ "S3_6_C15_C1_5",
1509
+ "S3_6_C15_C1_6",
1510
+ },
1511
+ "PAC_KEYS": {
1512
+ "S3_4_C15_C1_0",
1513
+ "S3_4_C15_C1_1",
1514
+ },
1515
+ "JIT_HARDENING": {
1516
+ "S3_4_C15_C2_6",
1517
+ "S3_4_C15_C2_7",
1518
+ },
1519
+ "PERF_COUNTERS": {
1520
+ "S3_1_C15_C0_0",
1521
+ "S3_1_C15_C1_0",
1522
+ "S3_1_C15_C2_0",
1523
+ "S3_1_C15_C3_0",
1524
+ "S3_1_C15_C4_0",
1525
+ "S3_1_C15_C5_0",
1526
+ "S3_1_C15_C6_0",
1527
+ "S3_1_C15_C13_0",
1528
+ "S3_2_C15_C0_0",
1529
+ "S3_2_C15_C1_0",
1530
+ "S3_2_C15_C2_0",
1531
+ "S3_2_C15_C3_0",
1532
+ "S3_2_C15_C4_0",
1533
+ "S3_2_C15_C5_0",
1534
+ "S3_2_C15_C6_0",
1535
+ "S3_2_C15_C7_0",
1536
+ "S3_2_C15_C9_0",
1537
+ "S3_2_C15_C10_0",
1538
+ },
1539
+ "IPI_CONTROL": {
1540
+ "S3_5_C15_C1_1",
1541
+ "S3_5_C15_C3_1",
1542
+ },
1543
+ "VIRTUALIZATION": {
1544
+ "S3_5_C15_C1_2",
1545
+ "S3_5_C15_C1_3",
1546
+ },
1547
+ }
@@ -19,6 +19,7 @@ from blint.lib.utils import (
19
19
  cleanup_dict_lief_errors,
20
20
  decode_base64,
21
21
  demangle_symbolic_name,
22
+ enum_to_str,
22
23
  )
23
24
  from blint.lib.disassembler import disassemble_functions
24
25
 
@@ -98,7 +99,7 @@ def extract_note_data(idx, note):
98
99
  if note.type == lief.ELF.Note.TYPE.GNU_BUILD_ID:
99
100
  build_id = description_str.replace(" ", "")
100
101
  type_str = note.type
101
- type_str = str(type_str).rsplit(".", maxsplit=1)[-1]
102
+ type_str = enum_to_str(type_str)
102
103
  note_details = ""
103
104
  sdk_version = ""
104
105
  ndk_version = ""
@@ -258,10 +259,10 @@ def parse_symbols(symbols):
258
259
  symbols_list.append(
259
260
  {
260
261
  "name": symbol_name,
261
- "type": str(symbol.type).rsplit(".", maxsplit=1)[-1],
262
+ "type": enum_to_str(symbol.type),
262
263
  "value": symbol.value,
263
- "visibility": str(symbol.visibility).rsplit(".", maxsplit=1)[-1],
264
- "binding": str(symbol.binding).rsplit(".", maxsplit=1)[-1],
264
+ "visibility": enum_to_str(symbol.visibility),
265
+ "binding": enum_to_str(symbol.binding),
265
266
  "is_imported": is_imported,
266
267
  "is_exported": is_exported,
267
268
  "information": symbol.information,
@@ -342,13 +343,13 @@ def parse_pe_data(parsed_obj):
342
343
  section_name = ""
343
344
  section_chars = ""
344
345
  section_entropy = ""
345
- dir_type = str(directory.type).rsplit(".", maxsplit=1)[-1]
346
+ dir_type = enum_to_str(directory.type)
346
347
  if not dir_type.startswith("?") and directory.size:
347
348
  if directory.has_section:
348
349
  if directory.section.has_characteristic:
349
350
  section_chars = ", ".join(
350
351
  [
351
- str(chara).rsplit(".", maxsplit=1)[-1]
352
+ enum_to_str(chara)
352
353
  for chara in directory.section.characteristics_lists
353
354
  ]
354
355
  )
@@ -433,10 +434,10 @@ def process_pe_signature(parsed_obj):
433
434
  ci = sig.content_info
434
435
  signature_obj = {
435
436
  "version": sig.version,
436
- "digest_algorithm": str(sig.digest_algorithm).rsplit(".", maxsplit=1)[-1],
437
+ "digest_algorithm": enum_to_str(sig.digest_algorithm),
437
438
  "content_info": {
438
439
  "content_type": lief.PE.oid_to_string(ci.content_type),
439
- "digest_algorithm": str(ci.digest_algorithm).rsplit(".", maxsplit=1)[-1],
440
+ "digest_algorithm": enum_to_str(ci.digest_algorithm),
440
441
  "digest": ci.digest.hex(),
441
442
  },
442
443
  }
@@ -446,7 +447,7 @@ def process_pe_signature(parsed_obj):
446
447
  "version": signer.version,
447
448
  "serial_number": signer.serial_number.hex(),
448
449
  "issuer": str(signer.issuer),
449
- "digest_algorithm": str(signer.digest_algorithm).rsplit(".", maxsplit=1)[-1],
450
+ "digest_algorithm": enum_to_str(signer.digest_algorithm),
450
451
  "encryption_algorithm": str(signer.encryption_algorithm).rsplit(
451
452
  ".", maxsplit=1
452
453
  )[-1],
@@ -475,7 +476,7 @@ def parse_pe_authenticode(parsed_obj):
475
476
  "sha256_hash": parsed_obj.authentihash_sha256.hex(*sep),
476
477
  "sha512_hash": parsed_obj.authentihash_sha512.hex(*sep),
477
478
  "sha1_hash": parsed_obj.authentihash(lief.PE.ALGORITHMS.SHA_1).hex(*sep),
478
- "verification_flags": str(parsed_obj.verify_signature()).rsplit(".", maxsplit=1)[-1],
479
+ "verification_flags": enum_to_str(parsed_obj.verify_signature()),
479
480
  }
480
481
  if signatures := parsed_obj.signatures:
481
482
  if not isinstance(signatures, lief.lief_errors) and signatures[0].signers:
@@ -535,9 +536,9 @@ def parse_pe_symbols(symbols):
535
536
  "name": demangle_symbolic_name(symbol.name),
536
537
  "value": symbol.value,
537
538
  "id": section_nb_str,
538
- "base_type": str(symbol.base_type).rsplit(".", maxsplit=1)[-1],
539
- "complex_type": str(symbol.complex_type).rsplit(".", maxsplit=1)[-1],
540
- "storage_class": str(symbol.storage_class).rsplit(".", maxsplit=1)[-1],
539
+ "base_type": enum_to_str(symbol.base_type),
540
+ "complex_type": enum_to_str(symbol.complex_type),
541
+ "storage_class": enum_to_str(symbol.storage_class),
541
542
  }
542
543
  )
543
544
  except (IndexError, AttributeError, ValueError, RuntimeError):
@@ -663,7 +664,12 @@ def parse_macho_symbols(symbols):
663
664
  "num_sections": symbol.numberof_sections,
664
665
  "description": symbol.description,
665
666
  "address": symbol_value,
666
- "export_info": symbol.export_info if symbol.has_export_info else None,
667
+ "export_info": {
668
+ "symbol": symbol.export_info.symbol, "kind": symbol.export_info.kind,
669
+ "flags": str(symbol.export_info.flags),
670
+ "offset": ADDRESS_FMT.format(symbol.export_info.offset),
671
+ "address": ADDRESS_FMT.format(symbol.export_info.address)
672
+ } if symbol.has_export_info else None,
667
673
  "origin": symbol.origin,
668
674
  }
669
675
  )
@@ -785,16 +791,14 @@ def add_elf_header(header, metadata):
785
791
  return metadata
786
792
  try:
787
793
  eflags_str = determine_elf_flags(header)
788
- metadata["class"] = str(header.identity_class).rsplit(".", maxsplit=1)[-1]
789
- metadata["endianness"] = str(header.identity_data).rsplit(".", maxsplit=1)[-1]
790
- metadata["identity_version"] = str(header.identity_version).rsplit(".", maxsplit=1)[-1]
791
- metadata["identity_os_abi"] = str(header.identity_os_abi).rsplit(".", maxsplit=1)[-1]
792
- metadata["identity_abi_version"] = header.identity_abi_version
793
- metadata["file_type"] = str(header.file_type).rsplit(".", maxsplit=1)[-1]
794
- metadata["machine_type"] = str(header.machine_type).rsplit(".", maxsplit=1)[-1]
795
- metadata["object_file_version"] = str(header.object_file_version).rsplit(".", maxsplit=1)[
796
- -1
797
- ]
794
+ metadata["class"] = enum_to_str(header.identity_class)
795
+ metadata["endianness"] = enum_to_str(header.identity_data)
796
+ metadata["identity_version"] = enum_to_str(header.identity_version)
797
+ metadata["identity_os_abi"] = enum_to_str(header.identity_os_abi)
798
+ metadata["identity_abi_version"] = enum_to_str(header.identity_abi_version)
799
+ metadata["file_type"] = enum_to_str(header.file_type)
800
+ metadata["machine_type"] = enum_to_str(header.machine_type)
801
+ metadata["object_file_version"] = enum_to_str(header.object_file_version)
798
802
  metadata["entrypoint"] = header.entrypoint
799
803
  metadata["processor_flag"] = str(header.processor_flag) + eflags_str
800
804
  except (AttributeError, TypeError, ValueError) as e:
@@ -859,7 +863,7 @@ def add_elf_dynamic_entries(dynamic_entries, metadata):
859
863
  metadata["dynamic_entries"].append(
860
864
  {
861
865
  "name": demangle_symbolic_name(entry.name),
862
- "tag": str(entry.tag).rsplit(".", maxsplit=1)[-1],
866
+ "tag": enum_to_str(entry.tag),
863
867
  "value": entry.value,
864
868
  }
865
869
  )
@@ -871,7 +875,7 @@ def add_elf_dynamic_entries(dynamic_entries, metadata):
871
875
  metadata["dynamic_entries"].append(
872
876
  {
873
877
  "name": "runpath",
874
- "tag": str(entry.tag).rsplit(".", maxsplit=1)[-1],
878
+ "tag": enum_to_str(entry.tag),
875
879
  "value": entry.runpath,
876
880
  }
877
881
  )
@@ -881,7 +885,7 @@ def add_elf_dynamic_entries(dynamic_entries, metadata):
881
885
  metadata["dynamic_entries"].append(
882
886
  {
883
887
  "name": "rpath",
884
- "tag": str(entry.tag).rsplit(".", maxsplit=1)[-1],
888
+ "tag": enum_to_str(entry.tag),
885
889
  "value": entry.rpath,
886
890
  }
887
891
  )
@@ -899,7 +903,7 @@ def determine_elf_flags(header):
899
903
  eflags_str = ""
900
904
  if header.machine_type == lief.ELF.ARCH.ARM and hasattr(header, "arm_flags_list"):
901
905
  eflags_str = " - ".join(
902
- [str(s).rsplit(".", maxsplit=1)[-1] for s in header.arm_flags_list]
906
+ [enum_to_str(s) for s in header.arm_flags_list]
903
907
  )
904
908
  if header.machine_type in [
905
909
  lief.ELF.ARCH.MIPS,
@@ -907,15 +911,15 @@ def determine_elf_flags(header):
907
911
  lief.ELF.ARCH.MIPS_X,
908
912
  ]:
909
913
  eflags_str = " - ".join(
910
- [str(s).rsplit(".", maxsplit=1)[-1] for s in header.mips_flags_list]
914
+ [enum_to_str(s) for s in header.mips_flags_list]
911
915
  )
912
916
  if header.machine_type == lief.ELF.ARCH.PPC64:
913
917
  eflags_str = " - ".join(
914
- [str(s).rsplit(".", maxsplit=1)[-1] for s in header.ppc64_flags_list]
918
+ [enum_to_str(s) for s in header.ppc64_flags_list]
915
919
  )
916
920
  if header.machine_type == lief.ELF.ARCH.HEXAGON:
917
921
  eflags_str = " - ".join(
918
- [str(s).rsplit(".", maxsplit=1)[-1] for s in header.hexagon_flags_list]
922
+ [enum_to_str(s) for s in header.hexagon_flags_list]
919
923
  )
920
924
  return eflags_str
921
925
 
@@ -1303,7 +1307,7 @@ def add_pe_header_data(metadata, parsed_obj):
1303
1307
  dos_header.addressof_new_exeheader
1304
1308
  ).strip()
1305
1309
  metadata["characteristics"] = ", ".join(
1306
- [str(chara).rsplit(".", maxsplit=1)[-1] for chara in header.characteristics_list]
1310
+ [enum_to_str(chara) for chara in header.characteristics_list]
1307
1311
  )
1308
1312
  metadata["num_sections"] = header.numberof_sections
1309
1313
  metadata["time_date_stamps"] = header.time_date_stamps
@@ -1331,14 +1335,14 @@ def add_pe_optional_headers(metadata, optional_header):
1331
1335
  with contextlib.suppress(IndexError, TypeError):
1332
1336
  metadata["dll_characteristics"] = ", ".join(
1333
1337
  [
1334
- str(chara).rsplit(".", maxsplit=1)[-1]
1338
+ enum_to_str(chara)
1335
1339
  for chara in optional_header.dll_characteristics_lists
1336
1340
  ]
1337
1341
  )
1338
1342
  # Detect if this binary is a driver
1339
1343
  if "WDM_DRIVER" in metadata["dll_characteristics"]:
1340
1344
  metadata["is_driver"] = True
1341
- metadata["subsystem"] = str(optional_header.subsystem).rsplit(".", maxsplit=1)[-1]
1345
+ metadata["subsystem"] = enum_to_str(optional_header.subsystem)
1342
1346
  metadata["is_gui"] = metadata["subsystem"] == "WINDOWS_GUI"
1343
1347
  metadata["exe_type"] = "PE32" if optional_header.magic == lief.PE.PE_TYPE.PE32 else "PE64"
1344
1348
  metadata["major_linker_version"] = optional_header.major_linker_version
@@ -1552,13 +1556,13 @@ def add_mach0_build_metadata(exe_file, metadata, parsed_obj):
1552
1556
  build_version = parsed_obj.build_version
1553
1557
  if not build_version:
1554
1558
  return metadata
1555
- metadata["platform"] = str(build_version.platform).rsplit(".", maxsplit=1)[-1]
1559
+ metadata["platform"] = enum_to_str(build_version.platform)
1556
1560
  metadata["minos"] = "{:d}.{:d}.{:d}".format(*build_version.minos)
1557
1561
  metadata["sdk"] = "{:d}.{:d}.{:d}".format(*build_version.sdk)
1558
1562
  if tools := build_version.tools:
1559
1563
  metadata["tools"] = []
1560
1564
  for tool in tools:
1561
- tool_str = str(tool.tool).rsplit(".", maxsplit=1)[-1]
1565
+ tool_str = enum_to_str(tool.tool)
1562
1566
  metadata["tools"].append(
1563
1567
  {
1564
1568
  "tool": tool_str,
@@ -1614,12 +1618,12 @@ def add_mach0_header_data(exe_file, metadata, parsed_obj):
1614
1618
  """
1615
1619
  try:
1616
1620
  header = parsed_obj.header
1617
- flags_str = ", ".join([str(s).rsplit(".", maxsplit=1)[-1] for s in header.flags_list])
1618
- metadata["magic"] = str(header.magic).rsplit(".", maxsplit=1)[-1]
1621
+ flags_str = ", ".join([enum_to_str(s) for s in header.flags_list])
1622
+ metadata["magic"] = enum_to_str(header.magic)
1619
1623
  metadata["is_neural_model"] = header.magic == lief.MachO.MACHO_TYPES.NEURAL_MODEL
1620
- metadata["cpu_type"] = str(header.cpu_type).rsplit(".", maxsplit=1)[-1]
1624
+ metadata["cpu_type"] = enum_to_str(header.cpu_type)
1621
1625
  metadata["cpu_subtype"] = header.cpu_subtype
1622
- metadata["file_type"] = str(header.file_type).rsplit(".", maxsplit=1)[-1]
1626
+ metadata["file_type"] = enum_to_str(header.file_type)
1623
1627
  metadata["flags"] = flags_str
1624
1628
  metadata["number_commands"] = header.nb_cmds
1625
1629
  metadata["size_commands"] = header.sizeof_cmds
@@ -1643,6 +1647,18 @@ def add_mach0_functions(metadata, parsed_obj):
1643
1647
  metadata["ctor_functions"] = parse_functions(parsed_obj.ctor_functions)
1644
1648
  metadata["unwind_functions"] = parse_functions(parsed_obj.unwind_functions)
1645
1649
  metadata["symtab_symbols"], exe_type = parse_macho_symbols(parsed_obj.symbols)
1650
+
1651
+ # Populate function info based on local symbols for .o files or others where parsed_obj.functions is empty.
1652
+ if not metadata["functions"]:
1653
+ metadata["functions"] = [
1654
+ {
1655
+ "idx": idx,
1656
+ "name": symbol["name"],
1657
+ "address": symbol["address"]
1658
+ }
1659
+ for idx, symbol in enumerate(s for s in metadata["symtab_symbols"] if s["category"] == lief.MachO.Symbol.CATEGORY.LOCAL)
1660
+ ]
1661
+
1646
1662
  if exe_type:
1647
1663
  metadata["exe_type"] = exe_type
1648
1664
  if parsed_obj.dylinker:
@@ -2,15 +2,43 @@ from blint.logger import LOG
2
2
  import lief
3
3
  import hashlib
4
4
  import re
5
- from blint.config import CRYPTO_INDICATORS, GPU_INDICATORS, SECURITY_INDICATORS, SYSCALL_INDICATORS, IMPLICIT_REGS_X86, IMPLICIT_REGS_X64
5
+ from blint.config import CRYPTO_INDICATORS, GPU_INDICATORS, SECURITY_INDICATORS, SYSCALL_INDICATORS, IMPLICIT_REGS_X86, IMPLICIT_REGS_X64, IMPLICIT_REGS_ARM64, APPLE_PROPRIETARY_INSTRUCTION_RANGES, APPLE_PROPRIETARY_SREGS
6
6
 
7
7
  OPERAND_DELIMITERS_PATTERN = re.compile(r'[^a-zA-Z0-9_]+')
8
8
 
9
9
  ARITH_INST = ['add', 'sub', 'imul', 'mul', 'div', 'idiv', 'inc', 'dec', 'neg', 'not', 'and', 'or', 'xor', 'adc', 'sbb', 'xadd', 'cmpxchg']
10
10
  SHIFT_INST = ['shl', 'shr', 'sal', 'sar', 'rol', 'ror', 'rcl', 'rcr', 'psll', 'psrl', 'psra', 'vpsll', 'vpsrl', 'vpsra']
11
- CONDITIONAL_JMP_INST = ['je', 'jne', 'jz', 'jnz', 'jg', 'jge', 'jl', 'jle', 'ja', 'jae', 'jb', 'jbe',
11
+ CONDITIONAL_JMP_INST_X86 = ['je', 'jne', 'jz', 'jnz', 'jg', 'jge', 'jl', 'jle', 'ja', 'jae', 'jb', 'jbe',
12
12
  'jp', 'jnp', 'jo', 'jno',
13
13
  'js', 'jns', 'loop', 'loopz', 'loopnz', 'jcxz', 'jecxz', 'jrcxz']
14
+ X86_CALL_INST = {'call'}
15
+ X86_UNCONDITIONAL_JMP_INST = {'jmp', 'jmpq', 'jmpl'}
16
+ X86_RET_INST = {'ret', 'retn', 'retf', 'iret', 'iretd', 'iretq'}
17
+ ARM64_B_COND_INST = [
18
+ 'beq', 'bne', 'bge', 'bgt', 'ble', 'blt', 'bhs', 'bcs',
19
+ 'blo', 'bcc', 'bvs', 'bvc', 'bmi', 'bpl', 'bhi', 'bls'
20
+ ]
21
+ ARM64_CB_TB_INST = ['cbz', 'cbnz', 'tbz', 'tbnz']
22
+ ARM64_CONDITIONAL_JMP_INST = ARM64_B_COND_INST + ARM64_CB_TB_INST
23
+ CONDITIONAL_JMP_INST = CONDITIONAL_JMP_INST_X86 + ARM64_CONDITIONAL_JMP_INST
24
+
25
+ ARM64_GENERAL_REGS_64 = {f'x{i}' for i in range(31)}
26
+ ARM64_GENERAL_REGS_32 = {f'w{i}' for i in range(31)}
27
+ ARM64_SPECIAL_REGS = {'sp', 'xzr', 'wzr'}
28
+ ARM64_VFP_NEON_REGS = {f'v{i}' for i in range(32)} | \
29
+ {f's{i}' for i in range(32)} | \
30
+ {f'd{i}' for i in range(32)} | \
31
+ {f'q{i}' for i in range(32)}
32
+ ARM64_ALL_REGS = (
33
+ ARM64_GENERAL_REGS_64 | ARM64_GENERAL_REGS_32 | ARM64_SPECIAL_REGS | ARM64_VFP_NEON_REGS
34
+ )
35
+ ARM64_CALL_INST = {'bl', 'blr'}
36
+ ARM64_UNCONDITIONAL_JMP_INST = {'b', 'br'}
37
+ ARM64_RET_INST = {'ret', 'eret'}
38
+ TERMINATING_INST = X86_RET_INST | ARM64_RET_INST
39
+ UNCONDITIONAL_JMP_INST_ALL = X86_UNCONDITIONAL_JMP_INST | ARM64_UNCONDITIONAL_JMP_INST
40
+ SORTED_ARM64_ALL_REGS = sorted(ARM64_ALL_REGS, key=len, reverse=True)
41
+
14
42
  COMMON_REGS_64 = {'rax', 'rbx', 'rcx', 'rdx', 'rsi', 'rdi', 'rbp', 'rsp',
15
43
  'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15'}
16
44
  COMMON_REGS_32 = {'eax', 'ebx', 'ecx', 'edx', 'esi', 'edi', 'ebp', 'esp',
@@ -20,9 +48,6 @@ COMMON_REGS_16 = {'ax', 'bx', 'cx', 'dx', 'si', 'di', 'bp', 'sp',
20
48
  COMMON_REGS_8l = {'al', 'bl', 'cl', 'dl', 'sil', 'dil', 'bpl', 'spl',
21
49
  'r8b', 'r9b', 'r10b', 'r11b', 'r12b', 'r13b', 'r14b', 'r15b'}
22
50
  COMMON_REGS_8h = {'ah', 'bh', 'ch', 'dh'}
23
-
24
- TERMINATING_INST = {'ret', 'retn', 'retf', 'iret', 'iretd', 'iretq'}
25
- UNCONDITIONAL_JMP_INST = {'jmp', 'jmpq', 'jmpl'}
26
51
  READ_WRITE_BOTH_OPS_INST = {'xadd', 'cmpxchg', 'cmpxchg8b', 'cmpxchg16b'}
27
52
  BIT_MANIPULATION_INST = {'bt', 'bts', 'bsf', 'bsr', 'btr', 'btc', 'popcnt', 'lzcnt', 'tzcnt'}
28
53
  READ_WRITE_ONE_OP_INST = {'inc', 'dec', 'not', 'neg', 'rol', 'ror', 'rcl', 'rcr', 'shl', 'shr', 'sal', 'sar'}
@@ -42,8 +67,8 @@ XMM_REGS = {f'xmm{i}' for i in range(32)}
42
67
  YMM_REGS = {f'ymm{i}' for i in range(32)}
43
68
  ZMM_REGS = {f'zmm{i}' for i in range(32)}
44
69
  ALL_SIMD_REGS = FPU_REGS | MMX_REGS | XMM_REGS | YMM_REGS | ZMM_REGS
45
- ALL_REGS = COMMON_REGS_64 | COMMON_REGS_32 | COMMON_REGS_16 | COMMON_REGS_8l | COMMON_REGS_8h | ALL_SIMD_REGS | SEGMENT_REGS
46
- SORTED_ALL_REGS = sorted(ALL_REGS, key=len, reverse=True)
70
+ ALL_REGS_X86 = (COMMON_REGS_64 | COMMON_REGS_32 | COMMON_REGS_16 | COMMON_REGS_8l | COMMON_REGS_8h | ALL_SIMD_REGS | SEGMENT_REGS)
71
+ SORTED_ALL_REGS_X86 = sorted(ALL_REGS_X86, key=len, reverse=True)
47
72
 
48
73
  WIN_X64_VOLATILE_REGS = frozenset({'rax', 'rcx', 'rdx', 'r8', 'r9', 'r10', 'r11'})
49
74
  SYSV_X64_VOLATILE_REGS = frozenset({'rax', 'rcx', 'rdx', 'rsi', 'rdi', 'r8', 'r9', 'r10', 'r11'})
@@ -51,6 +76,12 @@ CDECL_X86_VOLATILE_REGS = frozenset({'eax', 'ecx', 'edx'})
51
76
  X64_RETURN_REGS = frozenset({'rax'})
52
77
  X86_RETURN_REGS = frozenset({'eax'})
53
78
 
79
+ _SREG_TO_CATEGORY_MAP = {
80
+ sreg.lower(): category
81
+ for category, sregs in APPLE_PROPRIETARY_SREGS.items()
82
+ for sreg in sregs
83
+ }
84
+
54
85
  try:
55
86
  from nyxstone import Nyxstone
56
87
  NYXSTONE_AVAILABLE = True
@@ -58,10 +89,20 @@ except ImportError:
58
89
  LOG.debug("Nyxstone not found. Disassembly features will be unavailable. Install with 'pip install blint[extended]'.")
59
90
  NYXSTONE_AVAILABLE = False
60
91
 
92
+ def get_arch_reg_set(arch_target):
93
+ """Returns the appropriate set of registers based on the architecture."""
94
+ is_aarch64 = "aarch64" in arch_target.lower() or "arm64" in arch_target.lower()
95
+ if is_aarch64:
96
+ return SORTED_ARM64_ALL_REGS
97
+ else:
98
+ return SORTED_ALL_REGS_X86
99
+
61
100
  def _get_implicit_regs_map(arch_target):
62
101
  """Selects the appropriate implicit registers map based on architecture."""
63
- if "64" in arch_target:
102
+ if "64" in arch_target and "aarch64" not in arch_target.lower():
64
103
  return IMPLICIT_REGS_X64
104
+ elif "aarch64" in arch_target.lower() or "arm64" in arch_target.lower():
105
+ return IMPLICIT_REGS_ARM64
65
106
  return IMPLICIT_REGS_X86
66
107
 
67
108
  def _find_function_end_index(instr_list):
@@ -76,10 +117,10 @@ def _find_function_end_index(instr_list):
76
117
  if mnemonic in TERMINATING_INST:
77
118
  if i + 1 < len(instr_list):
78
119
  next_mnemonic = instr_list[i+1].assembly.split(None, 1)[0].lower()
79
- if next_mnemonic in ['int3', 'nop']:
120
+ if next_mnemonic in ('int3', 'nop'):
80
121
  return i
81
122
  return i
82
- if mnemonic in UNCONDITIONAL_JMP_INST:
123
+ if mnemonic in UNCONDITIONAL_JMP_INST_ALL:
83
124
  return i
84
125
  return len(instr_list) - 1
85
126
 
@@ -102,7 +143,7 @@ def _get_abi_volatile_regs(parsed_obj, arch_target):
102
143
  def _get_function_ranges(parsed_obj, metadata):
103
144
  """Calculates the address ranges for each function based on the next function or section end."""
104
145
  section_func_map = {}
105
- for func_list_key in ["functions", "ctor_functions", "exception_functions", "unwind_functions", "exports"]:
146
+ for func_list_key in ("functions", "ctor_functions", "exception_functions", "unwind_functions", "exports"):
106
147
  for func_entry in metadata.get(func_list_key, []):
107
148
  func_addr_str = func_entry.get("address", "")
108
149
  if func_addr_str:
@@ -193,17 +234,26 @@ def _get_disasm_range(func_addr, sec_obj, parsed_obj, section_func_map):
193
234
  size_to_disasm = max(0, min(size_to_disasm, len(sec_content_bytes) - func_offset_in_sec))
194
235
  return func_offset_in_sec, size_to_disasm, sec_content_bytes
195
236
 
196
- def extract_regs_from_operand(op):
237
+ def extract_regs_from_operand(op, sorted_arch_regs=SORTED_ALL_REGS_X86):
197
238
  found_regs = set()
198
239
  if not op:
199
240
  return found_regs
200
241
  potential_tokens = filter(None, OPERAND_DELIMITERS_PATTERN.split(op.lower()))
201
242
  for token in potential_tokens:
202
- if token in SORTED_ALL_REGS:
243
+ if token in sorted_arch_regs:
203
244
  found_regs.add(token)
245
+ cleaned_token = token.strip('[]!')
246
+ if cleaned_token in sorted_arch_regs:
247
+ found_regs.add(cleaned_token)
248
+ if ' ' in cleaned_token:
249
+ sub_tokens = cleaned_token.split()
250
+ for sub_t in sub_tokens:
251
+ sub_cleaned = sub_t.strip('[]!')
252
+ if sub_cleaned in sorted_arch_regs:
253
+ found_regs.add(sub_cleaned)
204
254
  return found_regs
205
255
 
206
- def _extract_register_usage(instr_assembly, parsed_obj=None, arch_target=""):
256
+ def _extract_register_usage(instr_assembly, parsed_obj=None, arch_target="", sorted_arch_regs=None):
207
257
  """
208
258
  Performs a first-pass analysis to extract approximate register read/write usage
209
259
  from the instruction assembly string.
@@ -212,135 +262,222 @@ def _extract_register_usage(instr_assembly, parsed_obj=None, arch_target=""):
212
262
  regs_read = set()
213
263
  regs_written = set()
214
264
  if not instr_assembly:
215
- return list(regs_read), list(regs_written)
265
+ return sorted(regs_read), sorted(regs_written)
266
+ is_aarch64 = "aarch64" in arch_target.lower() or "arm64" in arch_target.lower()
267
+ if not sorted_arch_regs:
268
+ sorted_arch_regs = get_arch_reg_set(arch_target)
216
269
  first_space_idx = instr_assembly.find(' ')
270
+ operands = []
217
271
  if first_space_idx == -1:
218
272
  mnemonic = instr_assembly.strip().lower().rstrip(':')
219
- operands = []
220
273
  else:
221
274
  mnemonic_part = instr_assembly[:first_space_idx].strip().lower().rstrip(':')
222
275
  operands_part = instr_assembly[first_space_idx + 1:].strip()
223
276
  mnemonic = mnemonic_part.rstrip(':')
224
- comma_idx = operands_part.find(',')
225
- if comma_idx != -1:
226
- op1 = operands_part[:comma_idx].strip()
227
- op2 = operands_part[comma_idx + 1:].strip()
228
- operands = [op1, op2]
229
- else:
230
- operands = [operands_part] if operands_part else []
277
+ if operands_part:
278
+ operands = [op.strip() for op in operands_part.split(',')]
231
279
  num_operands = len(operands)
232
280
  if num_operands > 0:
233
281
  operands = [op.rstrip(',') for op in operands]
234
-
235
282
  has_rep_prefix = False
236
283
  if mnemonic.startswith(('rep', 'repe', 'repne')):
237
284
  has_rep_prefix = True
238
285
  mnemonic = mnemonic[4:] if len(mnemonic) > 3 and mnemonic[3] == 'e' else mnemonic[3:]
239
-
240
286
  if mnemonic in implicit_regs_map:
241
287
  regs_read.update(implicit_regs_map[mnemonic].get('read', set()))
242
288
  regs_written.update(implicit_regs_map[mnemonic].get('write', set()))
243
-
244
289
  if has_rep_prefix:
245
290
  is_64bit = "64" in arch_target
246
291
  counter_reg = 'rcx' if is_64bit else 'ecx'
247
292
  regs_read.add(counter_reg)
248
293
  regs_written.add(counter_reg)
249
-
250
- if mnemonic in WRITE_DST_READ_SRC_INST or mnemonic.startswith('cmov'):
251
- if num_operands >= 2:
252
- dst_regs = extract_regs_from_operand(operands[0].lower())
253
- src_regs = extract_regs_from_operand(operands[1].lower())
254
- regs_written.update(dst_regs)
255
- regs_read.update(src_regs)
256
- if mnemonic not in ['mov', 'movzx', 'movsx', 'movsxd', 'lea'] and not mnemonic.startswith('cmov'):
257
- regs_read.update(dst_regs)
258
-
259
- elif mnemonic in READ_WRITE_BOTH_OPS_INST:
260
- if num_operands >= 2:
261
- op1_regs = extract_regs_from_operand(operands[0].lower())
262
- op2_regs = extract_regs_from_operand(operands[1].lower())
263
- regs_read.update(op1_regs)
264
- regs_written.update(op1_regs)
265
- regs_read.update(op2_regs)
266
- if mnemonic != 'cmpxchg':
267
- regs_written.update(op2_regs)
268
-
269
- elif mnemonic in BIT_MANIPULATION_INST:
270
- if num_operands >= 2:
271
- dst_regs = extract_regs_from_operand(operands[0].lower())
272
- src_regs = extract_regs_from_operand(operands[1].lower())
273
- regs_written.update(dst_regs)
274
- regs_read.update(src_regs)
275
- if mnemonic not in ['bsf', 'bsr', 'lzcnt', 'tzcnt', 'popcnt']:
276
- regs_read.update(dst_regs)
277
-
278
- elif mnemonic in READ_WRITE_ONE_OP_INST:
279
- if num_operands >= 1:
280
- op_regs = extract_regs_from_operand(operands[0].lower())
281
- regs_read.update(op_regs)
282
- regs_written.update(op_regs)
283
-
284
- elif mnemonic in ['cmp', 'test']:
285
- if num_operands >= 2:
286
- regs_read.update(extract_regs_from_operand(operands[0].lower()))
287
- regs_read.update(extract_regs_from_operand(operands[1].lower()))
288
-
289
- elif mnemonic in ['push', 'pop']:
290
- is_64bit = "64" in arch_target
291
- stack_reg = 'rsp' if is_64bit else 'esp'
292
- regs_read.add(stack_reg)
293
- regs_written.add(stack_reg)
294
- if num_operands >= 1:
295
- op_regs = extract_regs_from_operand(operands[0].lower())
296
- if mnemonic == 'push':
294
+ if is_aarch64:
295
+ if mnemonic in ('add', 'adds', 'sub', 'subs', 'neg', 'negs', 'mul', 'umull', 'smull', 'smulh', 'umulh', 'div', 'udiv'):
296
+ if num_operands >= 2:
297
+ dst_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
298
+ src1_regs = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
299
+ regs_written.update(dst_regs)
300
+ regs_read.update(src1_regs)
301
+ if num_operands >= 3:
302
+ src2_regs = extract_regs_from_operand(operands[2].lower(), sorted_arch_regs)
303
+ regs_read.update(src2_regs)
304
+ elif mnemonic in ('mov', 'movz', 'movk', 'movn', 'fmov', 'fmov immediate'):
305
+ if num_operands >= 1:
306
+ dst_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
307
+ regs_written.update(dst_regs)
308
+ if num_operands >= 2 and not operands[1].lower().startswith('#'):
309
+ src_regs = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
310
+ regs_read.update(src_regs)
311
+ elif mnemonic in ('csel', 'csinc', 'csinv', 'cset', 'csetm', 'cinc', 'cinv'):
312
+ if num_operands >= 3:
313
+ dst_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
314
+ src1_regs = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
315
+ src2_regs = extract_regs_from_operand(operands[2].lower(), sorted_arch_regs)
316
+ regs_written.update(dst_regs)
317
+ regs_read.update(src1_regs)
318
+ regs_read.update(src2_regs)
319
+ if mnemonic in ('cinc', 'cinv'):
320
+ regs_read.update(dst_regs)
321
+ elif mnemonic in ('cmp', 'cmn', 'tst'):
322
+ if num_operands >= 2:
323
+ src1_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
324
+ src2_regs = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
325
+ regs_read.update(src1_regs)
326
+ regs_read.update(src2_regs)
327
+ elif mnemonic.startswith('ldr') or mnemonic.startswith('str'):
328
+ if num_operands >= 2:
329
+ data_reg = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
330
+ addr_parts = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
331
+ if 'str' in mnemonic:
332
+ regs_read.update(data_reg)
333
+ regs_read.update(addr_parts)
334
+ else: # ldr
335
+ regs_written.update(data_reg)
336
+ regs_read.update(addr_parts)
337
+ elif mnemonic.startswith('ldp') or mnemonic.startswith('stp'):
338
+ if num_operands >= 3:
339
+ data_reg1 = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
340
+ data_reg2 = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
341
+ mem_operand = operands[2].lower()
342
+ addr_parts = extract_regs_from_operand(operands[2].lower(), sorted_arch_regs)
343
+ if '!' in mem_operand:
344
+ base_reg = next(iter(addr_parts), None)
345
+ if base_reg:
346
+ regs_written.add(base_reg)
347
+ if 'str' in mnemonic:
348
+ regs_read.update(data_reg1)
349
+ regs_read.update(data_reg2)
350
+ regs_read.update(addr_parts)
351
+ else:
352
+ regs_written.update(data_reg1)
353
+ regs_written.update(data_reg2)
354
+ regs_read.update(addr_parts)
355
+ elif mnemonic.startswith('cb') or mnemonic.startswith('tb'):
356
+ if num_operands >= 1:
357
+ src_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
358
+ regs_read.update(src_regs)
359
+ elif mnemonic.startswith('b') and mnemonic not in ('bl', 'blr', 'br'):
360
+ pass
361
+ elif mnemonic in ('bl', 'blr', 'br'):
362
+ if num_operands >= 1 and mnemonic != 'bl':
363
+ target_op = operands[0].lower()
364
+ if not target_op.startswith('#') and not target_op.isdigit():
365
+ target_regs = extract_regs_from_operand(target_op, sorted_arch_regs)
366
+ regs_read.update(target_regs)
367
+ elif mnemonic in ('ret', 'eret'):
368
+ pass
369
+ elif mnemonic in ('and', 'orr', 'eor', 'bic', 'tst'):
370
+ if num_operands >= 2:
371
+ dst_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
372
+ src1_regs = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
373
+ regs_written.update(dst_regs)
374
+ regs_read.update(src1_regs)
375
+ if num_operands >= 3:
376
+ src2_regs = extract_regs_from_operand(operands[2].lower(), sorted_arch_regs)
377
+ regs_read.update(src2_regs)
378
+ elif mnemonic in ('lsl', 'lsr', 'asr', 'ror', 'uxtw', 'sxtw', 'sxtx', 'uxtb', 'uxth', 'sxtb', 'sxth'):
379
+ if num_operands >= 2:
380
+ dst_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
381
+ src1_regs = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
382
+ regs_written.update(dst_regs)
383
+ regs_read.update(src1_regs)
384
+ if num_operands >= 3:
385
+ src2_regs = extract_regs_from_operand(operands[2].lower(), sorted_arch_regs)
386
+ regs_read.update(src2_regs)
387
+ else:
388
+ if mnemonic in WRITE_DST_READ_SRC_INST or mnemonic.startswith('cmov'):
389
+ if num_operands >= 2:
390
+ dst_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
391
+ src_regs = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
392
+ regs_written.update(dst_regs)
393
+ regs_read.update(src_regs)
394
+ if mnemonic not in ('mov', 'movzx', 'movsx', 'movsxd', 'lea') and not mnemonic.startswith('cmov'):
395
+ regs_read.update(dst_regs)
396
+ elif mnemonic in READ_WRITE_BOTH_OPS_INST:
397
+ if num_operands >= 2:
398
+ op1_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
399
+ op2_regs = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
400
+ regs_read.update(op1_regs)
401
+ regs_written.update(op1_regs)
402
+ regs_read.update(op2_regs)
403
+ if mnemonic != 'cmpxchg':
404
+ regs_written.update(op2_regs)
405
+ elif mnemonic in BIT_MANIPULATION_INST:
406
+ if num_operands >= 2:
407
+ dst_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
408
+ src_regs = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
409
+ regs_written.update(dst_regs)
410
+ regs_read.update(src_regs)
411
+ if mnemonic not in ('bsf', 'bsr', 'lzcnt', 'tzcnt', 'popcnt'):
412
+ regs_read.update(dst_regs)
413
+ elif mnemonic in READ_WRITE_ONE_OP_INST:
414
+ if num_operands >= 1:
415
+ op_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
297
416
  regs_read.update(op_regs)
298
- else:
299
417
  regs_written.update(op_regs)
418
+ elif mnemonic in ('cmp', 'test'):
419
+ if num_operands >= 2:
420
+ regs_read.update(extract_regs_from_operand(operands[0].lower(), sorted_arch_regs))
421
+ regs_read.update(extract_regs_from_operand(operands[1].lower(), sorted_arch_regs))
422
+ elif mnemonic in ('push', 'pop'):
423
+ is_64bit = "64" in arch_target
424
+ stack_reg = 'rsp' if is_64bit else 'esp'
425
+ regs_read.add(stack_reg)
426
+ regs_written.add(stack_reg)
427
+ if num_operands >= 1:
428
+ op_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
429
+ if mnemonic == 'push':
430
+ regs_read.update(op_regs)
431
+ else:
432
+ regs_written.update(op_regs)
433
+ elif mnemonic == 'call':
434
+ volatile_regs = _get_abi_volatile_regs(parsed_obj, arch_target)
435
+ regs_written.update(volatile_regs)
436
+ if num_operands >= 1:
437
+ op = operands[0].lower()
438
+ if not op.startswith('0x') and not op.isdigit():
439
+ op_regs = extract_regs_from_operand(op, sorted_arch_regs)
440
+ regs_read.update(op_regs)
441
+ elif mnemonic in TERMINATING_INST:
442
+ is_64bit = "64" in arch_target or "aarch64" in arch_target
443
+ if is_64bit:
444
+ regs_read.update(X64_RETURN_REGS)
445
+ else:
446
+ regs_read.update(X86_RETURN_REGS)
447
+ stack_reg = 'rsp' if is_64bit else 'esp'
448
+ regs_read.add(stack_reg)
449
+ regs_written.add(stack_reg)
450
+ elif mnemonic.startswith('j'):
451
+ if num_operands >= 1:
452
+ op = operands[0].lower()
453
+ if not op.startswith('0x') and not op.isdigit():
454
+ op_regs = extract_regs_from_operand(op, sorted_arch_regs)
455
+ regs_read.update(op_regs)
456
+ elif mnemonic == 'xchg':
457
+ if num_operands >= 2:
458
+ op1_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
459
+ op2_regs = extract_regs_from_operand(operands[1].lower(), sorted_arch_regs)
460
+ regs_read.update(op1_regs)
461
+ regs_written.update(op1_regs)
462
+ regs_read.update(op2_regs)
463
+ regs_written.update(op2_regs)
464
+ if mnemonic in ('mul', 'imul', 'div', 'idiv') and num_operands == 1:
465
+ op_regs = extract_regs_from_operand(operands[0].lower(), sorted_arch_regs)
466
+ regs_read.update(op_regs)
300
467
 
301
- elif mnemonic == 'call':
302
- volatile_regs = _get_abi_volatile_regs(parsed_obj, arch_target)
303
- regs_written.update(volatile_regs)
304
- if num_operands >= 1:
305
- op = operands[0].lower()
306
- if not op.startswith('0x') and not op.isdigit():
307
- op_regs = extract_regs_from_operand(op)
308
- regs_read.update(op_regs)
309
-
310
- elif mnemonic in TERMINATING_INST:
311
- is_64bit = "64" in arch_target or "aarch64" in arch_target
312
- if is_64bit:
313
- regs_read.update(X64_RETURN_REGS)
314
- else:
315
- regs_read.update(X86_RETURN_REGS)
316
- stack_reg = 'rsp' if is_64bit else 'esp'
317
- regs_read.add(stack_reg)
318
- regs_written.add(stack_reg)
319
-
320
- elif mnemonic.startswith('j'):
321
- if num_operands >= 1:
322
- op = operands[0].lower()
323
- if not op.startswith('0x') and not op.isdigit():
324
- op_regs = extract_regs_from_operand(op)
325
- regs_read.update(op_regs)
326
-
327
- elif mnemonic == 'xchg':
328
- if num_operands >= 2:
329
- op1_regs = extract_regs_from_operand(operands[0].lower())
330
- op2_regs = extract_regs_from_operand(operands[1].lower())
331
- regs_read.update(op1_regs)
332
- regs_written.update(op1_regs)
333
- regs_read.update(op2_regs)
334
- regs_written.update(op2_regs)
335
-
336
- if mnemonic in ['mul', 'imul', 'div', 'idiv'] and num_operands == 1:
337
- op_regs = extract_regs_from_operand(operands[0].lower())
338
- regs_read.update(op_regs)
339
-
340
- return list(regs_read), list(regs_written)
468
+ return sorted(regs_read), sorted(regs_written)
341
469
 
342
470
  def _analyze_instructions(instr_list, func_addr, next_func_addr_in_sec, instr_addresses, parsed_obj=None, arch_target=""):
343
471
  """Analyzes the list of instructions for metrics, loops, and indirect calls."""
472
+ is_aarch64 = "aarch64" in arch_target.lower() or "arm64" in arch_target.lower()
473
+ if is_aarch64:
474
+ CALL_INST = ARM64_CALL_INST
475
+ UNCONDITIONAL_JMP_INST = ARM64_UNCONDITIONAL_JMP_INST
476
+ RET_INST = ARM64_RET_INST
477
+ else:
478
+ CALL_INST = X86_CALL_INST
479
+ UNCONDITIONAL_JMP_INST = X86_UNCONDITIONAL_JMP_INST
480
+ RET_INST = X86_RET_INST
344
481
  instruction_mnemonics = []
345
482
  instruction_metrics = {
346
483
  "call_count": 0,
@@ -358,15 +495,39 @@ def _analyze_instructions(instr_list, func_addr, next_func_addr_in_sec, instr_ad
358
495
  all_regs_written = set()
359
496
  used_simd_reg_types = set()
360
497
  instructions_with_registers = []
498
+ sorted_arch_regs = get_arch_reg_set(arch_target)
499
+ proprietary_instr_found = set()
500
+ sreg_interactions = set()
501
+ is_apple_silicon = "aarch64" in arch_target.lower() and isinstance(parsed_obj, lief.MachO.Binary)
361
502
  for instr in instr_list:
362
503
  instr_assembly = instr.assembly
363
- mnemonic = instr.assembly.split(None, 1)[0].lower()
504
+ parts = instr_assembly.split()
505
+ if is_apple_silicon and len(instr.bytes) == 4:
506
+ opcode = int.from_bytes(instr.bytes, 'little')
507
+ for name, (start, end) in APPLE_PROPRIETARY_INSTRUCTION_RANGES.items():
508
+ if start <= opcode <= end:
509
+ proprietary_instr_found.add(name)
510
+ break
511
+ mnemonic_and_operands = instr_assembly.split(None, 1)
512
+ mnemonic = mnemonic_and_operands[0].lower()
513
+ if is_apple_silicon and mnemonic in ('mrs', 'msr') and len(parts) > 1:
514
+ operands_str = mnemonic_and_operands[1]
515
+ operands = [op.strip().lower() for op in operands_str.split(',')]
516
+ sreg_operand = None
517
+ try:
518
+ if mnemonic == 'mrs':
519
+ sreg_operand = operands[1]
520
+ elif mnemonic == 'msr':
521
+ sreg_operand = operands[0]
522
+ except IndexError:
523
+ pass
524
+ if sreg_operand and sreg_operand in _SREG_TO_CATEGORY_MAP:
525
+ sreg_interactions.add(_SREG_TO_CATEGORY_MAP[sreg_operand])
364
526
  instruction_mnemonics.append(mnemonic)
365
- if mnemonic == 'call':
527
+ if mnemonic in CALL_INST:
366
528
  instruction_metrics["call_count"] += 1
367
529
  elif mnemonic in CONDITIONAL_JMP_INST:
368
530
  instruction_metrics["conditional_jump_count"] += 1
369
- parts = instr_assembly.split()
370
531
  if len(parts) >= 2:
371
532
  target_part = parts[1]
372
533
  if target_part.startswith('0x'):
@@ -376,43 +537,50 @@ def _analyze_instructions(instr_list, func_addr, next_func_addr_in_sec, instr_ad
376
537
  has_loop = True
377
538
  except ValueError:
378
539
  continue
540
+ elif mnemonic in UNCONDITIONAL_JMP_INST:
541
+ instruction_metrics["jump_count"] += 1
379
542
  elif mnemonic == 'xor':
380
543
  instruction_metrics["xor_count"] += 1
381
544
  elif mnemonic in SHIFT_INST:
382
545
  instruction_metrics["shift_count"] += 1
383
546
  elif mnemonic in ARITH_INST:
384
547
  instruction_metrics["arith_count"] += 1
385
- elif mnemonic == 'ret':
548
+ elif mnemonic in RET_INST:
386
549
  instruction_metrics["ret_count"] += 1
387
- elif mnemonic in ['jmp', 'jmpq', 'jmpl']:
388
- instruction_metrics["jump_count"] += 1
389
- if instr_assembly.startswith(('call ', 'jmp ')):
390
- parts = instr_assembly.split(None, 1)
550
+ # Check for ARM64 indirect calls and jumps
551
+ if mnemonic in (CALL_INST | UNCONDITIONAL_JMP_INST):
552
+ is_indirect = False
391
553
  if len(parts) > 1:
392
554
  operand = parts[1].lower().strip()
393
- if operand.startswith('[') and operand.endswith(']'):
394
- has_indirect_call = True
395
- elif any(operand.startswith(reg) for reg in SORTED_ALL_REGS):
396
- if operand.isalnum() or '_' in operand:
397
- has_indirect_call = True
398
- regs_read, regs_written = _extract_register_usage(instr_assembly, parsed_obj, arch_target)
555
+ if any(operand.startswith(reg) for reg in sorted_arch_regs) and (operand.isalnum() or '_' in operand):
556
+ is_indirect = True
557
+ elif '[' in operand and ']' in operand:
558
+ is_indirect = True
559
+ if is_indirect:
560
+ has_indirect_call = True
561
+ regs_read, regs_written = _extract_register_usage(instr_assembly, parsed_obj, arch_target, sorted_arch_regs)
399
562
  all_instr_regs = set(regs_read) | set(regs_written)
400
563
  is_simd_fpu = False
401
- if any(reg in FPU_REGS for reg in all_instr_regs):
402
- used_simd_reg_types.add("FPU")
403
- is_simd_fpu = True
404
- if any(reg in MMX_REGS for reg in all_instr_regs):
405
- used_simd_reg_types.add("MMX")
406
- is_simd_fpu = True
407
- if any(reg in XMM_REGS for reg in all_instr_regs):
408
- used_simd_reg_types.add("SSE/AVX")
409
- is_simd_fpu = True
410
- if any(reg in YMM_REGS for reg in all_instr_regs):
411
- used_simd_reg_types.add("AVX/AVX2")
412
- is_simd_fpu = True
413
- if any(reg in ZMM_REGS for reg in all_instr_regs):
414
- used_simd_reg_types.add("AVX-512")
415
- is_simd_fpu = True
564
+ if "aarch64" in arch_target.lower() or "arm64" in arch_target.lower():
565
+ if any(reg in ARM64_VFP_NEON_REGS for reg in all_instr_regs):
566
+ used_simd_reg_types.add("NEON/VFP")
567
+ is_simd_fpu = True
568
+ else:
569
+ if any(reg in FPU_REGS for reg in all_instr_regs):
570
+ used_simd_reg_types.add("FPU")
571
+ is_simd_fpu = True
572
+ if any(reg in MMX_REGS for reg in all_instr_regs):
573
+ used_simd_reg_types.add("MMX")
574
+ is_simd_fpu = True
575
+ if any(reg in XMM_REGS for reg in all_instr_regs):
576
+ used_simd_reg_types.add("SSE/AVX")
577
+ is_simd_fpu = True
578
+ if any(reg in YMM_REGS for reg in all_instr_regs):
579
+ used_simd_reg_types.add("AVX/AVX2")
580
+ is_simd_fpu = True
581
+ if any(reg in ZMM_REGS for reg in all_instr_regs):
582
+ used_simd_reg_types.add("AVX-512")
583
+ is_simd_fpu = True
416
584
  if is_simd_fpu:
417
585
  instruction_metrics["simd_fpu_count"] += 1
418
586
  all_regs_read.update(regs_read)
@@ -423,12 +591,12 @@ def _analyze_instructions(instr_list, func_addr, next_func_addr_in_sec, instr_ad
423
591
  })
424
592
  instruction_metrics["unique_regs_read_count"] = len(all_regs_read)
425
593
  instruction_metrics["unique_regs_written_count"] = len(all_regs_written)
426
- return instruction_metrics, instruction_mnemonics, has_indirect_call, has_loop, list(all_regs_read), list(all_regs_written), instructions_with_registers, list(used_simd_reg_types)
594
+ return instruction_metrics, instruction_mnemonics, has_indirect_call, has_loop, sorted(all_regs_read), sorted(all_regs_written), instructions_with_registers, sorted(used_simd_reg_types), sorted(proprietary_instr_found), sorted(sreg_interactions)
427
595
 
428
596
  def _build_addr_to_name_map(metadata):
429
597
  """Builds a lookup map from address (int) to name from metadata functions."""
430
598
  addr_to_name_map = {}
431
- for func_list_key in ["functions", "ctor_functions", "exception_functions", "unwind_functions", "exports"]:
599
+ for func_list_key in ("functions", "ctor_functions", "exception_functions", "unwind_functions", "exports", "imports", "symtab_symbols", "dynamic_symbols"):
432
600
  for func_entry in metadata.get(func_list_key, []):
433
601
  addr_str = func_entry.get("address", "")
434
602
  name = func_entry.get("name", "")
@@ -440,37 +608,57 @@ def _build_addr_to_name_map(metadata):
440
608
  continue
441
609
  return addr_to_name_map
442
610
 
443
- def _resolve_direct_calls(instr_list, addr_to_name_map):
611
+ def _resolve_direct_calls(instr_list, addr_to_name_map, arch_target=""):
444
612
  """Identifies direct calls in instructions and resolves target addresses to function names.
445
613
  Handles both immediate absolute addresses (0x...) and relative offsets."""
446
614
  potential_callees = []
615
+ is_aarch64 = "aarch64" in arch_target.lower() or "arm64" in arch_target.lower()
447
616
  for instr in instr_list:
448
617
  instr_assembly = instr.assembly
449
- if instr_assembly.startswith('call '):
450
- parts = instr_assembly.split(None, 1)
451
- if len(parts) > 1:
452
- operand = parts[1]
453
- target_addr = None
618
+ parts = instr_assembly.split(None, 1)
619
+ if not parts:
620
+ continue
621
+ mnemonic = parts[0].lower()
622
+ is_direct_call = False
623
+ if is_aarch64 and mnemonic == 'bl':
624
+ is_direct_call = True
625
+ elif not is_aarch64 and mnemonic == 'call':
626
+ is_direct_call = True
627
+ if is_direct_call and len(parts) > 1:
628
+ operand = parts[1]
629
+ target_addr = None
630
+ try:
454
631
  if operand.startswith('0x'):
455
- try:
456
- target_addr = int(operand, 16)
457
- except ValueError:
458
- continue
459
- elif operand.isdigit():
460
- target_addr = operand
461
- elif operand.startswith(('+', '-')):
462
- offset = int(operand, 10)
463
- target_addr = instr.address + offset
464
- if target_addr is not None:
465
- target_name = addr_to_name_map.get(target_addr)
466
- if target_name:
467
- potential_callees.append(target_name)
632
+ target_addr = int(operand, 16)
633
+ elif operand.startswith('#'):
634
+ offset = int(operand.lstrip('#'))
635
+ target_addr = instr.address + offset
636
+ elif operand.isdigit() or operand.startswith(('+', '-')):
637
+ offset = int(operand)
638
+ target_addr = instr.address + len(instr.bytes) + offset
639
+ except (ValueError, IndexError):
640
+ continue
641
+ if target_addr is not None:
642
+ target_name = addr_to_name_map.get(target_addr)
643
+ if target_name:
644
+ potential_callees.append(target_name)
468
645
  return potential_callees
469
646
 
470
647
  def _classify_function(instruction_metrics, instruction_count, plain_assembly_text, has_system_call, has_indirect_call):
471
648
  """Classifies the function based on metrics and other flags."""
472
649
  function_type = ""
473
- if instruction_metrics["jump_count"] > 0 and instruction_count <= 5 and all(mnem in ['jmp', 'push', 'sub'] for mnem in [i.split(None, 1)[0].lower() for i in plain_assembly_text.split('\n') if i.strip()]):
650
+ if (
651
+ instruction_metrics["jump_count"] > 0
652
+ and instruction_count <= 5
653
+ and all(
654
+ mnem in ("jmp", "push", "sub")
655
+ for mnem in [
656
+ i.split(None, 1)[0].lower()
657
+ for i in plain_assembly_text.split("\n")
658
+ if i.strip()
659
+ ]
660
+ )
661
+ ):
474
662
  function_type = "PLT_Thunk"
475
663
  elif instruction_count == 1 and instruction_metrics["ret_count"] == 1:
476
664
  function_type = "Simple_Return"
@@ -603,8 +791,8 @@ def disassemble_functions(parsed_obj, metadata, arch_target="", cpu="", features
603
791
  assembly_hash = hashlib.sha256(plain_assembly_text.encode('utf-8')).hexdigest()
604
792
  instruction_count = len(truncated_instr_list)
605
793
  instr_addresses = [instr.address for instr in truncated_instr_list]
606
- instruction_metrics, instruction_mnemonics, has_indirect_call, has_loop, regs_read, regs_written, instructions_with_registers, used_simd_reg_types = _analyze_instructions(truncated_instr_list, func_addr, func_addr + size_to_disasm, instr_addresses, parsed_obj, arch_target)
607
- direct_calls = _resolve_direct_calls(truncated_instr_list, addr_to_name_map)
794
+ instruction_metrics, instruction_mnemonics, has_indirect_call, has_loop, regs_read, regs_written, instructions_with_registers, used_simd_reg_types, proprietary_instructions, sreg_interactions = _analyze_instructions(truncated_instr_list, func_addr, func_addr + size_to_disasm, instr_addresses, parsed_obj, arch_target)
795
+ direct_calls = _resolve_direct_calls(truncated_instr_list, addr_to_name_map, arch_target)
608
796
  joined_mnemonics = "\n".join(instruction_mnemonics)
609
797
  instruction_hash = hashlib.sha256(joined_mnemonics.encode('utf-8')).hexdigest()
610
798
  has_system_call = any(syscall_pattern in lower_assembly for syscall_pattern in SYSCALL_INDICATORS)
@@ -631,7 +819,9 @@ def disassemble_functions(parsed_obj, metadata, arch_target="", cpu="", features
631
819
  "regs_written": regs_written,
632
820
  "used_simd_reg_types": used_simd_reg_types,
633
821
  "instructions_with_registers": instructions_with_registers,
634
- "function_type": function_type
822
+ "function_type": function_type,
823
+ "proprietary_instructions": proprietary_instructions,
824
+ "sreg_interactions": sreg_interactions
635
825
  }
636
826
  if inst_count == 0:
637
827
  num_success += 1
@@ -682,3 +682,7 @@ def json_serializer(obj):
682
682
  return ""
683
683
 
684
684
  return obj
685
+
686
+ def enum_to_str(enum_obj) -> str:
687
+ """Converts a lief enum object to its string name."""
688
+ return str(enum_obj).rsplit(".", maxsplit=1)[-1]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "blint"
3
- version = "3.0.1"
3
+ version = "3.0.2"
4
4
  description = "Linter and SBOM generator for binary files."
5
5
  authors = [
6
6
  {name= "Team AppThreat", email = "cloud@appthreat.com"},
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes