Repository navigation
Expand file tree
/
Copy pathcontext.py
More file actions
663 lines (541 loc) · 21.8 KB
/
Copy pathcontext.py
File metadata and controls
663 lines (541 loc) · 21.8 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
"""Context class"""
import json
import re
from os.path import basename
from pathlib import Path
from leapp_functions.app.artifact_result import ArtifactResult
class Context:
"""
Context class provides a static context for managing and accessing global
state and configuration used during artifact processing in the LEAPPs
framework. It stores information such as report folder, artifact details,
files found, device IDs, and OS build mappings, and provides utility
methods for retrieving and manipulating this data.
"""
_output_params = None
_report_folder = None
_seeker = None
_artifact_info = None
_module_name = None
_module_file_path = None
_artifact_name = None
_artifact_func_name = None
_artifact_result = None
_files_found = []
_filename_lookup_map = {}
_data_folder = None
_output_folder_base = None
_metadata = {}
_installed_os_version = ""
# Run-level, like the output parameters: set once from the CLI or GUI and
# deliberately not reset by clear() between artifacts
_keychain_path = None
@staticmethod
def set_output_params(output_params):
"""
Sets the OutputParameters instance in the Context. This should only be
called once at the start of a run.
Args:
output_params: The initialized OutputParameters object.
"""
Context._output_params = output_params
Context._data_folder = getattr(output_params, 'data_folder', None)
Context._output_folder_base = getattr(
output_params, 'output_folder_base', None)
@staticmethod
def set_data_folder(data_folder):
"""
Sets the folder the seeker stages evidence into, without the rest of the
output parameters.
A normal run gets this from set_output_params. The test harness has no
OutputParameters: it extracts a case zip into its own temporary directory
and runs artifacts against that. Without this, _data_folder stays None and
get_relative_path returns every path unchanged, so an artifact that leaks
an absolute path and one that reports a relative path record identical
output and no fixture can tell them apart.
Args:
data_folder (str): The folder evidence is staged into.
"""
Context._data_folder = data_folder
@staticmethod
def set_report_folder(report_folder):
"""
Sets the report folder path in the Context.
Args:
report_folder (str): The path to the folder where reports will be
stored.
"""
Context._report_folder = report_folder
@staticmethod
def set_seeker(seeker):
"""
Sets the seeker object in the Context class.
Args:
seeker: The seeker object to be set as the current context seeker.
"""
Context._seeker = seeker
@staticmethod
def set_artifact_info(artifact_info):
"""
Sets the artifact information in the Context.
Args:
artifact_info: The artifact information to be stored.
"""
Context._artifact_info = artifact_info
@staticmethod
def set_module_name(module_name):
"""
Sets the module name in the Context class.
Args:
module_name (str): The name of the module to set.
"""
Context._module_name = module_name
@staticmethod
def set_module_file_path(module_file_path):
"""
Sets the file path for the current module in the Context.
Args:
module_file_path (str): The file path to be set for the module.
"""
Context._module_file_path = module_file_path
@staticmethod
def set_artifact_name(artifact_name):
"""
Sets the artifact name in the Context.
Args:
artifact_name (str): The name of the artifact to set.
"""
Context._artifact_name = artifact_name
@staticmethod
def set_artifact_func_name(artifact_func_name):
"""
Sets the function name for the current artifact in the Context.
Args:
artifact_func_name (str): The artifact processor function name.
"""
Context._artifact_func_name = artifact_func_name
@staticmethod
def set_files_found(files_found):
"""
Sets the list of files found in the current context.
Args:
files_found (list): A list of file paths that have been found
using the paths regex of __artifact_v2__ and that are to be stored
in the context.
"""
Context._files_found = files_found
@staticmethod
def get_metadata(collection):
"""
Lazily loads and caches metadata from a JSON file in the scripts/data/
directory.
Args:
collection (str): The name of the collection (filename without .json).
Returns:
dict: The decoded JSON collection, or {} if the file does not exist.
"""
if collection not in Context._metadata:
metadata_path = Path(__file__).parent.absolute().joinpath(
'data', f'{collection}.json')
if metadata_path.exists():
with open(metadata_path, 'rt', encoding='utf-8') as json_file:
Context._metadata[collection] = json.load(json_file)
else:
Context._metadata[collection] = {}
return Context._metadata[collection]
@staticmethod
def lookup_metadata(collection, key, group=None):
"""
Retrieves a value from a metadata collection.
Args:
collection (str): The name of the collection.
key (str): The key to look up.
group (str, optional): The group within the collection to search.
Returns:
str: The matching value, or '' if not found.
"""
data = Context.get_metadata(collection)
if not data:
return ''
if group:
return data.get(group, {}).get(key, '')
key = str(key)
# Check if it's a flat collection
if key in data and not isinstance(data[key], dict):
return data[key]
# Check if it's a grouped collection and search all groups
matches = []
for group_data in data.values():
if isinstance(group_data, dict) and key in group_data:
matches.append(group_data[key])
if matches:
return " or ".join(matches)
return ''
@staticmethod
def set_installed_os_version(os_version):
"""
Sets the OS version of the analyzed device only once.
"""
if not Context._installed_os_version:
Context._installed_os_version = os_version
@staticmethod
def set_keychain_path(keychain_path):
"""
Records the path to a keychain file supplied by the examiner.
iOS keychains are captured separately from the file system extraction,
so apps that keep their database key in the keychain cannot find it in
the extraction itself.
"""
Context._keychain_path = keychain_path
@staticmethod
def get_keychain_path():
"""
Returns the examiner-supplied keychain path, or None when none was given.
Artifacts must treat None as "no keychain available" and degrade rather
than fail, since supplying one is optional.
"""
return Context._keychain_path
@staticmethod
def _build_lookup_map():
"""Builds and returns a dictionary mapping filenames to a list
of full paths."""
if not Context._files_found:
raise ValueError(
"Cannot build lookup map: _files_found is not set.")
filename_lookup = {}
for full_path in Context._files_found:
filename = basename(full_path)
if filename not in filename_lookup:
filename_lookup[filename] = []
filename_lookup[filename].append(full_path)
return filename_lookup
@staticmethod
def get_output_params():
"""
Retrieves the current OutputParameters instance from the Context.
Raises:
ValueError: If the output parameters are not set.
Returns:
OutputParameters: The OutputParameters instance.
"""
if not Context._output_params:
raise ValueError("Context not set. OutputParameters not available.")
return Context._output_params
@staticmethod
def get_report_folder():
"""
Retrieves the current report folder path from the Context.
Raises:
ValueError: If the report folder is not set, indicating that the
function is called outside of an artifact context.
Returns:
str: The path to the report folder.
"""
if not Context._report_folder:
raise ValueError("Context not set. This function should be" +
" called from within an artifact.")
return Context._report_folder
@staticmethod
def get_seeker():
"""
Retrieve the current seeker object from the Context.
Raises:
ValueError: If the Context has not been set, indicating that this
function should only be called from within an artifact.
Returns:
The seeker object associated with the current Context.
"""
if not Context._seeker:
raise ValueError("Context not set. This function should be" +
" called from within an artifact.")
return Context._seeker
@staticmethod
def get_artifact_info():
"""
Retrieve the current artifact information (__artifact_v2__) from the
Context.
Raises:
ValueError: If the Context's artifact information is not set,
indicating that this function was called outside of an artifact
context.
Returns:
dict: The artifact information stored in the Context.
"""
if not Context._artifact_info:
raise ValueError("Context not set. This function should be" +
" called from within an artifact.")
return Context._artifact_info
@staticmethod
def get_module_name():
"""
Retrieves the current module name from the Context.
Raises:
ValueError: If the Context has not been set, indicating that this
function should only be called from within an artifact.
Returns:
str: The name of the current module.
"""
if not Context._module_name:
raise ValueError("Context not set. This function should be" +
" called from within an artifact.")
return Context._module_name
@staticmethod
def get_module_file_path():
"""
Returns the file path of the current module set in the Context.
Raises:
ValueError: If the module file path is not set in the Context,
indicating that this function was called outside of an artifact
context.
Returns:
str: The file path of the current module.
"""
if not Context._module_file_path:
raise ValueError("Context not set. This function should be" +
" called from within an artifact.")
return Context._module_file_path
@staticmethod
def get_artifact_name():
"""
Retrieves the current artifact name from the Context.
Raises:
ValueError: If the artifact name has not been set in the Context,
indicating that this function was called outside of an artifact
context.
Returns:
str: The name of the current artifact.
"""
if not Context._artifact_name:
raise ValueError("Context not set. This function should be" +
" called from within an artifact.")
return Context._artifact_name
@staticmethod
def get_artifact_func_name():
"""
Retrieves the current artifact processor function name from the Context.
Raises:
ValueError: If the function name has not been set in the Context.
Returns:
str: The function name of the current artifact.
"""
if not Context._artifact_func_name:
raise ValueError("Context not set. This function should be" +
" called from within an artifact.")
return Context._artifact_func_name
@staticmethod
def get_files_found():
"""
Retrieves the list of files found in the current context.
Raises:
ValueError: If the context has not been set, indicating that this
function should only be called from within an artifact.
Returns:
list: The list of files found in the current context.
"""
if not Context._files_found:
raise ValueError("Context not set. This function should be" +
" called from within an artifact.")
return Context._files_found
@staticmethod
def get_filename_lookup_map():
"""
Retrieves the filename lookup map, initializing it if necessary.
Returns:
dict: A mapping of filenames to their corresponding lookup values.
"""
if not Context._filename_lookup_map:
Context._filename_lookup_map = Context._build_lookup_map()
return Context._filename_lookup_map
@staticmethod
def get_source_file_path(partial_path):
"""
Finds the full source path for a given partial or relative path.
This function uses a pre-computed lookup map for high-speed searching.
It first finds candidate paths based on the filename and then verifies
the match using the full partial path provided.
Args:
partial_path (str): The partial or relative path of the file
to find.
Returns:
str: The full path of the matching source file, or None
if not found.
"""
lookup_map = Context.get_filename_lookup_map()
# Defensive check to satisfy the linter.
# This state should not be possible in practice.
if lookup_map is None:
return None
filename = basename(partial_path)
if filename in lookup_map:
candidate_paths = lookup_map[filename]
# The filename map already keyed on the exact basename, so a single
# candidate is unambiguous — return it without a pattern match.
if len(candidate_paths) == 1:
return candidate_paths[0]
# Multiple files share this basename; disambiguate by the fuller
# path. Path.match treats glob metacharacters ('[', ']', '*', '?')
# in the pattern as wildcards, so it fails for real filenames that
# contain them (e.g. "IMG_0347[1].jpg"). Try it first for backward
# compatibility, then fall back to an exact path-suffix comparison.
for candidate in candidate_paths:
if Path(candidate).match(partial_path):
return candidate
norm = partial_path.replace('\\', '/')
for candidate in candidate_paths:
cand_norm = candidate.replace('\\', '/')
if cand_norm == norm or cand_norm.endswith('/' + norm):
return candidate
return None
@staticmethod
def get_data_folder():
"""
Returns the global extraction folder path.
"""
return Context._data_folder
@staticmethod
def create_artifact_result(
headers=None,
source_path=None,
estimated_row_count=None,
async_write=False,
queue_size=5000,
batch_size=10000,
rows=None,
):
"""
Create an artifact result wrapper for modules with large row sets.
Headers, source_path, and estimated_row_count are optional and can be
set later by the module before returning the result.
"""
artifact_info = Context._artifact_info or {}
source_path_formatter = Context._normalize_source_path
writer_metadata = {
"category": artifact_info.get("category", ""),
"module_name": Context._module_name or "",
"artifact_name": Context._artifact_name or Context._module_name or "",
"func_name": Context._artifact_func_name,
"data_views": artifact_info.get("data_views"),
"artifact_icon": artifact_info.get("artifact_icon"),
}
result = ArtifactResult(
headers=headers,
source_path=source_path,
estimated_row_count=estimated_row_count,
async_write=async_write,
queue_size=queue_size,
batch_size=batch_size,
rows=rows,
writer_metadata=writer_metadata,
source_path_formatter=source_path_formatter,
)
# Kept so the core can discard a result whose module raised before returning it.
Context._artifact_result = result
return result
@staticmethod
def get_artifact_result():
"""Return the ArtifactResult the current artifact created, or None."""
return Context._artifact_result
@staticmethod
def _normalize_source_path(source_path):
"""Return extraction-relative source path metadata for reports and LAVA."""
return '\n'.join(
Context.get_relative_path(p) for p in str(source_path).split('\n'))
@staticmethod
def get_relative_path(full_path):
"""
Converts a full on-disk path into one that carries none of the
examiner's own filesystem layout.
Two prefixes are stripped, in this order:
1. the data folder, where the seeker stages evidence, so a staged
file is reported by its path inside the extraction;
2. the report folder, so a file the run itself writes is reported by
its path inside the report.
The second case exists for artifacts that declare no search paths. The
main script hands those '<report folder>/_lava_artifacts.db' as their
source file, because they read the rows a previous artifact wrote
rather than any file in the extraction. That path is outside the data
folder, so before this it was reported unchanged and the examiner's own
report directory reached both the "located at" line and the LAVA
manifest's source_path.
The data folder is tried first because it sits inside the report
folder: stripping the report folder first would leave every staged
evidence path prefixed with 'data/'.
Args:
full_path (str): The full path to the file.
Returns:
str: The relative path, or the original path if neither prefix is
known or present.
"""
if not full_path:
return full_path
for base in (Context._data_folder, Context._output_folder_base):
if base and base in full_path:
# Strip the base path everywhere it appears, including inside path
# strings concatenated with arbitrary separators (', ', '; ', ...)
return (full_path.replace(base + '/', '')
.replace(base + '\\', '')
.replace(base, '')
.lstrip('/\\'))
return full_path
@staticmethod
def get_apple_os_version(build, device_family=''):
"""
Returns the Apple operating system version corresponding to a given
build number and device family.
Args:
build (str): The build number to look up.
device_family (str, optional): The device family (e.g., 'iPhone',
'iPad', 'Mac', 'RealityDevice', 'Watch', 'AppleTV').
Defaults to ''.
Returns:
str: The OS version string associated with the build and device
family. If not found, returns an empty string.
"""
group = None
if 'iPhone' in device_family:
group = 'iOS'
elif 'iPad' in device_family:
group = 'iOS'
elif 'Mac' in device_family:
group = 'macOS'
elif 'RealityDevice' in device_family:
group = 'visionOS'
elif 'Watch' in device_family:
group = 'watchOS'
elif 'AppleTV' in device_family:
group = 'tvOS'
resolved = Context.lookup_metadata(
'apple_build_id_to_os_version', build, group)
if not resolved:
return ''
if 'iPad' in device_family:
try:
build_major = int(re.match(r'^(\d+)', build).group(1))
if build_major >= 17:
resolved = resolved.replace('iOS', 'iPadOS', 1)
except (TypeError, ValueError, AttributeError):
pass
return resolved
@staticmethod
def get_installed_os_version():
"""
Retrieves the OS version of the installed device.
"""
return Context._installed_os_version
@staticmethod
def clear():
"""
Resets all context-related class variables to None, effectively
clearing any stored state or references, except for the metadata
cache and output parameters which are retained for efficiency.
"""
Context._report_folder = None
Context._seeker = None
Context._artifact_info = None
Context._module_name = None
Context._module_file_path = None
Context._artifact_name = None
Context._artifact_func_name = None
Context._artifact_result = None
Context._files_found = []
Context._filename_lookup_map = {}