-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathilapfuncs.py
More file actions
1722 lines (1504 loc) · 77.1 KB
/
Copy pathilapfuncs.py
File metadata and controls
1722 lines (1504 loc) · 77.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
# common standard imports
import codecs # pylint: disable=unused-import # re-exported
import contextlib
import csv
import hashlib
import inspect
import io
import itertools
import json
import math
import nska_deserialize
import os
import plistlib
import re # pylint: disable=unused-import # re-exported for modules importing it from here
import shutil
import sqlite3
import sys
import xml
from datetime import datetime, timezone, timedelta
from functools import lru_cache
from pathlib import Path
from urllib.parse import quote
import scripts.artifact_report as artifact_report
from scripts.context import Context
from scripts.version_info import leapp_name # pylint: disable=unused-import # re-exported
# new location for modules imported for backward compatibility
# existing functions that are moved should leave a commented out def line
# These names are re-exported on purpose: modules that still do
# `from scripts.ilapfuncs import ...` (or pick them up through the wildcard import in
# ileapp.py / ileappGUI.py) must keep resolving them here, so pylint's unused-import
# check does not apply to this block.
# pylint: disable=unused-import
from leapp_functions.app.platform import (
ILLEGAL_FILENAME_CHARS,
format_illegal_filename_chars,
illegal_chars_in_filename,
sanitize_file_name,
sanitize_file_path,
validate_filename,
)
from leapp_functions.app.output import (
get_output_folder_base,
resolve_output_folder_name,
validate_output_folder_available,
)
# pylint: enable=unused-import
_console_write = sys.stdout.write
# common third party imports
import pytz
import simplekml
from scripts.filetype import guess_mime, guess_extension
from functools import wraps
# LEAPP version unique imports
import binascii
from PIL import Image
from scripts.html_safe import esc, safe_local_path
from scripts.lavafuncs import lava_process_artifact, lava_insert_sqlite_data, lava_get_media_item, \
lava_insert_sqlite_media_item, lava_insert_sqlite_media_references, lava_get_media_references, \
lava_get_full_media_info, lava_update_record_count
os.path.basename = lru_cache(maxsize=None)(os.path.basename)
thumbnail_root = '**/Media/PhotoData/Thumbnails/**/'
media_root = '**/Media/'
thumb_size = 256, 256
identifiers = {}
icons = {}
lava_only_artifacts = {}
class iOS:
_version = None
@staticmethod
def get_version():
"""Return the value of the class property."""
return iOS._version
@staticmethod
def set_version(os_version):
"""Assign a value to the class property once."""
if iOS._version is None:
iOS._version = os_version
class OutputParameters:
'''Defines the parameters that are common for '''
# static parameters
nl = '\n'
screen_output_file_path = ''
def __init__(self, output_folder, custom_folder_name=None):
self.output_folder_base = get_output_folder_base(output_folder, custom_folder_name)
self.data_folder = os.path.join(self.output_folder_base, 'data')
self.media_folder = os.path.join(self.output_folder_base, 'media')
self.html_media_folder = os.path.join(self.output_folder_base, '_HTML', 'media')
OutputParameters.screen_output_file_path = os.path.join(
self.output_folder_base, '_HTML', '_Script_Logs', 'Screen_Output.html')
OutputParameters.screen_output_file_path_devinfo = os.path.join(
self.output_folder_base, '_HTML', '_Script_Logs', 'DeviceInfo.html')
OutputParameters.screen_output_file_path_lava_only = os.path.join(
self.output_folder_base, '_HTML', '_Script_Logs', 'Lava_only_artifacts_log.html')
os.makedirs(os.path.join(self.output_folder_base, '_HTML', '_Script_Logs'))
os.makedirs(self.data_folder)
os.makedirs(self.media_folder, exist_ok=True)
os.makedirs(self.html_media_folder, exist_ok=True)
class GuiWindow:
'''This only exists to hold window handle if script is run from GUI'''
window_handle = None # static variable
@staticmethod
def SetProgressBar(n, total): # pylint: disable=unused-argument
if GuiWindow.window_handle:
progress_bar = GuiWindow.window_handle.nametowidget('progress_bar_frame.progress_bar')
progress_bar.config(value=n)
class MediaItem():
def __init__(self, id): # pylint: disable=redefined-builtin
self.id = id
self.source_path = ""
self.extraction_path = ""
self.mimetype = ""
self.metadata = ""
self.created_at = 0
self.updated_at = 0
self.is_embedded = 0
def set_values(self, media_info):
self.id = media_info[0]
self.source_path = media_info[1]
self.extraction_path = media_info[2]
self.mimetype = media_info[3]
self.metadata = media_info[4]
self.created_at = media_info[5]
self.updated_at = media_info[6]
self.is_embedded = media_info[7]
class MediaReferences():
def __init__(self, id): # pylint: disable=redefined-builtin
self.id = id
self.media_item_id = ""
self.module_name = ""
self.artifact_name = ""
self.name = ""
def set_values(self, media_ref_info):
self.id = media_ref_info[0]
self.media_item_id = media_ref_info[1]
self.module_name = media_ref_info[2]
self.artifact_name = media_ref_info[3]
self.name = media_ref_info[4]
def logfunc(message=""):
def redirect_logs(string):
_console_write(string)
log_text.insert('end', string) # pylint: disable=used-before-assignment
log_text.see('end')
log_text.update()
if GuiWindow.window_handle:
log_text = GuiWindow.window_handle.nametowidget('logs_frame.log_text')
sys.stdout.write = redirect_logs
if OutputParameters.screen_output_file_path:
with open(OutputParameters.screen_output_file_path, 'a', encoding='utf8') as a:
a.write(message + '<br>' + OutputParameters.nl)
print(message)
def strip_tuple_from_headers(data_headers):
return [header[0] if isinstance(header, tuple) else header for header in data_headers]
def get_media_header_info(data_headers):
media_header_info = {}
for index, header in enumerate(data_headers):
if isinstance(header, tuple) and header[1] == 'media':
style = header[2] if len(header) == 3 else ''
media_header_info[index] = style
return media_header_info
def check_output_types(type, output_types): # pylint: disable=redefined-builtin
if type in output_types or type == output_types or 'all' in output_types or 'all' == output_types:
return True
elif type != 'kml' and ('standard' in output_types or 'standard' == output_types):
return True
elif type == 'lava' and ('lava_only' in output_types or 'lava_only' == output_types):
return True
else:
return False
def get_media_references_id(media_id, artifact_name, name):
'''
Get the media references ID.
Args:
media_id: The ID of the media.
artifact_name: The name of the artifact.
name: The name of the media (optional).
Returns:
The media references ID.
'''
return hashlib.sha1(f"{media_id}-{artifact_name}-{name}".encode()).hexdigest()
def set_media_references(media_ref_id, media_id, module_name, artifact_name, name):
'''
Set the media references in the LAVA database.
Args:
media_ref_id: The ID of the media references.
media_id: The ID of the media.
module_name: The name of the module.
artifact_name: The name of the artifact.
name: The name of the media (optional).
'''
media_references = MediaReferences(media_ref_id)
media_references.set_values((
media_ref_id, media_id, module_name, artifact_name, name
))
lava_insert_sqlite_media_references(media_references)
def _check_in_media(media_id, source_path, is_embedded, name, media_data=None, converted_file_path=None, force_type=None,
force_extension=None, force_creation_date=None, force_modification_date=None):
'''
Check in media.
Args:
media_id: The ID of the media.
source_path: The source path of the media file.
is_embedded: Whether the media is embedded.
name: The name of the media (optional).
media_data: The media data (optional).
converted_file_path: The converted file path (optional).
force_type: The MIME type of the media (optional).
force_extension: The extension of the media (optional).
force_creation_date: The creation date of the media (optional).
force_modification_date: The modification date of the media (optional).
Returns:
The media reference ID or None.
'''
output_params = Context.get_output_params()
seeker = Context.get_seeker()
media_ref_id = get_media_references_id(media_id, Context.get_artifact_name(), name)
if lava_get_media_references(media_ref_id):
return media_ref_id # Reference already exists, we're done.
# If media item doesn't exist, create it.
if not lava_get_media_item(media_id):
media_item = MediaItem(media_id)
if force_type:
media_item.mimetype = force_type
else:
media_item.mimetype = guess_mime(media_data)
if force_extension:
suffix = force_extension
elif name and len(name.split('.')[-1]) < 5:
suffix = name.split('.')[-1]
elif not is_embedded and len(source_path.split('.')[-1]) < 5:
suffix = source_path.split('.')[-1]
else:
suffix = f".{guess_extension(media_data)}"
if suffix and not suffix.startswith('.'):
suffix = f".{suffix}"
extraction_path = Context.get_source_file_path(source_path)
file_info = seeker.file_infos.get(extraction_path)
if file_info:
media_item.source_path = file_info.source_path
else:
media_item.source_path = source_path
if is_embedded:
media_item.created_at = force_creation_date if force_creation_date else 0
media_item.updated_at = force_modification_date if force_modification_date else 0
else:
if not extraction_path:
return None
file_to_copy = Path(converted_file_path) if converted_file_path else Path(extraction_path)
if not file_to_copy.is_file():
return None
if force_creation_date:
media_item.created_at = force_creation_date
elif file_info:
media_item.created_at = file_info.creation_date
else:
media_item.created_at = 0
if force_modification_date:
media_item.updated_at = force_modification_date
elif file_info:
media_item.updated_at = file_info.modification_date
else:
media_item.updated_at = 0
# 1. Create the canonical media file
canonical_media_path = Path(output_params.media_folder).joinpath(media_id).with_suffix(suffix)
if is_embedded:
canonical_media_path.write_bytes(media_data)
else:
try:
canonical_media_path.hardlink_to(file_to_copy)
except OSError:
shutil.copy2(file_to_copy, canonical_media_path)
# 2. Create the HTML media file link/copy
html_media_path = Path(output_params.html_media_folder).joinpath(media_id).with_suffix(suffix)
if not html_media_path.exists():
try:
html_media_path.hardlink_to(canonical_media_path)
except OSError:
shutil.copy2(canonical_media_path, html_media_path)
media_item.extraction_path = f"media/{media_id}{suffix}"
media_item.metadata = "not parsed yet"
media_item.is_embedded = 1 if is_embedded else 0
lava_insert_sqlite_media_item(media_item)
# Always set the reference
set_media_references(media_ref_id, media_id, Context.get_module_name(), Context.get_artifact_name(), name)
return media_ref_id
def check_in_media(file_path, name="", converted_file_path=False, force_type=None, force_extension=None,
force_creation_date=None, force_modification_date=None):
'''
Check in media.
Args:
file_path: The file path of the media file.
name: The name of the media (optional).
converted_file_path: The converted file path (optional).
force_type: The MIME type of the media (optional).
force_extension: The extension of the media (optional).
force_creation_date: The creation date of the media (optional).
force_modification_date: The modification date of the media (optional).
Returns:
The media reference ID or None.
'''
extraction_path = Context.get_source_file_path(file_path)
if not extraction_path:
logfunc(f'No matching file found for "{file_path}"')
return None
file_info = Context.get_seeker().file_infos.get(extraction_path)
if file_info:
media_id = hashlib.sha1(f"{file_info.source_path}".encode()).hexdigest()
with open(extraction_path, "rb") as f:
file_data = f.read()
return _check_in_media(media_id, file_path, False, name, media_data=file_data, converted_file_path=converted_file_path,
force_type=force_type, force_extension=force_extension,
force_creation_date=force_creation_date, force_modification_date=force_modification_date)
return None
def check_in_embedded_media(source_file, data, name="", force_type=None, force_extension=None,
force_creation_date=None, force_modification_date=None):
'''
Check in embedded media.
Args:
source_file: The source file path of the embedded media data.
data: The bytes of the embedded media data.
name: The name of the media (optional).
force_type: The MIME type of the media (optional).
force_extension: The extension of the media (optional).
force_creation_date: The creation date of the media (optional).
force_modification_date: The modification date of the media (optional).
Returns:
The media reference ID or None.
'''
if not data:
return None
media_id = hashlib.sha1(data).hexdigest()
return _check_in_media(media_id, source_file, True, name, media_data=data, force_type=force_type,
force_extension=force_extension, force_creation_date=force_creation_date,
force_modification_date=force_modification_date)
def html_media_tag(media_path, mimetype, style, title=''):
def relative_paths(source):
# HTML report is in <report_folder>/_HTML/<artifact_name>.html
# Media will be linked from <report_folder>/_HTML/media/<media_id>.<ext>
# source path is the canonical path: ./media/<media_id>.<ext>
filename = Path(source).name
return f"media/{filename}"
# The media name comes from the evidence, so every place it is emitted is
# escaped: percent-encoded in src/href by safe_local_path(), which also refuses a
# target that would leave the report folder, and HTML-escaped in title= and in the
# fallback link text. Before this, a crafted attachment filename broke out of the
# title attribute and ran in the examiner's report (CWE-79).
filename = esc(Path(media_path).name)
media_path = safe_local_path(relative_paths(media_path))
if mimetype is None:
mimetype = ''
if 'video' in mimetype:
thumb = f'<video width="320" height="240" controls="controls"><source src="{media_path}" type="video/mp4" preload="none">Your browser does not support the video tag.</video>'
elif 'image' in mimetype:
image_style = esc(style) if style else "max-height:300px; max-width:400px;"
thumb = f'<a href="{media_path}" target="_blank"><img title="{esc(title)}" src="{media_path}" style="{image_style}"></img></a>'
elif 'audio' in mimetype:
thumb = f'<audio controls><source src="{media_path}" type="audio/ogg"><source src="{media_path}" type="audio/mpeg">Your browser does not support the audio element.</audio>'
else:
thumb = f'<a href="{media_path}" target="_blank"> Link to {filename} file</a>'
return thumb
def get_data_list_with_media(media_header_info, data_list):
'''
For columns with media item, generate:
- A data list with HTML code for HTML output
- A data list with extraction path of media items for TSV, KML and Timeline exports
'''
html_data_list = []
txt_data_list = []
# Get the correct output paths from the context
output_params = Context.get_output_params()
for data in data_list:
html_row = list(data)
txt_row = list(data)
for idx, style in media_header_info.items():
media_ref_id_cell = html_row[idx]
if not media_ref_id_cell:
html_row[idx] = ''
txt_row[idx] = ''
continue
html_code = ''
path_list = []
# Handle both single items and lists of items uniformly
media_ref_ids = media_ref_id_cell if isinstance(media_ref_id_cell, list) else [media_ref_id_cell]
for ref_id in media_ref_ids:
media_item = lava_get_full_media_info(ref_id)
if not (media_item and media_item['extraction_path']):
continue
# Construct the full, absolute path to the canonical media file
canonical_path = os.path.join(output_params.output_folder_base, media_item['extraction_path'])
# Construct the full, absolute path for the HTML link destination
html_path = os.path.join(output_params.html_media_folder, Path(canonical_path).name)
# Create the link/copy for the HTML report if it doesn't exist
if os.path.exists(canonical_path) and not os.path.exists(html_path):
try:
os.link(canonical_path, html_path)
except OSError:
shutil.copy2(canonical_path, html_path)
# Generate the HTML tag and add the path for the text report
html_code += html_media_tag(media_item['extraction_path'], media_item['type'], style, media_item['name'])
path_list.append(media_item['extraction_path'])
# Assign the generated values to the rows
html_row[idx] = html_code
if isinstance(media_ref_id_cell, list):
txt_row[idx] = ' | '.join(path_list)
else:
txt_row[idx] = path_list[0] if path_list else ''
html_data_list.append(tuple(html_row))
txt_data_list.append(tuple(txt_row))
return html_data_list, txt_data_list
_reported_unsafe_report_names = set()
def sanitize_report_name(name, kind='name'):
"""
Replaces path separators in an artifact name or category so it is usable as a file
or folder name.
Artifact names become HTML/TSV/KML filenames and categories become _HTML subfolder
names. A name such as 'Twitter/X' makes os.path.join() read the '/' as a path
separator, so the artifact either fails to write its report or lands in an
unintended folder, even though the parser ran fine. The original name is kept for
display and for LAVA; only the on-disk name is rewritten.
Args:
name (str): The artifact name or category to make path safe.
kind (str): What is being sanitized, used in the warning ('name' or 'category').
Returns:
str: The name with '/' and '\\' replaced by '_'.
"""
safe_name = name.replace('/', '_').replace('\\', '_')
if safe_name != name and name not in _reported_unsafe_report_names:
_reported_unsafe_report_names.add(name)
logfunc(f"Warning: artifact {kind} '{name}' contains a path separator. "
f"Report files use '{safe_name}' instead; rename it to avoid the mismatch.")
return safe_name
def artifact_processor(func):
@wraps(func)
def wrapper(files_found, report_folder, seeker, wrap_text, timezone_offset):
module_name = func.__module__.split('.')[-1]
func_name = func.__name__
module_file_path = inspect.getfile(func)
all_artifacts_info = func.__globals__.get('__artifacts_v2__', {})
artifact_info = all_artifacts_info.get(func_name, {})
artifact_name = artifact_info.get('name', func_name)
category = artifact_info.get('category', '')
description = artifact_info.get('description', '')
icon = artifact_info.get('artifact_icon', '')
html_columns = artifact_info.get('html_columns', [])
output_types = artifact_info.get('output_types', ['html', 'tsv', 'timeline', 'lava', 'kml'])
is_lava_only = 'lava_only' in output_types
Context.clear()
Context.set_report_folder(report_folder)
Context.set_seeker(seeker)
Context.set_files_found(files_found)
Context.set_artifact_info(artifact_info)
Context.set_module_name(module_name)
Context.set_module_file_path(module_file_path)
Context.set_artifact_name(artifact_name)
sig = inspect.signature(func)
if len(sig.parameters) == 1:
data_headers, data_list, source_path = func(Context)
else:
data_headers, data_list, source_path = func(files_found, report_folder, seeker, wrap_text, timezone_offset)
if data_list and not source_path:
logfunc("No source_path provided")
else:
# Report extraction-relative paths, never the examiner's local filesystem
source_path = '\n'.join(
Context.get_relative_path(p) for p in str(source_path).split('\n'))
if isinstance(data_list, tuple):
data_list, html_data_list = data_list
else:
html_data_list = data_list
if len(data_list):
logfunc(f"Found {len(data_list):,} {'records' if len(data_list)>1 else 'record'} for {artifact_name}")
# Path separators would break (or misplace) the report files, so the HTML, TSV
# and KML outputs are written under a path safe name. The sidebar keys off the
# on-disk names, so the icon lookup has to use the same safe names.
safe_artifact_name = sanitize_report_name(artifact_name)
safe_category = sanitize_report_name(category, 'category')
icons.setdefault(safe_category, {safe_artifact_name: icon}).update({safe_artifact_name: icon})
# Strip tuples from headers for HTML, TSV, and timeline
stripped_headers = strip_tuple_from_headers(data_headers)
# Check if headers contains a 'media' type
media_header_info = get_media_header_info(data_headers)
if media_header_info:
html_columns.extend([data_headers[idx][0] for idx in media_header_info])
html_data_list, txt_data_list = get_data_list_with_media(media_header_info, data_list)
if check_output_types('html', output_types):
report = artifact_report.ArtifactHtmlReport(artifact_name)
report.start_artifact_report(report_folder, safe_artifact_name, description)
report.add_script()
report.write_artifact_data_table(stripped_headers, html_data_list, source_path, html_no_escape=html_columns)
report.end_artifact_report()
if check_output_types('tsv', output_types):
tsv(report_folder, stripped_headers, txt_data_list if media_header_info else data_list, safe_artifact_name)
if check_output_types('timeline', output_types):
timeline(report_folder, artifact_name, txt_data_list if media_header_info else data_list, stripped_headers)
if check_output_types('lava', output_types):
table_name, object_columns, column_map = lava_process_artifact(category,
module_name,
artifact_name,
data_headers,
len(data_list),
func_name=func_name,
data_views=artifact_info.get("data_views"),
artifact_icon=icon,
source_path=source_path)
if is_lava_only:
lava_only_info(category, artifact_name, table_name, len(data_list))
lava_insert_sqlite_data(table_name, data_list, object_columns, data_headers, column_map)
if check_output_types('kml', output_types):
kmlgen(report_folder, safe_artifact_name, txt_data_list if media_header_info else data_list, stripped_headers)
else:
if output_types != 'none':
logfunc(f"No data found for {artifact_name}")
if is_lava_only:
lava_only_info(category, artifact_name, artifact_name, 0)
return data_headers, data_list, source_path
return wrapper
# Rows written per INSERT batch by artifact_processor_streaming. Large enough that the
# per-statement overhead disappears, small enough that the batch itself stays small.
STREAMING_BATCH_SIZE = 50000
def _batched(iterable, size):
"""Yield lists of up to `size` items. itertools.batched is 3.12+, iLEAPP supports 3.10."""
batch = []
for item in iterable:
batch.append(item)
if len(batch) >= size:
yield batch
batch = []
if batch:
yield batch
def artifact_processor_streaming(func):
"""LAVA-only artifact_processor for artifacts too large to hold in memory.
artifact_processor() needs a materialized data_list: it takes len() of it, hands it to
the HTML/TSV/timeline writers, and lava_insert_sqlite_data() then builds a second full
list of converted rows before executemany(). At roughly 617 bytes per row that is
~19 GB for a 31M row Unified Log import, and ~39 GB at peak with both lists live.
A function decorated here returns an *iterator* of rows instead of a list, and the
rows are written to SQLite in batches as they arrive; peak memory stays flat at the
batch size regardless of how many records the artifact produces.
The trade-off is that nothing which needs the whole result set is available, so this
is restricted to lava_only artifacts: no HTML, TSV, timeline or KML output, and the
record count is known only once the stream ends.
"""
@wraps(func)
def wrapper(files_found, report_folder, seeker, wrap_text, timezone_offset):
module_name = func.__module__.split('.')[-1]
func_name = func.__name__
module_file_path = inspect.getfile(func)
all_artifacts_info = func.__globals__.get('__artifacts_v2__', {})
artifact_info = all_artifacts_info.get(func_name, {})
artifact_name = artifact_info.get('name', func_name)
category = artifact_info.get('category', '')
icon = artifact_info.get('artifact_icon', '')
output_types = artifact_info.get('output_types', [])
if 'lava_only' not in output_types:
logfunc(f"{artifact_name} uses artifact_processor_streaming but is not declared "
f"lava_only; no output will be produced")
return None, iter(()), None
Context.clear()
Context.set_report_folder(report_folder)
Context.set_seeker(seeker)
Context.set_files_found(files_found)
Context.set_artifact_info(artifact_info)
Context.set_module_name(module_name)
Context.set_module_file_path(module_file_path)
Context.set_artifact_name(artifact_name)
sig = inspect.signature(func)
if len(sig.parameters) == 1:
data_headers, row_iterator, source_path = func(Context)
else:
data_headers, row_iterator, source_path = func(
files_found, report_folder, seeker, wrap_text, timezone_offset)
rows = iter(row_iterator)
# Registering the artifact creates its table, so only do it once a row proves
# there is something to store. Otherwise an empty table would be left behind and
# would read as "parsed, found nothing" rather than "did not run".
first_batch = next(_batched(rows, STREAMING_BATCH_SIZE), None)
if not first_batch:
logfunc(f"No data found for {artifact_name}")
lava_only_info(category, artifact_name, artifact_name, 0)
return data_headers, iter(()), source_path
if source_path:
source_path = '\n'.join(
Context.get_relative_path(p) for p in str(source_path).split('\n'))
safe_artifact_name = sanitize_report_name(artifact_name)
safe_category = sanitize_report_name(category, 'category')
icons.setdefault(safe_category, {safe_artifact_name: icon}).update({safe_artifact_name: icon})
table_name, object_columns, column_map = lava_process_artifact(
category, module_name, artifact_name, data_headers,
record_count=0, func_name=func_name,
data_views=artifact_info.get("data_views"),
artifact_icon=icon, source_path=source_path)
record_count = 0
for batch in itertools.chain([first_batch], _batched(rows, STREAMING_BATCH_SIZE)):
lava_insert_sqlite_data(table_name, batch, object_columns, data_headers, column_map)
record_count += len(batch)
lava_update_record_count(category, table_name, record_count)
lava_only_info(category, artifact_name, table_name, record_count)
logfunc(f"Found {record_count:,} {'records' if record_count > 1 else 'record'} for {artifact_name}")
return data_headers, iter(()), source_path
return wrapper
def is_platform_linux():
'''Returns True if running on Linux'''
return sys.platform == 'linux'
def is_platform_macos():
'''Returns True if running on macOS'''
return sys.platform == 'darwin'
def is_platform_windows():
'''Returns True if running on Windows'''
return sys.platform == 'win32'
# def sanitize_file_path(filename, replacement_char='_'):
# Moved to leapp_functions.app.platform
# def sanitize_file_name(filename, replacement_char='_'):
# Moved to leapp_functions.app.platform
def get_next_unused_name(path):
'''Checks if path exists, if it does, finds an unused name by appending -xx
where xx=00-99. Return value is new path.
If it is a file like abc.txt, then abc-01.txt will be the next
'''
folder, basename = os.path.split(path)
ext = None
if basename.find('.') > 0:
basename, ext = os.path.splitext(basename)
num = 1
new_name = basename
if ext != None:
new_name += f"{ext}"
while os.path.exists(os.path.join(folder, new_name)):
new_name = basename + "-{:02}".format(num)
if ext != None:
new_name += f"{ext}"
num += 1
return os.path.join(folder, new_name)
def get_file_path(files_found, filename, skip=False):
"""Returns the path of the searched filename if exists or returns None"""
try:
for file_found in files_found:
if skip and skip in file_found:
continue
if Path(file_found).match(filename):
return file_found
except Exception as e: # pylint: disable=broad-exception-caught
logfunc(f"Error: {str(e)}")
return None
def get_txt_file_content(file_path):
try:
with open(file_path, "r", encoding="utf-8") as file:
file_content = file.readlines()
return file_content
except FileNotFoundError:
logfunc(f"Error: File not found at {file_path}")
except PermissionError:
logfunc(f"Error: Permission denied when trying to read {file_path}")
except Exception as e: # pylint: disable=broad-exception-caught
logfunc(f"Unexpected error reading file {file_path}: {str(e)}")
return []
def _deserialize_nska(data):
"""Deserialize an NSKeyedArchiver payload without the dependency's console noise.
ccl_bplist.convert_NSMutableDictionary prints the exception whenever an
archived dictionary uses an unhashable key, despite its own comment saying it
ignores the condition. One artifact reading a few thousand such records emits
tens of thousands of lines, which buries the real log and, on a Windows
console, is slow enough to look like a hang. The condition is not actionable
from here, so the chatter is dropped while real errors still raise.
"""
with contextlib.redirect_stdout(io.StringIO()):
return nska_deserialize.deserialize_plist_from_string(data)
def get_plist_content(data):
try:
plist_content = plistlib.loads(data)
if isinstance(plist_content, dict) and plist_content.get('$archiver', '') == 'NSKeyedArchiver':
return _deserialize_nska(data)
return plist_content
except plistlib.InvalidFileException:
logfunc("Error: Invalid plist data")
except xml.parsers.expat.ExpatError:
logfunc("Error: Malformed XML")
except TypeError as e:
logfunc(f"Error: Type error when parsing plist data: {str(e)}")
except ValueError as e:
logfunc(f"Error: Value error when parsing plist data: {str(e)}")
except OverflowError as e:
logfunc(f"Error: Overflow error when parsing plist data: {str(e)}")
except nska_deserialize.DeserializeError:
logfunc("Error: Invalid NSKeyedArchive plist data")
except Exception as e: # pylint: disable=broad-exception-caught
logfunc(f"Unexpected error reading plist data: {str(e)}")
return {}
def get_plist_file_content(file_path):
try:
with open(file_path, 'rb') as file:
plist_content = plistlib.load(file)
if isinstance(plist_content, dict) and plist_content.get('$archiver', '') == 'NSKeyedArchiver':
return nska_deserialize.deserialize_plist(file_path)
return plist_content
except FileNotFoundError:
logfunc(f"Error: Plist file not found at {file_path}")
except PermissionError:
logfunc(f"Error: Permission denied when trying to read {file_path}")
except plistlib.InvalidFileException:
logfunc(f"Error: Invalid plist file format in {file_path}")
except xml.parsers.expat.ExpatError:
logfunc(f"Error: Malformed XML in plist file {file_path}")
except TypeError as e:
logfunc(f"Error: Type error when parsing plist {file_path}: {str(e)}")
except ValueError as e:
logfunc(f"Error: Value error when parsing plist {file_path}: {str(e)}")
except OverflowError as e:
logfunc(f"Error: Overflow error when parsing plist {file_path}: {str(e)}")
except nska_deserialize.DeserializeError:
logfunc(f"Error: {file_path} is not a valid NSKeyedArchive plist file")
except Exception as e: # pylint: disable=broad-exception-caught
logfunc(f"Unexpected error reading plist file {file_path}: {str(e)}")
return {}
def get_sqlite_db_path(path):
if is_platform_windows():
path_str = str(path)
if path_str.startswith('\\\\?\\UNC\\'): # UNC long path
remainder = path_str[4:]
elif path_str.startswith('\\\\?\\'): # normal long path
remainder = path_str[4:]
elif path_str.startswith('\\\\'): # UNC path
remainder = '\\UNC' + path_str[1:]
else: # normal path
remainder = path_str
# Encode special URI characters (e.g. '#', space) so SQLite doesn't
# treat them as fragment delimiters or query separators. Keep ':'
# and '/' safe so the drive letter and forward slashes are preserved.
return "%5C%5C%3F%5C" + quote(remainder, safe=':/')
else:
return quote(str(path), safe='/')
def open_sqlite_db_readonly(path):
'''Opens a sqlite db in read-only mode, so original db (and -wal/journal are intact)'''
try:
if path:
path = get_sqlite_db_path(path)
with sqlite3.connect(f"file:{path}?mode=ro", uri=True) as db:
return db
except sqlite3.OperationalError as e:
logfunc(f"Error with {path}:")
logfunc(f" - {str(e)}")
return None
def attach_sqlite_db_readonly(path, db_name):
'''Return the query to attach a sqlite db in read-only mode.
path: str --> Path of the SQLite DB to attach
db_name: str --> Name of the SQLite DB in the query'''
path = get_sqlite_db_path(path)
return f'''ATTACH DATABASE "file:{path}?mode=ro" AS {db_name}'''
def get_sqlite_db_records(path, query, attach_query=None):
db = open_sqlite_db_readonly(path)
if db:
db.row_factory = sqlite3.Row # For fetching columns by name
try:
cursor = db.cursor()
if attach_query:
cursor.execute(attach_query)
cursor.execute(query)
# records = cursor.fetchall()
# NOTE: we return the cursor directly, to be iterated by the caller
# to keep it as a generator
return cursor
except sqlite3.DatabaseError as e:
logfunc(f"Error with {path}:")
logfunc(f" - {str(e)}")
return []
def get_sqlite_multiple_db_records(path_list, query, data_headers):
multiple_source_files = len(path_list) > 1
source_path = ""
data_list = []
if multiple_source_files:
data_headers = list(data_headers)
data_headers.append('Source Path')
data_headers = tuple(data_headers)
source_path = 'file path in the report below'
elif path_list:
source_path = path_list[0]
for file in path_list:
db_records = get_sqlite_db_records(file, query)
for record in db_records:
if multiple_source_files:
modifiable_record = list(record)
modifiable_record.append(file)
record = tuple(modifiable_record)
data_list.append(record)
return data_headers, data_list, source_path
def does_column_exist_in_db(path, table_name, col_name):
'''Checks if a specific col exists'''
db = open_sqlite_db_readonly(path)
col_name = col_name.lower()
try:
db.row_factory = sqlite3.Row # For fetching columns by name
query = f"pragma table_info('{table_name}');"
cursor = db.cursor()
cursor.execute(query)
all_rows = cursor.fetchall()
for row in all_rows:
if row['name'].lower() == col_name:
return True
except sqlite3.Error as ex:
logfunc(f"Query error, query={query} Error={str(ex)}")
return False
def does_table_exist_in_db(path, table_name):
'''Checks if a table with specified name exists in an sqlite db'''
db = open_sqlite_db_readonly(path)
if db:
try:
query = f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'"
cursor = db.execute(query)
for _ in cursor:
return True
except sqlite3.Error as ex:
logfunc(f"Query error, query={query} Error={str(ex)}")
return False
def does_view_exist_in_db(path, table_name):
'''Checks if a table with specified name exists in an sqlite db'''
db = open_sqlite_db_readonly(path)
if db:
try:
query = f"SELECT name FROM sqlite_master WHERE type='view' AND name='{table_name}'"
cursor = db.execute(query)
for _ in cursor:
return True
except sqlite3.Error as ex:
logfunc(f"Query error, query={query} Error={str(ex)}")
return False
def tsv(report_folder, data_headers, data_list, tsvname, source_file=None): # pylint: disable=unused-argument
report_folder = report_folder.rstrip('/')
report_folder = report_folder.rstrip('\\')
report_folder_base = os.path.dirname(os.path.dirname(report_folder))
tsv_report_folder = os.path.join(report_folder_base, '_TSV Exports')
if os.path.isdir(tsv_report_folder):
pass
else:
os.makedirs(tsv_report_folder)
with open(os.path.join(tsv_report_folder, tsvname + '.tsv'), 'a', encoding='utf-8-sig') as tsvfile:
tsv_writer = csv.writer(tsvfile, delimiter='\t')
tsv_writer.writerow(data_headers)
for i in data_list:
tsv_writer.writerow(i)
def timeline(report_folder, tlactivity, data_list, data_headers):
report_folder = report_folder.rstrip('/')
report_folder = report_folder.rstrip('\\')
report_folder_base = os.path.dirname(os.path.dirname(report_folder))
tl_report_folder = os.path.join(report_folder_base, '_Timeline')
if os.path.isdir(tl_report_folder):
tldb = os.path.join(tl_report_folder, 'tl.db')
db = sqlite3.connect(tldb)
cursor = db.cursor()
cursor.execute('''PRAGMA synchronous = EXTRA''')
cursor.execute('''PRAGMA journal_mode = WAL''')
db.commit()
else:
os.makedirs(tl_report_folder)
# create database
tldb = os.path.join(tl_report_folder, 'tl.db')
db = sqlite3.connect(tldb, isolation_level = 'exclusive')
cursor = db.cursor()
cursor.execute(
"""
CREATE TABLE data(key TEXT, activity TEXT, datalist TEXT)
"""
)