-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoptimized_feature_processing_v1.py
More file actions
1708 lines (1383 loc) · 60.1 KB
/
optimized_feature_processing_v1.py
File metadata and controls
1708 lines (1383 loc) · 60.1 KB
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
import asyncio
import hashlib
import ipaddress
import json
import logging
import os
import re
import socket
import subprocess
import sys
import time
from collections import defaultdict
from datetime import datetime
from functools import cache
from pathlib import Path
from typing import Any, Dict, Literal, Optional, Union
from urllib.parse import urlparse
import aiofiles
import censys
import lief
import pandas as pd
import tldextract
import yara
# https://github.com/censys/censys-python
# https://github.com/censys/censys-python
from censys.search import CensysCerts, CensysHosts
from oletools import rtfobj
from oletools.oleid import OleID
from oletools.olevba import VBA_Parser
from PyPDF2 import PdfReader
NON_COMMERCIAL_API_LIMIT = 1000
logger = logging.getLogger(__name__)
logging.basicConfig(
filename="logger_file",
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
exif_tool_path = "bins/exiftool.exe"
floss_executable_path = "bins/floss2.2.exe"
top_500_domains = "data/top_500_domains.csv"
censys_api_id = os.getenv("CENSYS_API_ID")
censys_api_secret = os.getenv("CENSYS_API_SECRET")
censys_certificates = CensysCerts(api_id=censys_api_id, api_secret=censys_api_secret)
censys_hosts = CensysHosts(api_id=censys_api_id, api_secret=censys_api_secret)
def get_first_submission_date(vt_meta: dict[str, Any]):
first_submission_date = vt_meta["attributes"]["first_submission_date"]
return datetime.utcfromtimestamp(first_submission_date)
def extract_ole_features(
metadata: dict[str, Any],
output_directory: str,
filename: str = "oletool_features_updated.json",
) -> None:
"""Extracts the OLE features from a given file and writes them to a JSON file.
Args:
metadata (dict): The metadata of the file.
output_directory (str): The directory to write the JSON file to.
filename (str, optional): The name of the JSON file to write the OLE features to. Defaults to "oletool_features_updated.json".
"""
file_path = os.path.join(output_directory, filename)
if os.path.exists(file_path):
return
ole_features = defaultdict(dict)
sample_hash = os.path.basename(os.path.normpath(output_directory))
file_type = metadata.get("FileType", "")
if not is_supported_file_type(file_type):
logging.info(f"Unsupported file type for {output_directory}.")
return
file_to_process = os.path.join(output_directory, sample_hash)
try:
ole_features[sample_hash] = extract_features_from_file(
file_to_process, file_type=file_type
)
if ole_features[sample_hash]:
write_features_to_file(ole_features, file_path)
except Exception as e:
logging.info(f"Exception occurred for sample {output_directory}: {e}")
if ole_features:
write_features_to_file(ole_features, file_path)
def is_supported_file_type(file_type: str) -> bool:
"""Checks if the file type is supported for OLE feature extraction.
Args:
file_type (str): The file type of the file based on exif.
Returns:
bool: True if the file type is supported, False otherwise.
"""
supported_types = [
"DOC",
"DOCX",
"DOTM",
"PPT",
"PDF",
"RTF",
"XLS",
"XLSX",
"FPX",
"ZIP",
]
return file_type in supported_types
def extract_features_from_file(file: str, file_type: str) -> dict[str, Any]:
"""Extracts features from a file based on its metadata.
Args:
file (str): The path to the file.
file_type (str): The file type of the file based on exif.
Returns:
dict: The features extracted from the file.
"""
features = {}
if file_type == "RTF":
features.update(extract_rtf_features(file))
if file_type == "PDF":
features.update(pdf_feature(file))
if file_type not in ["RTF", "PDF"]:
oid = OleID(file)
indicators = oid.check()
for indicator in indicators:
if isinstance(indicator.value, (bytes, bytearray)):
features[indicator.name] = indicator.value.decode("latin-1")
else:
features[indicator.name] = indicator.value
vba_features = extract_vba_features(file)
for key in vba_features:
features[key] = vba_features.get(key)
return features
def extract_rtf_features(file: str) -> dict[str, str]:
"""Extracts features from an RTF file.
Args:
file (str): The path to the RTF file.
Returns:
dict: The features extracted from the RTF file.
"""
features = {"rtfobject": {}}
for index, orig_len, data in rtfobj.rtf_iter_objects(file):
features["rtfobject"][hex(index)] = f"size {len(data)}"
return features
def extract_vba_features(file: str) -> dict[str, Any]:
"""Extracts VBA features from a file.
Args:
file (str): The path to the file.
Returns:
dict: The VBA features extracted from the file.
"""
vbaparser = VBA_Parser(file)
if not vbaparser.detect_vba_macros():
logging.info(f"The file {file} doesn't have VBA macros.")
return {}
features = {"VBAMacro": defaultdict(list)}
for filename, stream_path, vba_filename, vba_code in vbaparser.extract_macros():
features["VBAMacro"]["Filename"].append(filename)
features["VBAMacro"]["OLEstream"].append(stream_path)
features["VBAMacro"]["VBAfilename"].append(vba_filename)
features["VBAMacro"]["VBAcode"].append(vba_code)
results = vbaparser.analyze_macros()
for kw_type, keyword, description in results:
features["VBAMacro"]["Keyword Types"].append(kw_type)
if features.get("Keyword Found"):
features["Keyword Found"].setdefault(keyword, description)
else:
features["Keyword Found"] = {keyword: description}
features["VBAMacro"].update(
{
"AutoExec keywords": vbaparser.nb_autoexec,
"Suspicious keywords": vbaparser.nb_suspicious,
"IOCs": vbaparser.nb_iocs,
"Hex obfuscated strings": vbaparser.nb_hexstrings,
"Base64 obfuscated strings": vbaparser.nb_base64strings,
"Dridex obfuscated strings": vbaparser.nb_dridexstrings,
"VBA obfuscated strings": vbaparser.nb_vbastrings,
}
)
return features
def write_features_to_file(features, file_path) -> None:
"""Writes the extracted features to a JSON file.
Args:
features (dict): The extracted features.
file_path (str): The path to the JSON file.
"""
with open(file_path, "w+") as f:
json.dump(features, f, indent=4)
def extract_pdf_metadata(reader):
"""Extracts metadata from a PDF file.
Args:
reader (PdfReader): A PdfReader object of the PDF file.
Returns:
dict: A dictionary containing the PDF metadata.
"""
metadata = reader.metadata
return {
"Number of Pages": len(reader.pages),
"Author": getattr(metadata, "author", None),
"Creator": getattr(metadata, "creator", None),
"Producer": getattr(metadata, "producer", None),
"Subject": getattr(metadata, "subject", None),
"Title": getattr(metadata, "title", None),
}
def extract_pdf_text(page):
"""Extracts text from the first page of a PDF file.
Args:
page (PageObject): The first page object of the PDF.
Returns:
str: Extracted text from the first page of the PDF.
"""
try:
return page.extract_text() or "No text found"
except Exception as e:
logging.warning(f"Failed to extract text: {e}")
return "Failed to extract text"
def pdf_feature(file_name):
"""Extracts features from a PDF file including metadata and text from the first page.
Args:
file_name (str): The path to the PDF file.
Returns:
defaultdict: A dictionary containing extracted features and information.
"""
feature_set = defaultdict(dict)
try:
reader = PdfReader(file_name)
first_page = reader.pages[0] if reader.pages else None
if first_page:
feature_set["Page"]["Text"] = extract_pdf_text(first_page)
feature_set["Information"] = extract_pdf_metadata(reader)
except Exception as e:
logging.warning(f"Warning: Exception occurred {e}")
feature_set["Exception"] = str(e)
return feature_set
def get_exiftool_json(
file_path: str, parsing_charset: str = "latin1"
) -> Optional[Union[dict[str, Any], None]]:
"""
Get Exiftool output in JSON format for a given file with a specific charset (Latin-1).
Parameters:
file_path (str): The path to the file.
parsing_charset: What encoding to process the file with
Returns:
dict or None: A dictionary containing the Exiftool information in JSON format,
or None if an error occurs.
"""
try:
exiftool_command = [
exif_tool_path,
"-j",
"-charset",
parsing_charset,
file_path,
]
exiftool_output = subprocess.check_output(
exiftool_command, universal_newlines=True, encoding=parsing_charset
)
exif_data = json.loads(exiftool_output)[0]
return exif_data
except subprocess.CalledProcessError as e:
raise e
logging.debug(f"Error handling output from subprocess: {e}")
return None
except Exception as all_other_exceptions:
raise all_other_exceptions
logging.debug(f"Error running Exiftool: {all_other_exceptions}")
return None
def process_document_file(file_path: str, output_directory: str) -> None:
"""
Process a file to extract OLE features and write them to a JSON file.
Examples:
>>> process_document_file(r"C:/users/randomuser/5aaaaaaaaabbb/5aaaaaaaaabbb", r"C:/users/randomuser/5aaaaaaaaabbb")
>>> process_document_file(r"C:/users/randomuser/6aaa8845ssscc/6aaa8845ssscc", r"C:/users/randomuser/6aaa8845ssscc")
Args:
file_path (str): The path to the file.
output_directory (str): The directory to write the JSON file to.
"""
metadata = get_exiftool_json(file_path)
if metadata:
extract_ole_features(metadata, output_directory)
def process_yara_rule(
file_path: str,
yara_rules_path: str,
output_dir: str,
result_filename: str = "malcatYaraResults.json",
) -> None:
"""
Applies YARA rules to a specified file and saves the matches in a JSON file.
Examples:
>>> process_yara_rule("C:/users/randomuser/5aaaaaaaaabbb/5aaaaaaaaabbb", "yara_rules/malcat.yar", "C:/users/randomuser/5aaaaaaaaabbb")
>>> process_yara_rule("C:/users/randomuser/6aaa8845ssscc/6aaa8845ssscc", "yara_rules/malcat.yar", "C:/users/randomuser/6aaa8845ssscc")
Args:
file_path: Path to the file to be scanned.
yara_rules_path: Path to the YARA rules file.
output_dir: Directory to save the results JSON file to.
result_filename: Name of the JSON file to save the results to. Defaults to "malcatYaraResults.json".
"""
# Compile YARA rules from the specified file path
logging.info(f"Processing Yara rules for {file_path}")
rules = yara.compile(
filepath=yara_rules_path, includes=True, error_on_warning=False
)
try:
matches = rules.match(file_path, timeout=120)
yara_match = {"hash": os.path.basename(os.path.normpath(file_path))}
# Store each match in the dictionary
for match in matches:
yara_match[str(match)] = True
# Determine the path for the results JSON file
result_path = os.path.join(output_dir, result_filename)
# Write the matches to the specified JSON file
with open(result_path, "w+") as f:
json.dump(yara_match, f, indent=4)
except Exception as e:
logging.error(
f"Error extracting the yara rules for the file path {file_path}: {e}"
)
async def process_floss_file(
file_path: str,
output_directory: str,
floss_executable: str = "floss2.2.exe",
out_file_name: str = "flossresults_reduced_7.json",
) -> None:
if not os.path.isfile(file_path):
logging.error(f"File does not exist: {file_path}")
return
if not os.path.exists(output_directory):
os.makedirs(output_directory, exist_ok=True)
path_to_out_file = os.path.join(output_directory, out_file_name)
command = f'powershell {floss_executable} --json -n 7 -o "{path_to_out_file}" --no stack tight decoded -- "{file_path}"'
process = await asyncio.create_subprocess_shell(
command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
try:
stdout, stderr = await process.communicate()
if stderr:
logging.error(f"Error while processing floss on file: {file_path}: {stderr.decode()}")
else:
logging.info(f"Floss processing completed for {file_path}.")
except asyncio.CancelledError:
logging.info(f"Timeout occurred, terminating subprocess for file {file_path}.")
process.terminate() # Try to terminate the process
await process.wait() # Wait for the process to terminate
raise # Propagate the cancellation exception
finally:
if process.returncode is None: # Process is still running
process.kill() # Forcefully kill the process
await process.wait() # Ensure the process has terminated
logging.info(f"Subprocess for {file_path} has been cleaned up.")
def process_exiftool(
file_path: str,
output_directory: str,
encoding: str = "latin1",
output_file_name: str = "exiftool_results.json",
) -> Optional[dict[str, Any]]:
"""
Process a file to extract metadata using Exiftool and write it to a JSON file.
Examples:
>>> process_exiftool(r"C:/users/randomuser/5aaaaaaaaabbb/5aaaaaaaaabbb", r"C:/users/randomuser/5aaaaaaaaabbb")
>>> process_exiftool(r"C:/users/randomuser/6aaa8845ssscc/6aaa8845ssscc", r"C:/users/randomuser/6aaa8845ssscc")
Args:
file_path (str): The path to the file.
output_directory (str): The directory to write the JSON file to.
encoding (str): The encoding to use when processing the file. Defaults to "latin1".
output_file_name (str): The name of the JSON file to write the Exiftool results to. Defaults to "exiftool_results.json".
"""
metadata = get_exiftool_json(file_path, encoding)
if metadata:
write_features_to_file(
metadata, os.path.join(output_directory, output_file_name)
)
return metadata
def from_timestamp_to_date(timestamp: int) -> str:
"""
Converts a timestamp into a printable date string.
Args:
timestamp (int): Timestamp to be converted.
Returns:
str: Formatted date string (e.g., "Jan 01 2019 at 00:00:00").
"""
if not timestamp:
return None
return datetime.utcfromtimestamp(timestamp).strftime("%b %d %Y at %H:%M:%S")
def extract_common_attributes(binary: Any, file_type: str):
"""
Extracts common attributes from the binary file and updates the feature set to include
platform, CPU type, file type, entrypoint, and the number of sections.
This version is compatible with PE, ELF, and Mach-O binary types, accommodating the differences
in their attribute names and structures.
Args:
binary: The binary file being processed, expected to be an instance from lief.
file_type (str): The type of the file (e.g., 'PE', 'ELF', 'MachO').
"""
feature_set = {}
feature_set["Platform"] = file_type
# Handling CPU type variations
cpu_type_attr = (
getattr(binary.header, "cpu_type", None)
or getattr(binary.header, "machine", None)
or getattr(binary.header, "machine_type", None)
)
feature_set["CPU type"] = str(cpu_type_attr) if cpu_type_attr else "Unknown"
# Handling file type if applicable
file_type_attr = getattr(binary.header, "file_type", None)
feature_set["File type"] = str(file_type_attr) if file_type_attr else "Unknown"
# Entrypoint, if available
if hasattr(binary, "entrypoint"):
feature_set["Entrypoint"] = binary.entrypoint
# Number of sections
number_of_sections_attr = getattr(binary.header, "numberof_sections", None)
if number_of_sections_attr is not None:
feature_set["Number of sections"] = number_of_sections_attr
return feature_set
def lief_header(binary, file_type: str) -> dict:
"""
Displays header information for ELF, PE, and Mach-O files.
Args:
binary: The binary file to process.
file_type (str): The type of the binary file.
Returns:
dict: A dictionary containing the extracted features.
"""
feature_set = dict()
if file_type == "machofile":
feature_set.update(extract_macho_attributes(binary))
if file_type in ["EXEfile", "DLLfile"]:
feature_set.update(extract_pe_attributes(binary))
if file_type == "elffile":
feature_set.update(extract_elf_attributes(binary))
if not feature_set:
print("Warning: No header found for the specified file type.")
return feature_set
# Add the common headers
feature_set.update(extract_common_attributes(binary, file_type))
return feature_set
def extract_macho_attributes(binary: lief.MachO.Binary) -> dict:
"""
Extracts Mach-O specific attributes from the binary file.
Args:
binary: The Mach-O binary file to process.
Returns:
A dictionary containing the extracted Mach-O attributes.
"""
feature_set = {}
feature_set["CPU type"] = str(binary.header.cpu_type)
feature_set["File type"] = str(binary.header.file_type)
feature_set["Number of commands"] = binary.header.nb_cmds
feature_set["Size of commands"] = binary.header.sizeof_cmds
feature_set["Flags"] = ":".join(str(flag) for flag in binary.header.flags_list)
return feature_set
def resolve_attribute_value(value: Any) -> Union[dict, list, str, int, float, None]:
"""Attempts to resolve the value of attributes, handling specific types to include names and values in a dict.
Args:
value: The value to resolve.
Returns:
The resolved value, which could be a primitive type, string representation, a dictionary, or a list of dictionaries.
"""
if isinstance(value, (list, set)):
# Handle lists or sets, assuming they contain objects that can be resolved to name-value pairs
return [
{item.name: item.value}
for item in value
if hasattr(item, "name") and hasattr(item, "value")
]
elif hasattr(value, "name") and hasattr(value, "value"):
# Handle single objects that can be resolved to name-value pairs
return {value.name: value.value}
else:
return value
def extract_pe_attributes(binary: lief.PE.Binary) -> dict:
"""Extracts PE specific attributes from the binary file, handling specific complex types.
Args:
binary: The PE binary file to process.
Returns:
A dictionary containing the extracted PE attributes, properly handling complex or enumerable types.
"""
feature_set = {
"Date of compilation": from_timestamp_to_date(binary.header.time_date_stamps),
"Imphash": lief.PE.get_imphash(binary),
}
# Handle optional header specific attributes, resolving complex or enumerable types
if binary.header.sizeof_optional_header > 0:
optional_header_attrs = {}
for key in dir(binary.optional_header):
if not key.startswith("_"): # Skip private attributes
raw_value = getattr(binary.optional_header, key, None)
value = resolve_attribute_value(raw_value)
# Check to ensure the value is serializable (now including dicts and lists of dicts)
if isinstance(value, (str, int, float, dict, list)):
optional_header_attrs[key] = value
feature_set["Optional header"] = optional_header_attrs
return feature_set
def extract_elf_attributes(binary: lief.ELF.Binary) -> dict:
"""
Extracts ELF-specific attributes from an ELF binary file.
Args:
binary: The ELF binary file being processed.
Returns:
A dictionary containing the extracted ELF attributes.
"""
feature_set = {}
# Direct attribute extraction with straightforward mapping
feature_set["Platform"] = "ELF"
feature_set["Magic"] = bytes(binary.header.identity).hex()
feature_set["Type"] = str(binary.header.file_type)
feature_set["Entrypoint"] = hex(binary.header.entrypoint)
feature_set["ImageBase"] = hex(binary.imagebase) if binary.imagebase else "-"
feature_set["Header size"] = binary.header.header_size
feature_set["Endianness"] = str(binary.header.identity_data)
feature_set["Class"] = str(binary.header.identity_class)
feature_set["OS/ABI"] = str(binary.header.identity_os_abi)
feature_set["Version"] = str(binary.header.identity_version)
feature_set["Architecture"] = str(binary.header.machine_type)
# Handling ELF-specific flags, such as MIPS Flags, if applicable
if hasattr(binary.header, "mips_flags_list") and binary.header.mips_flags_list:
mips_flags = ":".join(str(flag) for flag in binary.header.mips_flags_list)
else:
mips_flags = "No flags"
feature_set["MIPS Flags"] = mips_flags
# Additional ELF-specific details
feature_set["Number of sections"] = binary.header.numberof_sections
feature_set["Number of segments"] = binary.header.numberof_segments
feature_set["Program header offset"] = hex(binary.header.program_header_offset)
feature_set["Program header size"] = binary.header.program_header_size
feature_set["Section Header offset"] = hex(binary.header.section_header_offset)
feature_set["Section header size"] = binary.header.section_header_size
return feature_set
def check_binary_format(
binary,
) -> Optional[Literal["DLLfile", "EXEfile", "machofile", "elffile"]]:
"""
Checks the format of a binary file and returns its type as a literal string.
Args:
binary: The binary file to check.
Returns:
Literal['DLLfile', 'EXEfile', 'machofile', 'elffile']: A literal string indicating the type of the binary.
"""
if not binary:
return None
if binary.format == lief.EXE_FORMATS.PE:
if binary.header.characteristics & lief.PE.HEADER_CHARACTERISTICS.DLL:
return "DLLfile"
else:
return "EXEfile"
elif binary.format == lief.EXE_FORMATS.MACHO:
return "machofile"
elif binary.format == lief.EXE_FORMATS.ELF:
return "elffile"
return None
def exported_functions(binary: lief.Binary, file_type: str) -> dict:
"""
Extracts exported functions from ELF, PE, Mach-O binaries.
Args:
binary: The binary file being processed.
file_type: The type of the binary file.
Returns:
A dictionary containing exported functions if any.
"""
feature_set = {"Exported functions": []}
if binary.exported_functions:
for function in binary.exported_functions:
feature_set["Exported functions"].append(str(function.name))
else:
logger.info("Warning: No exported function found")
return feature_set
def imported_functions(binary: lief.Binary, file_type: str) -> dict:
"""
Extracts imported functions from ELF, PE, Mach-O binaries.
Args:
binary: The binary file being processed.
file_type: The type of the binary file.
Returns:
A dictionary containing imported functions if any.
"""
feature_set = {"Imported functions": []}
if binary.imported_functions:
for function in binary.imported_functions:
feature_set["Imported functions"].append(str(function.name))
else:
logger.info("Warning: No imported function found")
return feature_set
def print_elf_symbols(symbols: list, title: str) -> dict:
"""
Formats ELF symbols for display.
Args:
symbols: List of symbols.
title: Title for the display section.
Returns:
A dictionary containing formatted ELF symbols.
"""
feature_set_sub = {
title: {
"Name": [],
}
}
if symbols:
for symbol in symbols:
feature_set_sub[title]["Name"].append(symbol.name)
else:
logger.info(f"Warning: No {title.lower()} found")
return feature_set_sub
def exported_symbols(binary: lief.Binary, file_type: str) -> dict:
"""
Extracts exported symbols from ELF, Mach-O binaries.
Args:
binary: The binary file being processed.
file_type: The type of the binary file.
Returns:
A dictionary containing exported symbols if any.
"""
feature_set = {}
if file_type == "elffile" and binary.exported_symbols:
feature_set = print_elf_symbols(binary.exported_symbols, "Exported symbols")
elif file_type == "machofile" and binary.exported_symbols:
feature_set["Exported symbols"] = {
"Name": [],
}
for symbol in binary.exported_symbols:
feature_set["Exported symbols"]["Name"].append(symbol.name)
else:
logger.info("Warning: No exported symbol found")
return feature_set
def imported_symbols(binary: lief.Binary, file_type: str) -> dict:
"""
Extracts imported symbols from ELF, Mach-O binaries.
Args:
binary: The binary file being processed.
file_type: The type of the binary file.
Returns:
A dictionary containing imported symbols if any.
"""
feature_set = {}
if file_type == "elffile" and binary.imported_symbols:
feature_set = print_elf_symbols(binary.imported_symbols, "Imported symbols")
elif file_type == "machofile" and binary.imported_symbols:
feature_set["Imported symbols"] = {
"Name": [],
"Number of sections": [],
"Value": [],
"Origin": [],
}
for symbol in binary.imported_symbols:
feature_set["Imported symbols"]["Name"].append(symbol.name)
feature_set["Imported symbols"]["Number of sections"].append(
symbol.numberof_sections
)
feature_set["Imported symbols"]["Value"].append(hex(symbol.value))
feature_set["Imported symbols"]["Origin"].append(str(symbol.origin))
else:
logger.info("Warning: No imported symbols found")
return feature_set
def resources(binary: lief.PE.Binary, file_type: str) -> dict:
"""
Extracts PE resources, if any, from the binary.
Args:
binary: The binary file being processed.
file_type: The type of the binary file, expecting 'EXEfile' or 'DLLfile'.
Returns:
A dictionary containing resources information if available.
"""
feature_set = {}
if file_type in ["EXEfile", "DLLfile"] and binary.has_resources:
resource_type = (
"Directory"
if binary.resources.is_directory
else "Data" if binary.resources.is_data else "Unknown"
)
feature_set["Resources"] = {
"Name": binary.resources.name if binary.resources.has_name else "No name",
"Number of childs": len(binary.resources.childs),
"Depth": binary.resources.depth,
"Type": resource_type,
"Id": hex(binary.resources.id),
}
resource_manager = {}
if binary.resources_manager.has_type:
resource_manager["Type"] = ", ".join(
str(rType) for rType in binary.resources_manager.types_available
)
if binary.resources_manager.langs_available:
langs_available = ", ".join(
str(lang) for lang in binary.resources_manager.langs_available
)
sublangs_available = ", ".join(
str(sublang) for sublang in binary.resources_manager.sublangs_available
)
resource_manager.update(
{"Language": langs_available, "Sub-language": sublangs_available}
)
if resource_manager:
feature_set["Resource manager"] = resource_manager
else:
logger.info("Warning: No resource found")
return feature_set
def dlls(binary: lief.PE.Binary, file_type: str) -> dict:
"""
Lists the DLLs imported by the PE binary.
Args:
binary: The binary file being processed.
file_type: The type of the binary file, expecting 'EXEfile' or 'DLLfile'.
Returns:
A dictionary containing a list of imported libraries if available.
"""
if file_type in ["EXEfile", "DLLfile"] and binary.libraries:
return {"Libraries": binary.libraries}
else:
logger.info("Error: No dll found")
return {}
def imports(binary: lief.PE.Binary, file_type: str) -> dict:
"""
Extracts import information from the PE binary.
Args:
binary: The binary file being processed.
file_type: The type of the binary file, expecting 'EXEfile' or 'DLLfile'.
Returns:
A dictionary containing imports names and functions if available.
"""
feature_set = {
"Imports Name": [],
"Imports Function IAT": [],
"Imports Function name": [],
}
if file_type in ["EXEfile", "DLLfile"] and binary.imports:
for imp in binary.imports:
feature_set["Imports Name"].append(imp.name)
for function in imp.entries:
feature_set["Imports Function IAT"].append(hex(function.iat_address))
feature_set["Imports Function name"].append(function.name)
else:
logger.info("Warning: No import found")
return feature_set
def load_configuration(binary: lief.PE.Binary, file_type: str) -> dict:
"""
Extracts load configuration details from the PE binary.
Args:
binary: The binary file being processed.
file_type: The type of the binary file, expecting 'EXEfile' or 'DLLfile'.
Returns:
A dictionary containing load configuration details if available.
"""
if file_type in ["EXEfile", "DLLfile"] and binary.has_configuration:
config = binary.load_configuration
return {
"Configuration": {
"Version": str(config.version),
"Characteristics": hex(config.characteristics),
"Timedatestamp": from_timestamp_to_date(config.timedatestamp),
"Major version": config.major_version,
"Minor version": config.minor_version,
"Security cookie": hex(config.security_cookie),
}
}
else:
logger.info("Warning: No load configuration found")
return {}
def signature(pe: lief.PE.Binary, type_of_binary: str) -> dict[str, Any]:
"""
Extracts and displays the PE signature information, if available.
Args:
pe: The PE binary file being processed.
type_of_binary: The type of the binary file, expecting 'EXEfile' or 'DLLfile'.
Returns:
A dictionary containing the signature information if available.
"""
feature_set = {}
if type_of_binary in ["EXEfile", "DLLfile"] and pe.has_signatures:
feature_set["Signature"] = {
"MD5 authentihash": pe.authentihash_md5.hex(),
"SHA1 authentihash": pe.authentihash(lief.PE.ALGORITHMS.SHA_1).hex(),
}
# Extract signer details from the first signature
if pe.signatures:
cert_signer = pe.signatures[0].signers[0].cert
signer_details = {
line.split(" : ")[0].strip(): line.split(" : ")[1].strip()
for line in str(cert_signer).split("\n")
if " : " in line
}
feature_set["Signature"]["Signer details"] = signer_details
else:
# Assuming a logging mechanism or similar feedback for when signatures are not found
print("Warning: No signature found for the specified binary type.")
return feature_set
def get_sections(binary: lief.Binary, type_of_binary: str) -> dict:
"""
Extracts and displays the sections of ELF, PE, Mach-O binaries.
Args:
binary: The binary file being processed.
type_of_binary: The type of the binary file ('elffile', 'EXEfile', 'DLLfile', 'machofile').
Returns:
A dictionary with sections' details if available.
"""
sections_info = {"Sections": {}}
if not binary.sections:
print("Warning: No section found")
return sections_info
rows = []
if type_of_binary == "elffile":
for section in binary.sections:
rows.append(
{
"Name": section.name,
"Offset": hex(section.offset),
"Virtual address": hex(section.virtual_address),
"Size": f"{section.size:<6} bytes",
"Type": str(section.type),
"Flags": ":".join(str(flag) for flag in section.flags_list),
"Entropy": round(section.entropy, 4),
}
)
elif type_of_binary in ["EXEfile", "DLLfile"]:
for section in binary.sections:
rows.append(
{
"Name": section.name,
"Virtual address": hex(section.virtual_address),
"Virtual size": f"{section.virtual_size:<6} bytes",
"Offset": hex(section.offset),
"Size": f"{section.size:<6} bytes",
"Entropy": round(section.entropy, 4),
}