-
Notifications
You must be signed in to change notification settings - Fork 28
/
binary.py
1512 lines (1347 loc) · 58.3 KB
/
binary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=too-many-lines,consider-using-f-string
import codecs
import contextlib
import sys
from typing import Tuple
import zlib
import orjson
import lief
from blint.logger import DEBUG, LOG
from blint.utils import calculate_entropy, check_secret, cleanup_dict_lief_errors, decode_base64
SYMBOLIC_FOUND = True
try:
from symbolic._lowlevel import ffi, lib
from symbolic.utils import encode_str, decode_str, rustcall
except OSError:
SYMBOLIC_FOUND = False
MIN_ENTROPY = 0.39
MIN_LENGTH = 80
# Enable lief logging in debug mode
if LOG.level != DEBUG:
lief.logging.disable()
ADDRESS_FMT = "0x{:<10x}"
def demangle_symbolic_name(symbol, lang=None, no_args=False):
"""Demangles symbol using llvm demangle falling back to some heuristics. Covers legacy rust."""
if not SYMBOLIC_FOUND:
return symbol
try:
func = lib.symbolic_demangle_no_args if no_args else lib.symbolic_demangle
lang_str = encode_str(lang) if lang else ffi.NULL
demangled = rustcall(func, encode_str(symbol), lang_str)
demangled_symbol = decode_str(demangled, free=True).strip()
# demangling didn't work
if symbol and symbol == demangled_symbol:
for ign in ("__imp_anon.", "anon.", ".L__unnamed"):
if symbol.startswith(ign):
return "anonymous"
if symbol.startswith("GCC_except_table"):
return "GCC_except_table"
if symbol.startswith("@feat.00"):
return "SAFESEH"
if (
symbol.startswith("__imp_")
or symbol.startswith(".rdata$")
or symbol.startswith(".refptr.")
):
symbol = f"__declspec(dllimport) {symbol.removeprefix('__imp_').removeprefix('.rdata$').removeprefix('.refptr.')}"
demangled_symbol = (
symbol.replace("..", "::")
.replace("$SP$", "@")
.replace("$BP$", "*")
.replace("$LT$", "<")
.replace("$u5b$", "[")
.replace("$u7b$", "{")
.replace("$u3b$", ";")
.replace("$u20$", " ")
.replace("$u5d$", "]")
.replace("$u7d$", "}")
.replace("$GT$", ">")
.replace("$RF$", "&")
.replace("$LP$", "(")
.replace("$RP$", ")")
.replace("$C$", ",")
.replace("$u27$", "'")
)
# In case of rust symbols, try and trim the hash part from the end of the symbols
if demangled_symbol.count("::") > 2:
last_part = demangled_symbol.split("::")[-1]
if len(last_part) == 17:
demangled_symbol = demangled_symbol.removesuffix(f"::{last_part}")
return demangled_symbol
except AttributeError:
return symbol
def is_shared_library(parsed_obj):
"""
Checks if the given parsed binary object represents a shared library.
Args:
parsed_obj: The parsed binary object to be checked.
Returns:
bool: True if the parsed object represents a shared library.
"""
if not parsed_obj:
return False
if parsed_obj.format == lief.Binary.FORMATS.ELF:
return parsed_obj.header.file_type == lief.ELF.E_TYPE.DYNAMIC
if parsed_obj.format == lief.Binary.FORMATS.PE:
return parsed_obj.header.has_characteristic(lief.PE.Header.CHARACTERISTICS.DLL)
if parsed_obj.format == lief.Binary.FORMATS.MACHO:
return parsed_obj.header.file_type == lief.MachO.FILE_TYPES.DYLIB
return False
def parse_notes(parsed_obj):
"""
Parses the notes from the given parsed binary object.
Args:
parsed_obj: The parsed binary object containing the notes.
Returns:
list[dict]: A list of metadata dictionaries, each representing a note.
Note:
- The description is truncated to 16 words and appended with "..." if
it exceeds 16 words.
"""
data = []
notes = parsed_obj.notes
if isinstance(notes, lief.lief_errors):
return data
data += [extract_note_data(idx, note) for idx, note in enumerate(notes)]
return data
def extract_note_data(idx, note):
"""
Extracts metadata from a note object and returns a dictionary.
Args:
idx (int): The index of the note.
note: The note object to extract data from.
Returns:
dict: A dictionary containing the extracted metadata
"""
note_str = ""
build_id = ""
if note.type == lief.ELF.Note.TYPE.GNU_BUILD_ID:
note_str = str(note)
if "ID Hash" in note_str:
build_id = note_str.rsplit("ID Hash:", maxsplit=1)[-1].strip()
description = note.description
description_str = " ".join(map(integer_to_hex_str, description[:64]))
if len(description) > 64:
description_str += " ..."
if note.type == lief.ELF.Note.TYPE.GNU_BUILD_ID:
build_id = description_str.replace(" ", "")
type_str = note.type
type_str = str(type_str).rsplit(".", maxsplit=1)[-1]
note_details = ""
sdk_version = ""
ndk_version = ""
ndk_build_number = ""
abi = ""
version_str = ""
if type_str == "ANDROID_IDENT":
sdk_version = note.sdk_version
ndk_version = note.ndk_version
ndk_build_number = note.ndk_build_number
elif type_str.startswith("GNU_ABI_TAG"):
version = [str(i) for i in note.version]
version_str = ".".join(version)
else:
with contextlib.suppress(AttributeError):
note_details = note.details
version = note_details.version
abi = str(note_details.abi)
version_str = f"{version[0]}.{version[1]}.{version[2]}"
if not version_str and build_id:
version_str = build_id
return {
"index": idx,
"description": description_str,
"type": type_str,
"details": note_details,
"sdk_version": sdk_version,
"ndk_version": ndk_version,
"ndk_build_number": ndk_build_number,
"abi": abi,
"version": version_str,
"build_id": build_id,
}
def integer_to_hex_str(e):
"""
Converts an integer to a hexadecimal string representation.
Args:
e: The integer to be converted.
Returns:
The hexadecimal string representation of the integer.
"""
return "{:02x}".format(e)
def parse_relro(parsed_obj):
"""
Determines the Relocation Read-Only (RELRO) protection level.
Args:
parsed_obj: The parsed binary object to analyze.
Returns:
str: The RELRO protection level of the binary object.
"""
test_stmt = parsed_obj.get(lief.ELF.SEGMENT_TYPES.GNU_RELRO)
if isinstance(test_stmt, lief.lief_errors):
return "no"
dynamic_tags = parsed_obj.get(lief.ELF.DYNAMIC_TAGS.FLAGS)
bind_now, now = False, False
if dynamic_tags and not isinstance(dynamic_tags, lief.lief_errors):
bind_now = lief.ELF.DYNAMIC_FLAGS.BIND_NOW in dynamic_tags
dynamic_tags = parsed_obj.get(lief.ELF.DYNAMIC_TAGS.FLAGS_1)
if dynamic_tags and not isinstance(dynamic_tags, lief.lief_errors):
now = lief.ELF.DYNAMIC_FLAGS_1.NOW in dynamic_tags
return "full" if bind_now or now else "partial"
def parse_functions(functions):
"""
Parses a list of functions and returns a list of dictionaries.
Args:
functions (list): A list of function objects to parse.
Returns:
list[dict]: A list of function dictionaries
"""
func_list = []
with contextlib.suppress(AttributeError, TypeError):
LOG.debug("Parsing functions")
for idx, f in enumerate(functions):
if f.name and f.address:
cleaned_name = demangle_symbolic_name(f.name)
func_list.append(
{
"index": idx,
"name": cleaned_name,
"address": ADDRESS_FMT.format(f.address).strip(),
}
)
return func_list
def parse_strings(parsed_obj):
"""
Parse strings from a parsed object.
Args:
parsed_obj: The parsed object from which to extract strings.
Returns:
list: A list of dictionaries with keys: value, entropy, secret type
"""
strings_list = []
with contextlib.suppress(AttributeError):
LOG.debug("Parsing strings")
strings = parsed_obj.strings
if isinstance(strings, lief.lief_errors):
return strings_list
for s in strings:
try:
if s and "[]" not in s and "{}" not in s:
entropy = calculate_entropy(s)
secret_type = check_secret(s)
if (entropy and (entropy > MIN_ENTROPY or len(s) > MIN_LENGTH)) or secret_type:
strings_list.append(
{
"value": (decode_base64(s) if s.endswith("==") else s),
"entropy": entropy,
"secret_type": secret_type,
}
)
except (AttributeError, TypeError):
continue
return strings_list
def parse_symbols(symbols):
"""
Parse symbols from a list of symbols.
Args:
symbols (it_symbols): A list of symbols to parse.
Returns:
tuple[list[dict], str]: A tuple containing the symbols_list and exe_type
"""
symbols_list = []
exe_type = ""
LOG.debug("Parsing symbols")
for symbol in symbols:
try:
symbol_version = symbol.symbol_version if symbol.has_version else ""
is_imported = False
is_exported = False
if symbol.imported and not isinstance(symbol.imported, lief.lief_errors):
is_imported = True
if symbol.exported and not isinstance(symbol.exported, lief.lief_errors):
is_exported = True
symbol_name = symbol.demangled_name
if isinstance(symbol_name, lief.lief_errors):
symbol_name = demangle_symbolic_name(symbol.name)
else:
symbol_name = demangle_symbolic_name(symbol_name)
exe_type = guess_exe_type(symbol_name)
symbols_list.append(
{
"name": symbol_name,
"type": str(symbol.type).rsplit(".", maxsplit=1)[-1],
"value": symbol.value,
"visibility": str(symbol.visibility).rsplit(".", maxsplit=1)[-1],
"binding": str(symbol.binding).rsplit(".", maxsplit=1)[-1],
"is_imported": is_imported,
"is_exported": is_exported,
"information": symbol.information,
"is_function": symbol.is_function,
"is_static": symbol.is_static,
"is_variable": symbol.is_variable,
"version": str(symbol_version),
}
)
except (AttributeError, IndexError, TypeError):
continue
return symbols_list, exe_type
def detect_exe_type(parsed_obj, metadata):
"""
Detects the type of the parsed binary object based on its characteristics
and metadata.
Args:
parsed_obj: The parsed binary object to analyze.
metadata (dict): The metadata dictionary containing binary information.
Returns:
str: The detected type of the binary.
"""
with contextlib.suppress(AttributeError, TypeError):
if parsed_obj.has_section(".note.go.buildid"):
return "gobinary"
if (
parsed_obj.has_section(".note.gnu.build-id")
or "musl" in metadata.get("interpreter")
or "ld-linux" in metadata.get("interpreter")
):
return "genericbinary"
if metadata.get("machine_type") and metadata.get("file_type"):
return f'{metadata.get("machine_type")}-{metadata.get("file_type")}'.lower()
if metadata["relro"] in ("partial", "full"):
return "genericbinary"
return ""
def guess_exe_type(symbol_name):
"""
Guess the executable type based on the symbol name.
Args:
symbol_name (str): The name of the symbol.
Returns:
str: The guessed executable type based on the symbol name.
"""
exe_type = ""
if "golang" in symbol_name or "_cgo_" in symbol_name:
exe_type = "gobinary"
if "_rust_" in symbol_name:
exe_type = "genericbinary"
if "DotNetRuntimeInfo" in symbol_name:
exe_type = "dotnetbinary"
return exe_type
def parse_pe_data(parsed_obj):
"""
Parses the data directories from the given parsed PE binary object.
Args:
parsed_obj: The parsed PE binary object to extract from.
Returns:
list[dict]: A list of dictionaries, each representing a data directory.
"""
data_list = []
LOG.debug("Parsing data dictionaries")
data_directories = parsed_obj.data_directories
if not data_directories or isinstance(data_directories, lief.lief_errors):
return data_list
for directory in data_directories:
section_name = ""
section_chars = ""
section_entropy = ""
dir_type = str(directory.type).rsplit(".", maxsplit=1)[-1]
if not dir_type.startswith("?") and directory.size:
if directory.has_section:
if directory.section.has_characteristic:
section_chars = ", ".join(
[
str(chara).rsplit(".", maxsplit=1)[-1]
for chara in directory.section.characteristics_lists
]
)
section_name = directory.section.name
section_entropy = directory.section.entropy
data_list.append(
{
"name": section_name,
"type": dir_type,
"rva": directory.rva,
"size": directory.size,
"section_characteristics": section_chars,
"section_entropy": section_entropy,
}
)
return data_list
def process_pe_resources(parsed_obj):
"""
Processes the resources of the parsed PE (Portable Executable) binary object
and returns metadata about the resources.
Args:
parsed_obj: The parsed PE binary object to process the resources from.
Returns:
dict: A dictionary containing metadata about the resources
"""
LOG.debug("Parsing PE resources")
rm = parsed_obj.resources_manager
if not rm or isinstance(rm, lief.lief_errors):
return {}
resources = {}
version_metadata = {}
version_info: lief.PE.ResourceVersion = rm.version if rm.has_version else None
if version_info and version_info.has_string_file_info:
string_file_info: lief.PE.ResourceStringFileInfo = version_info.string_file_info
for lc_item in string_file_info.langcode_items:
if lc_item.items:
version_metadata.update(lc_item.items)
try:
resources = {
"has_accelerator": rm.has_accelerator,
"has_dialogs": rm.has_dialogs,
"has_html": rm.has_html,
"has_icons": rm.has_icons,
"has_manifest": rm.has_manifest,
"has_string_table": rm.has_string_table,
"has_version": rm.has_version,
"manifest": (rm.manifest.replace("\\xef\\xbb\\xbf", "") if rm.has_manifest else None),
"version_info": str(rm.version) if rm.has_version else None,
"html": rm.html if rm.has_html else None,
}
if version_metadata:
resources["version_metadata"] = version_metadata
except (AttributeError, UnicodeError):
return resources
return resources
def process_pe_signature(parsed_obj):
"""
Processes the signatures of the parsed PE (Portable Executable) binary
object and returns information about the signatures.
Args:
parsed_obj: The parsed PE binary object to process the signatures from.
Returns:
list[dict]: A list of dictionaries containing signatures info.
"""
signature_list = []
with contextlib.suppress(AttributeError, TypeError, KeyError):
for sig in parsed_obj.signatures:
ci = sig.content_info
signature_obj = {
"version": sig.version,
"digest_algorithm": str(sig.digest_algorithm),
"content_info": {
"content_type": lief.PE.oid_to_string(ci.content_type),
"digest_algorithm": str(ci.digest_algorithm),
"digest": ci.digest.hex(),
},
}
signers_list = []
for signer in sig.signers:
signer_obj = {
"version": signer.version,
"serial_number": signer.serial_number.hex(),
"issuer": str(signer.issuer),
"digest_algorithm": str(signer.digest_algorithm),
"encryption_algorithm": str(signer.encryption_algorithm),
"encrypted_digest": signer.encrypted_digest.hex(),
}
signers_list.append(signer_obj)
signature_obj["signers"] = signers_list
signature_list.append(signature_obj)
return signature_list
def parse_pe_authenticode(parsed_obj):
"""
Parses the Authenticode information from the given parsed PE.
Args:
parsed_obj: The parsed PE binary object to extract.
Returns:
dict: A dictionary containing the Authenticode information
"""
try:
LOG.debug("Parsing authentihash")
sep = ":" if sys.version_info.minor > 7 else ()
authenticode = {
"md5_hash": parsed_obj.authentihash_md5.hex(*sep),
"sha256_hash": parsed_obj.authentihash_sha256.hex(*sep),
"sha512_hash": parsed_obj.authentihash_sha512.hex(*sep),
"sha1_hash": parsed_obj.authentihash(lief.PE.ALGORITHMS.SHA_1).hex(*sep),
"verification_flags": str(parsed_obj.verify_signature()).replace(
"VERIFICATION_FLAGS.", ""
),
}
if signatures := parsed_obj.signatures:
if not isinstance(signatures, lief.lief_errors) and signatures[0].signers:
cert_signer_str = str(parsed_obj.signatures[0].signers[0].cert)
cert_signer_obj = {}
for p in cert_signer_str.split("\n"):
tmp_a = p.split(" : ")
if len(tmp_a) == 2:
tmp_key = tmp_a[0].strip().replace(" ", "_")
if "version" in tmp_key:
tmp_key = "version"
cert_signer_obj[tmp_key] = tmp_a[1].strip()
authenticode["cert_signer"] = cert_signer_obj
return authenticode
except (AttributeError, IndexError, KeyError, TypeError) as e:
LOG.exception(f"Caught {type(e)} while parsing PE authentihash.")
return {}
def parse_pe_symbols(symbols):
"""
Parses the symbols and determines the executable type.
Args:
symbols (list): A list of symbol objects to parse.
Returns:
tuple: A tuple containing two elements:
- symbols_list (list): A list of symbol dictionaries
- exe_type (str): The determined executable type.
"""
LOG.debug("Parsing symbols")
symbols_list = []
exe_type = ""
for symbol in symbols:
if not symbol:
continue
try:
if symbol.section_number <= 0:
section_nb_str = str(lief.PE.SYMBOL_SECTION_NUMBER(symbol.section_number)).rsplit(
".", maxsplit=1
)[-1]
elif symbol.section and symbol.section.name:
section_nb_str = symbol.section.name
else:
section_nb_str = "section<{:d}>".format(symbol.section_number)
except (AttributeError, TypeError) as e:
LOG.debug(f"Caught {type(e)}: {e} while parsing {symbol} PE symbol.")
section_nb_str = ""
try:
if not exe_type:
exe_type = guess_exe_type(symbol.name.lower())
if symbol.name:
symbols_list.append(
{
"name": demangle_symbolic_name(symbol.name),
"value": symbol.value,
"id": section_nb_str,
"base_type": str(symbol.base_type).rsplit(".", maxsplit=1)[-1],
"complex_type": str(symbol.complex_type).rsplit(".", maxsplit=1)[-1],
"storage_class": str(symbol.storage_class).rsplit(".", maxsplit=1)[-1],
}
)
except (IndexError, AttributeError, ValueError) as e:
LOG.debug(f"Caught {type(e)}: {e} while parsing {symbol}.")
except RuntimeError:
pass
return symbols_list, exe_type
def parse_pe_imports(imports):
"""
Parses the imports and returns lists of imported symbols and DLLs.
Args:
imports (it_imports): A list of import objects to parse.
Returns:
tuple: A tuple containing two elements:
- imports_list (list[dict])
- dll_list (list[dict])
"""
LOG.debug("Parsing imports")
imports_list = []
dlls = set()
if not imports or isinstance(imports, lief.lief_errors):
return imports_list, []
for import_ in imports:
try:
entries = import_.entries
except AttributeError:
break
if isinstance(entries, lief.lief_errors):
break
for entry in entries:
try:
if entry.name:
dlls.add(import_.name)
imports_list.append(
{
"name": f"{import_.name}::{demangle_symbolic_name(entry.name)}",
"short_name": demangle_symbolic_name(entry.name),
"data": entry.data,
"iat_value": entry.iat_value,
"hint": entry.hint,
}
)
except AttributeError:
continue
dll_list = [{"name": d, "tag": "NEEDED"} for d in list(dlls)]
return imports_list, dll_list
def parse_pe_exports(exports):
"""
Parses the exports and returns a list of exported symbols.
Args:
exports: The exports object to parse.
Returns:
list[dict]: A list of exported symbol dictionaries.
"""
LOG.debug("Parsing exports")
exports_list = []
if not exports or isinstance(exports, lief.lief_errors):
return exports_list
if not (entries := exports.entries) or isinstance(exports.entries, lief.lief_errors):
return exports_list
for entry in entries:
metadata = {}
extern = "[EXTERN]" if entry.is_extern else ""
if entry.name:
metadata = {
"name": demangle_symbolic_name(entry.name),
"ordinal": entry.ordinal,
"address": ADDRESS_FMT.format(entry.address),
"extern": extern,
}
fwd = entry.forward_information if entry.is_forwarded else None
metadata["is_forwarded"] = entry.is_forwarded
if fwd:
metadata["fwd_library"] = fwd.library
metadata["fwd_function"] = fwd.function
if metadata:
exports_list.append(metadata)
return exports_list
def parse_macho_symbols(symbols):
"""
Parses the symbols and determines the executable type.
Args:
symbols (it_symbols): A list of symbol objects to parse.
Returns:
tuple: A tuple containing two elements:
- symbols_list (list): A list of symbol dictionaries.
- exe_type (str): The determined executable type.
"""
LOG.debug("Parsing symbols")
symbols_list = []
exe_type = ""
if not symbols or isinstance(symbols, lief.lief_errors):
return symbols_list, exe_type
for symbol in symbols:
try:
libname = ""
if symbol.has_binding_info and symbol.binding_info.has_library:
libname = symbol.binding_info.library.name
symbol_value = (
symbol.value
if symbol.value > 0 or not symbol.has_binding_info
else ADDRESS_FMT.format(symbol.binding_info.address)
)
symbol_name = symbol.demangled_name
if not symbol_name or isinstance(symbol_name, lief.lief_errors):
symbol_name = demangle_symbolic_name(symbol.name)
else:
symbol_name = demangle_symbolic_name(symbol_name)
if not exe_type:
exe_type = guess_exe_type(symbol_name)
symbols_list.append(
{
"name": (f"{libname}::{symbol_name}" if libname else symbol_name),
"short_name": symbol_name,
"type": symbol.type,
"num_sections": symbol.numberof_sections,
"description": symbol.description,
"value": symbol_value,
}
)
except (AttributeError, TypeError):
continue
return symbols_list, exe_type
def parse(exe_file): # pylint: disable=too-many-locals,too-many-branches,too-many-statements
"""
Parse the executable using lief and capture the metadata
:param: exe_file Binary file
:return Metadata dict
"""
metadata = {"file_path": exe_file}
try:
parsed_obj = lief.parse(exe_file)
metadata["is_shared_library"] = is_shared_library(parsed_obj)
# ELF Binary
if isinstance(parsed_obj, lief.ELF.Binary):
metadata = add_elf_metadata(exe_file, metadata, parsed_obj)
elif isinstance(parsed_obj, lief.PE.Binary):
# PE
metadata = add_pe_metadata(exe_file, metadata, parsed_obj)
elif isinstance(parsed_obj, lief.MachO.Binary):
metadata = add_mach0_metadata(exe_file, metadata, parsed_obj)
except (AttributeError, TypeError, ValueError) as e:
LOG.exception(f"Caught {type(e)}: {e} while parsing {exe_file}.")
return cleanup_dict_lief_errors(metadata)
def add_elf_metadata(exe_file, metadata, parsed_obj):
"""Adds ELF metadata to the given metadata dictionary.
Args:
exe_file (str): The path of the executable file.
metadata (dict): The dictionary to store the metadata.
parsed_obj: The parsed object representing the ELF binary.
Returns:
dict: The updated metadata dictionary.
"""
metadata["binary_type"] = "ELF"
header = parsed_obj.header
identity = header.identity
metadata["magic"] = ("{:<02x} " * 8).format(*identity[:8]).strip()
metadata = add_elf_header(header, metadata)
metadata["name"] = exe_file
metadata["imagebase"] = parsed_obj.imagebase
metadata["interpreter"] = parsed_obj.interpreter
metadata["is_pie"] = parsed_obj.is_pie
metadata["virtual_size"] = parsed_obj.virtual_size
metadata["has_nx"] = parsed_obj.has_nx
metadata["relro"] = parse_relro(parsed_obj)
metadata["exe_type"] = detect_exe_type(parsed_obj, metadata)
# Canary check
canary_sections = ["__stack_chk_fail", "__intel_security_cookie"]
for section in canary_sections:
if parsed_obj.get_symbol(section):
if isinstance(parsed_obj.get_symbol(section), lief.lief_errors):
metadata["has_canary"] = False
else:
metadata["has_canary"] = True
break
# rpath check
rpath = parsed_obj.get(lief.ELF.DYNAMIC_TAGS.RPATH)
if isinstance(rpath, lief.lief_errors):
metadata["has_rpath"] = False
elif rpath:
metadata["has_rpath"] = True
# runpath check
runpath = parsed_obj.get(lief.ELF.DYNAMIC_TAGS.RUNPATH)
if isinstance(runpath, lief.lief_errors):
metadata["has_runpath"] = False
elif runpath:
metadata["has_runpath"] = True
# This is getting renamed to symtab_symbols in lief 0.15.0
static_symbols = parsed_obj.static_symbols
metadata["static"] = bool(static_symbols and not isinstance(static_symbols, lief.lief_errors))
dynamic_entries = parsed_obj.dynamic_entries
metadata = add_elf_dynamic_entries(dynamic_entries, metadata)
metadata = add_elf_symbols(metadata, parsed_obj)
metadata["notes"] = parse_notes(parsed_obj)
metadata["strings"] = parse_strings(parsed_obj)
metadata["symtab_symbols"], exe_type = parse_symbols(static_symbols)
if exe_type:
metadata["exe_type"] = exe_type
metadata["dynamic_symbols"], exe_type = parse_symbols(parsed_obj.dynamic_symbols)
if exe_type:
metadata["exe_type"] = exe_type
metadata["functions"] = parse_functions(parsed_obj.functions)
metadata["ctor_functions"] = parse_functions(parsed_obj.ctor_functions)
metadata["dotnet_dependencies"] = parse_overlay(parsed_obj)
metadata["go_dependencies"], metadata["go_formulation"] = parse_go_buildinfo(parsed_obj)
metadata["rust_dependencies"] = parse_rust_buildinfo(parsed_obj)
return metadata
def add_elf_header(header, metadata):
"""Adds ELF header data to the metadata dictionary.
Args:
header: The ELF header.
metadata: The dictionary to store the metadata.
Returns:
The updated metadata dictionary.
"""
if not header or isinstance(header, lief.lief_errors):
return metadata
try:
eflags_str = determine_elf_flags(header)
metadata["class"] = str(header.identity_class).rsplit(".", maxsplit=1)[-1]
metadata["endianness"] = str(header.identity_data).rsplit(".", maxsplit=1)[-1]
metadata["identity_version"] = str(header.identity_version).rsplit(".", maxsplit=1)[-1]
metadata["identity_os_abi"] = str(header.identity_os_abi).rsplit(".", maxsplit=1)[-1]
metadata["identity_abi_version"] = header.identity_abi_version
metadata["file_type"] = str(header.file_type).rsplit(".", maxsplit=1)[-1]
metadata["machine_type"] = str(header.machine_type).rsplit(".", maxsplit=1)[-1]
metadata["object_file_version"] = str(header.object_file_version).rsplit(".", maxsplit=1)[
-1
]
metadata["entrypoint"] = header.entrypoint
metadata["processor_flag"] = str(header.processor_flag) + eflags_str
except (AttributeError, TypeError, ValueError) as e:
LOG.debug(f"Caught {type(e)}: {e} while parsing elf headers.")
return metadata
def add_elf_symbols(metadata, parsed_obj):
"""Extracts ELF symbols version information and adds it to the metadata dictionary.
Args:
metadata: The dictionary to store the metadata.
parsed_obj: The parsed object representing the ELF binary.
Returns:
The updated metadata dictionary.
"""
try:
symbols_version = parsed_obj.symbols_version
if symbols_version and not isinstance(symbols_version, lief.lief_errors):
metadata["symbols_version"] = []
symbol_version_auxiliary_cache = {}
for entry in symbols_version:
symbol_version_auxiliary = entry.symbol_version_auxiliary
if symbol_version_auxiliary and not symbol_version_auxiliary_cache.get(
symbol_version_auxiliary.name
):
symbol_version_auxiliary_cache[symbol_version_auxiliary.name] = True
metadata["symbols_version"].append(
{
"name": demangle_symbolic_name(symbol_version_auxiliary.name),
"hash": symbol_version_auxiliary.hash,
"value": entry.value,
}
)
except (AttributeError, TypeError) as e:
LOG.debug(f"Caught {type(e)}: {e} while parsing elf symbols.")
metadata["symbols_version"] = []
return metadata
def add_elf_dynamic_entries(dynamic_entries, metadata):
"""Extracts ELF dynamic entries and adds them to the metadata dictionary.
Args:
dynamic_entries: The dynamic entries of the ELF binary.
metadata: The dictionary to store the metadata.
Returns:
dict: The updated metadata dictionary.
"""
metadata["dynamic_entries"] = []
if isinstance(dynamic_entries, lief.lief_errors):
return metadata
for entry in dynamic_entries:
if entry.tag == lief.ELF.DYNAMIC_TAGS.NULL:
continue
if entry.tag in [
lief.ELF.DYNAMIC_TAGS.SONAME,
lief.ELF.DYNAMIC_TAGS.NEEDED,
lief.ELF.DYNAMIC_TAGS.RUNPATH,
lief.ELF.DYNAMIC_TAGS.RPATH,
]:
metadata["dynamic_entries"].append(
{
"name": demangle_symbolic_name(entry.name),
"tag": str(entry.tag).rsplit(".", maxsplit=1)[-1],
"value": entry.value,
}
)
# Detect dotnet binary
if "netcoredeps" in entry.name:
metadata["exe_type"] = "dotnetbinary"
return metadata
def determine_elf_flags(header):
"""Determines the ELF flags based on the given ELF header.
Args:
header: The ELF header.
Returns:
A string representing the ELF flags.
"""
eflags_str = ""
if header.machine_type == lief.ELF.ARCH.ARM:
eflags_str = " - ".join(
[str(s).rsplit(".", maxsplit=1)[-1] for s in header.arm_flags_list]
)
if header.machine_type in [
lief.ELF.ARCH.MIPS,
lief.ELF.ARCH.MIPS_RS3_LE,
lief.ELF.ARCH.MIPS_X,
]:
eflags_str = " - ".join(
[str(s).rsplit(".", maxsplit=1)[-1] for s in header.mips_flags_list]
)
if header.machine_type == lief.ELF.ARCH.PPC64:
eflags_str = " - ".join(
[str(s).rsplit(".", maxsplit=1)[-1] for s in header.ppc64_flags_list]
)
if header.machine_type == lief.ELF.ARCH.HEXAGON:
eflags_str = " - ".join(
[str(s).rsplit(".", maxsplit=1)[-1] for s in header.hexagon_flags_list]
)
return eflags_str
def parse_overlay(parsed_obj: lief.Binary) -> dict[str, dict]:
"""
Parse the overlay section to extract dotnet dependencies
Args:
parsed_obj (lief.Binary): The parsed object representing the PE binary.
Returns:
dict: Dict representing the deps.json if available.
"""
deps = {}
if hasattr(parsed_obj, "overlay"):
overlay = parsed_obj.overlay
overlay_str = (
codecs.decode(overlay.tobytes(), encoding="utf-8", errors="backslashreplace")
.replace("\0", "")
.replace("\r\n", "")
.replace("\n", "")
.replace(" ", "")
)
if overlay_str.find('{"runtimeTarget') > -1:
start_index = overlay_str.find('{"runtimeTarget')
end_index = overlay_str.rfind("}}}")
if end_index > -1:
overlay_str = overlay_str[start_index : end_index + 3]
try:
# deps should have runtimeTarget, compilationOptions, targets, and libraries
# Use libraries to construct BOM components and targets for the dependency tree
deps = orjson.loads(overlay_str)
except orjson.JSONDecodeError:
pass
return deps
def parse_go_buildinfo(
parsed_obj: lief.Binary,
) -> Tuple[dict[str, dict[str, str]], dict[str, str]]:
"""
Parse the go build info section to extract go dependencies
Args:
parsed_obj (lief.Binary): The parsed object representing the binary.
Returns:
tuple(dict[str, str], dict[str, str]): Tuple representing the dependencies and formulation.
"""
formulation = {}
deps = {}
build_info_str: str = ""
# Look for specific buildinfo sections for ELF and MachO binaries
build_info: lief.Section = None
if isinstance(parsed_obj, lief.ELF.Binary):
build_info = parsed_obj.get_section(".go.buildinfo")
elif isinstance(parsed_obj, lief.MachO.Binary):