-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsaferpickle.py
More file actions
1477 lines (1257 loc) · 46 KB
/
saferpickle.py
File metadata and controls
1477 lines (1257 loc) · 46 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
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Pickle hook to detect malicious content in pickle files."""
import concurrent.futures
import contextlib
import dataclasses
import functools
import importlib
import io
import lzma
import math
from multiprocessing import shared_memory
import os
import pickle
import pickletools
import re
import sys
import tarfile
import tempfile
import threading
from typing import Any, BinaryIO, Callable, Dict, Iterator, Optional, Set, Tuple
import zipfile
from absl import logging
from third_party.corrupy import picklemagic
import multiprocessing
from lib import config
from lib import constants
from lib import exceptions
from lib import utils
IllegalArgumentCombinationError = exceptions.IllegalArgumentCombinationError
StrictCheckError = exceptions.StrictCheckError
UnsafePickleDetectedError = exceptions.UnsafePickleDetectedError
MaxRecursionDepthExceededError = exceptions.MaxRecursionDepthExceededError
# Global flag for debug mode
DEBUG_MODE = False
IS_COLAB_ENABLED = "google.colab" in sys.modules
Classification = utils.Classification
@dataclasses.dataclass
class ScanResults:
"""Results from a pickle security scan."""
safe_results: Set[str] = dataclasses.field(default_factory=set)
unsafe_results: Set[str] = dataclasses.field(default_factory=set)
suspicious_results: Set[str] = dataclasses.field(default_factory=set)
unknown_results: Set[str] = dataclasses.field(default_factory=set)
is_denylisted: bool = False
def _custom_genops(
pickle_bytes: bytes,
) -> Iterator[tuple[pickletools.OpcodeInfo, Any | None]]:
"""Generates string-declaring opcodes and their arguments from pickle data.
Args:
pickle_bytes: The pickle data to generate opcodes from.
Yields:
A tuple of (opcode, opcode_argument) for each string-declaring opcode.
"""
if isinstance(pickle_bytes, bytes):
pickle_file = io.BytesIO(pickle_bytes)
else:
pickle_file = pickle_bytes
while True:
charcode = pickle_file.read(1)
if not charcode: # Indicates exhaustion of the data stream
break
try:
opcode = constants.OPCODES_INFO_INT.get(charcode[0])
except IndexError:
continue # Skip invalid opcode bytes
if opcode is None:
# We skip processing unknown opcodes
continue
opcode_argument = None
if opcode.arg is not None:
try:
opcode_argument = opcode.arg.reader(pickle_file)
except (
ValueError,
IndexError,
AttributeError,
EOFError,
TypeError,
ImportError,
pickle.UnpicklingError,
):
# Continue if we can't read the argument
continue
# We only yield opcodes that declare strings and have arguments
should_yield = False
for relevant_opcode_substr in constants.OPCODE_SUBSTRS_THAT_DECLARE_STRINGS:
if relevant_opcode_substr in opcode.name:
should_yield = True
break
if (
should_yield
and opcode_argument is not None # Exclude opcodes without arguments
):
# This is to be careful while processing opcode arguments. This was
# borrowed from what works in the chunked version.
if isinstance(opcode_argument, (str, bytes)) and len(opcode_argument) > 1:
yield opcode, opcode_argument
elif isinstance(opcode_argument, tuple):
yield opcode, opcode_argument
if charcode == b".":
break
def _custom_chunked_genops(
pickle_file: BinaryIO,
chunk_range: Tuple[int, int],
) -> Iterator[tuple[pickletools.OpcodeInfo, Any | None]]:
"""Generates string-declaring opcodes and arguments from a chunk.
This function reads a specific byte range (chunk) of the pickle bytecode
and yields opcodes that are known to declare strings, along with their
arguments. It's designed to be used in parallel for large pickle files.
Args:
pickle_file: The pickle data stream to generate opcodes from.
chunk_range: A tuple (start, end) defining the byte range to process.
Yields:
A tuple of (opcode, opcode_argument) for each string-declaring opcode.
"""
pickle_file.seek(chunk_range[0])
while True:
current_file_position = pickle_file.tell()
if not (chunk_range[0] <= current_file_position < chunk_range[1]):
break
charcode = pickle_file.read(1)
if not charcode: # Indicates exhaustion of the data stream
break
try:
opcode = constants.OPCODES_INFO_INT.get(charcode[0])
except IndexError:
continue # Skip invalid opcode bytes
if opcode is None:
# We skip processing unknown opcodes
if not charcode:
break
continue
opcode_argument = None
if opcode.arg is not None:
pos_before_arg_read = pickle_file.tell()
try:
opcode_argument = opcode.arg.reader(pickle_file)
new_pos = pickle_file.tell()
# Ensure we don't read past the chunk boundary accidentally
if new_pos > chunk_range[1]:
pickle_file.seek(pos_before_arg_read)
continue
except (
ValueError,
IndexError,
AttributeError,
EOFError,
TypeError,
ImportError,
pickle.UnpicklingError,
):
# Continue if we can't read the argument within the chunk
pickle_file.seek(pos_before_arg_read)
continue
# We only yield opcodes that declare strings and have arguments
should_yield = False
for relevant_opcode_substr in constants.OPCODE_SUBSTRS_THAT_DECLARE_STRINGS:
if relevant_opcode_substr in opcode.name:
should_yield = True
break
if (
should_yield
and opcode_argument is not None # Exclude opcodes without arguments
):
# Filter to ensure the argument is string-like if needed
if isinstance(opcode_argument, (str, bytes)) and len(opcode_argument) > 1:
yield opcode, opcode_argument
elif isinstance(
opcode_argument, tuple
): # Sometimes these arguments are memoized tuples
yield opcode, opcode_argument
if charcode == b".":
break
def _process_chunk_for_generate_ops(
pickle_data_source: str | bytes,
chunk_range: Tuple[int, int],
is_shared_memory: bool = False,
) -> Set[str]:
"""Helper function to process a chunk of pickle data."""
chunked_operands = set()
try:
if is_shared_memory:
shm = shared_memory.SharedMemory(name=pickle_data_source)
# Use BytesIO on the memoryview for compatibility with
# _custom_chunked_genops
data_view = shm.buf
with io.BytesIO(data_view) as f:
for _, operand in _custom_chunked_genops(f, chunk_range):
if operand is None:
continue
chunked_operands.add(str(operand))
else:
with open(pickle_data_source, "rb") as f:
f.seek(chunk_range[0])
chunk_data = f.read(chunk_range[1] - chunk_range[0])
with io.BytesIO(chunk_data) as memory_f:
for _, operand in _custom_chunked_genops(
memory_f, (0, len(chunk_data))
):
if operand is None:
continue
chunked_operands.add(str(operand))
except StopIteration:
pass
return chunked_operands
def generate_ops_from_file(
pickle_file_path: str,
shm_name: Optional[str] = None,
pickle_length: Optional[int] = None,
) -> Set[str]:
"""Returns opcodes that declare strings from a path or shared memory.
Args:
pickle_file_path: The path to the pickle file.
shm_name: Optional name of the shared memory block.
pickle_length: Optional length of the pickle data.
Returns:
genops_output: The operands associated with the opcodes that declare
strings.
"""
filtered_operands = set()
num_workers = utils.get_optimal_workers(pickle_length)
if (
pickle_length < constants.MIN_SIZE_FOR_CHUNKING
or not utils.is_sys_executable_patched()
):
if shm_name:
shm = shared_memory.SharedMemory(name=shm_name)
pickle_bytes = bytes(shm.buf[:pickle_length])
else:
with open(pickle_file_path, "rb") as f:
pickle_bytes = f.read()
try:
for _, operand in _custom_genops(pickle_bytes):
if operand is None:
continue
filtered_operands.add(str(operand))
except StopIteration:
pass
return filtered_operands
else:
# Divide into constants.MAX_NUM_CHUNKS for larger files
chunk_size = math.ceil(pickle_length / num_workers)
ranges = []
for chunk_index in range(num_workers):
chunk_start_size = chunk_index * chunk_size
# Extend the chunk end by CHUNK_OVERLAP, but don't exceed pickle_length
chunk_end = min(
chunk_start_size + chunk_size + constants.CHUNK_OVERLAP, pickle_length
)
if chunk_start_size < pickle_length:
ranges.append((chunk_start_size, chunk_end))
if chunk_end == pickle_length:
break # Last chunk reaches the end
ctx = multiprocessing.get_context("spawn")
with concurrent.futures.ProcessPoolExecutor(
max_workers=num_workers, mp_context=ctx
) as executor:
future_to_range_tuple = {
executor.submit(
_process_chunk_for_generate_ops,
shm_name if shm_name else pickle_file_path,
range_tuple,
is_shared_memory=bool(shm_name),
): range_tuple
for range_tuple in ranges
}
for future in concurrent.futures.as_completed(future_to_range_tuple):
try:
filtered_operands.update(future.result())
except (
EOFError,
ValueError,
IndexError,
TypeError,
) as exc:
logging.exception(
"Error processing chunk %s: %s",
future_to_range_tuple[future],
exc,
)
return filtered_operands
def generate_ops(pickle_bytes: bytes) -> Set[str]:
"""Returns string-declaring opcodes.
Args:
pickle_bytes: The pickle bytecode to yield opcode information for.
Returns:
genops_output: The operands associated with the opcodes that declare
strings.
"""
filtered_operands = set()
try:
for _, operand in _custom_genops(pickle_bytes):
if operand is None:
continue
filtered_operands.add(str(operand))
except StopIteration:
pass
return filtered_operands
def get_class_instantiations(pickle_bytes: bytes) -> tuple[io.StringIO, bool]:
"""Gets the class instantiations from a pickle file.
Args:
pickle_bytes: The pickle bytecode to disassemble.
Returns:
A tuple containing:
- picklemagic_output: Suspicious function calls from picklemagic.
- was_unsafe_build_blocked: A boolean indicating if a dangerous
state assignment was blocked by the custom load_build hook.
"""
picklemagic_output = io.StringIO()
unpickler = None
with contextlib.redirect_stdout(picklemagic_output):
try:
factory = picklemagic.FakeClassFactory([], picklemagic.FakeWarning)
# Instead of using safe_loads, we do this to get the
# has_blocked_unsafe_build_instr boolean properly.
unpickler = picklemagic.SafeUnpickler(
io.BytesIO(pickle_bytes),
class_factory=factory,
safe_modules=constants.SAFE_STRINGS,
unsafe_modules=constants.UNSAFE_STRINGS,
)
factory.default.unpickler = unpickler
# Monkey-patch load_build so that we don't miss
# BUILD instructions due to differing Pickle implementations.
original_load_build = unpickler.load_build
def fixed_load_build(*unused_args):
return original_load_build()
unpickler.load_build = fixed_load_build
unpickler.dispatch[pickle.BUILD[0]] = unpickler.load_build
unpickler.load()
# These errors are expected and should not be raised.
# Even if errors are encountered, we still get the class instantiations
# before errors occur.
except (
ValueError,
AttributeError,
TypeError,
picklemagic.FakeUnpicklingError,
pickle.UnpicklingError,
IndexError,
EOFError,
KeyError,
):
pass
is_build_instr_blocked = False
if unpickler:
is_build_instr_blocked = getattr(
unpickler, "has_blocked_unsafe_build_instr", False
)
return picklemagic_output, is_build_instr_blocked
def categorize_strings(
filtered_output: Set[str] | io.StringIO,
use_picklemagic: bool = False,
) -> ScanResults:
"""Counts strings from filtered output and categorizes them.
Args:
filtered_output: The series of statements filtered by string declarations.
use_picklemagic: If True, the filtered output is from picklemagic, otherwise
it is from genops or disassembly.
Returns:
A ScanResults object.
"""
unsafe_results: Set[str] = set()
safe_results: Set[str] = set()
suspicious_results: Set[str] = set()
unknown_results: Set[str] = set()
allow_list = config.get_allow_list()
deny_list = config.get_deny_list()
if use_picklemagic and isinstance(filtered_output, io.StringIO):
filtered_output = filtered_output.getvalue().split("\n")
for picklemagic_warning in filtered_output:
if not picklemagic_warning:
continue
picklemagic_warning_lower = picklemagic_warning.lower()
# Printable warning sourced from every suspicious invocation of
# find_class()
if picklemagic_warning_lower.startswith("warning"):
unsafe_module_match = utils.EXTRACT_UNSAFE_MODULE_REGEX.search(
picklemagic_warning_lower
)
if unsafe_module_match:
unsafe_results.add(unsafe_module_match.group(1))
# Printable warning for suspicious class instantiations
if picklemagic_warning_lower.startswith("<"):
class_args_match = utils.ARGS_REGEX.search(picklemagic_warning_lower)
if not class_args_match:
continue
class_name = class_args_match.group(1)
class_name_classification = utils.classify_class_name(class_name)
match class_name_classification:
case Classification.SAFE:
safe_results.add(class_name)
case Classification.UNSAFE:
unsafe_results.add(class_name)
case Classification.SUSPICIOUS:
suspicious_results.add(class_name)
case Classification.UNKNOWN:
unknown_results.add(class_name)
class_args = class_args_match.group(2)
for method_pattern in utils.PYTHON_METHOD_PATTERNS:
argument_finds = method_pattern.findall(class_args)
if not argument_finds:
continue
for argument_find in argument_finds:
found_match = False
for unsafe_string in constants.UNSAFE_STRINGS:
if unsafe_string in argument_find:
unsafe_results.add(argument_find)
found_match = True
for safe_string in constants.SAFE_STRINGS:
if safe_string in argument_find:
safe_results.add(argument_find)
found_match = True
for suspicious_string in constants.SUSPICIOUS_STRINGS:
if suspicious_string in argument_find:
suspicious_results.add(argument_find)
found_match = True
if not found_match and re.search(
utils.unknown_pattern, argument_find
):
unknown_results.add(argument_find)
else:
for line in filtered_output:
line_in_lowercase = line.lower()
unsafe_match = any(
unsafe_string in line_in_lowercase
for unsafe_string in constants.UNSAFE_STRINGS
) and re.findall(utils.unsafe_pattern, line_in_lowercase)
safe_match = any(
safe_string in line_in_lowercase
for safe_string in constants.SAFE_STRINGS
) and re.findall(utils.safe_pattern, line_in_lowercase)
suspicious_match = any(
suspicious_string in line_in_lowercase
for suspicious_string in constants.SUSPICIOUS_STRINGS
) and re.findall(utils.suspicious_pattern, line_in_lowercase)
if unsafe_match:
for match in unsafe_match:
unsafe_results.add(match)
elif safe_match:
for match in safe_match:
safe_results.add(match)
elif suspicious_match:
for match in suspicious_match:
suspicious_results.add(match)
else:
# Only check for unknown if no other categories matched
unknown_match = re.findall(utils.unknown_pattern, line_in_lowercase)
if unknown_match:
for match in unknown_match:
unknown_results.add(match)
# Combine results for `resolve_library_modules_from_results` call.
all_results = safe_results.union(
unsafe_results, suspicious_results, unknown_results
)
resolved_results = utils.resolve_library_modules_from_results(all_results)
# Re-categorize the resolved results
new_safe_results = set()
new_unsafe_results = set()
new_suspicious_results = set()
new_unknown_results = set()
is_denylisted = False
for result in resolved_results:
if any(result.startswith(denied_item) for denied_item in deny_list):
new_unsafe_results.add(result)
is_denylisted = True
continue
if any(result.startswith(allowed_item) for allowed_item in allow_list):
new_safe_results.add(result)
continue
if result == "builtins":
new_unknown_results.add(result)
continue
# Classify the resolved result
classification = utils.classify_class_name(result)
if classification == Classification.SAFE:
new_safe_results.add(result)
elif classification == Classification.UNSAFE:
new_unsafe_results.add(result)
elif classification == Classification.SUSPICIOUS:
new_suspicious_results.add(result)
elif classification == Classification.UNKNOWN:
# Fallback: Check against original categories if
# classify_class_name returns UNKNOWN.
if result in unsafe_results:
new_unsafe_results.add(result)
elif result in suspicious_results:
new_suspicious_results.add(result)
elif result in safe_results:
new_safe_results.add(result)
else:
new_unknown_results.add(result)
return ScanResults(
safe_results=new_safe_results,
unsafe_results=new_unsafe_results,
suspicious_results=new_suspicious_results,
unknown_results=new_unknown_results,
is_denylisted=is_denylisted,
)
def strict_security_scan(pickle_bytes: bytes) -> bool:
"""Strict security scan for malicious content in pickle files.
Args:
pickle_bytes: Pickle bytecode to scan.
Returns:
True if the pickle file is dangerous, False otherwise.
"""
for stmt in generate_ops(pickle_bytes):
for unsafe_string in constants.UNSAFE_STRINGS.union(
constants.SUSPICIOUS_STRINGS
):
if re.search(unsafe_string, stmt):
return True
# The below handles catching cases of unknown imports and state attacks.
instantiations_output, was_unsafe_build_blocked = get_class_instantiations(
pickle_bytes
)
if was_unsafe_build_blocked:
return True
instantiations = instantiations_output.getvalue().split("\n")
for instantiation in instantiations:
if re.search(utils.unknown_pattern, instantiation):
return True
# This is a noisy but necessary check for a small number of cases where
# a library is not explicitly imported but is used in a class instantiation
# in a suspicious manner.
if re.search(utils.suspicious_pattern, instantiation):
return True
return False
def is_unsafe(
number_of_safe_results: int,
number_of_unsafe_results: int,
number_of_suspicious_results: int,
) -> bool:
"""Conditional check for safeness.
Args:
number_of_safe_results: Number of safe results from the security scan.
number_of_unsafe_results: Number of unsafe results from the security scan.
number_of_suspicious_results: Number of suspicious results from the security
scan.
Returns:
True if the pickle file is dangerous, False otherwise.
"""
if number_of_unsafe_results == 0 and number_of_suspicious_results == 0:
return False
# We halve the weight of suspicious results to lower false positives
# caused by greedy matches of unknown method-like strings (Ex. "google.com")
if (
number_of_suspicious_results + number_of_unsafe_results
>= number_of_safe_results
):
return True
sum_of_unsafe_and_suspicious_results = (
number_of_unsafe_results + 0.5 * number_of_suspicious_results
)
unsafe = (sum_of_unsafe_and_suspicious_results > number_of_safe_results) or (
number_of_safe_results == 0 and sum_of_unsafe_and_suspicious_results >= 1
)
return unsafe
def picklemagic_scan(
pickle_bytes: bytes,
) -> ScanResults:
"""Picklemagic scan for malicious content in pickle files.
Args:
pickle_bytes: Pickle bytecode to scan.
Returns:
A ScanResults object.
"""
picklemagic_output, was_unsafe_build_blocked = get_class_instantiations(
pickle_bytes
)
results = categorize_strings(picklemagic_output, use_picklemagic=True)
if was_unsafe_build_blocked:
# Temporary addition to increase number of suspicious results given the
# current scoring implementation. This will be removed in the future.
results.suspicious_results.add("unsafe_state_assignment")
return results
def genops_scan(
pickle_bytes: bytes,
pickle_file_path: Optional[str] = None,
shm_name: Optional[str] = None,
) -> ScanResults:
"""Genops scan for malicious content in pickle files.
Args:
pickle_bytes: Pickle bytecode to scan.
pickle_file_path: Optional path to the pickle file for streaming scan.
shm_name: Optional name of the shared memory block.
Returns:
A ScanResults object.
"""
if shm_name:
genops_output = generate_ops_from_file(
"", shm_name=shm_name, pickle_length=len(pickle_bytes)
)
elif pickle_file_path:
genops_output = generate_ops_from_file(
pickle_file_path, pickle_length=len(pickle_bytes)
)
else:
genops_output = generate_ops(pickle_bytes)
results = categorize_strings(genops_output)
return results
def score_results(
safe_results: Set[str],
unsafe_results: Set[str],
suspicious_results: Set[str],
unknown_results: Set[str],
) -> Tuple[int, int, int, int]:
"""Count the results from the security scan.
Args:
safe_results: List of safe strings.
unsafe_results: List of unsafe strings.
suspicious_results: List of suspicious strings.
unknown_results: List of unknown strings.
Returns:
A tuple of safe, unsafe, suspicious, and unknown scores.
"""
number_of_safe_results = len(safe_results)
number_of_unsafe_results = len(unsafe_results)
number_of_suspicious_results = len(suspicious_results)
number_of_unknown_results = len(unknown_results)
safe_score = math.log(number_of_safe_results + 1) * 2
unsafe_score = math.log(number_of_unsafe_results + 1) * 4
suspicious_score = math.log(number_of_suspicious_results + 1) * 3
unknown_score = math.log(number_of_unknown_results + 1) * 1
return (
round(safe_score),
round(unsafe_score),
round(suspicious_score),
round(unknown_score),
)
def apply_approach(
scan_approach: Callable[..., ScanResults],
pickle_bytes: bytes,
pickle_file_path: Optional[str] = None,
shm_name: Optional[str] = None,
) -> Dict[str, int]:
"""Applies the given scan approach to the data.
Args:
scan_approach: The scan approach to apply to the data.
pickle_bytes: The data to scan.
pickle_file_path: Optional path to the pickle file for streaming scan.
shm_name: Optional name of the shared memory block.
Returns:
A dictionary of the resulting scores.
"""
if scan_approach is genops_scan:
results = scan_approach(
pickle_bytes, pickle_file_path=pickle_file_path, shm_name=shm_name
)
else:
results = scan_approach(pickle_bytes)
if DEBUG_MODE:
logging.info("Scan approach: %s", scan_approach.__name__)
logging.info(" Safe results: %s", results.safe_results)
logging.info(" Unsafe results: %s", results.unsafe_results)
logging.info(" Suspicious results: %s", results.suspicious_results)
logging.info(" Unknown results: %s\n", results.unknown_results)
(
number_of_safe_results,
number_of_unsafe_results,
number_of_suspicious_results,
number_of_unknown_results,
) = score_results(
results.safe_results,
results.unsafe_results,
results.suspicious_results,
results.unknown_results,
)
scores = {
"unsafe": number_of_unsafe_results,
"suspicious": number_of_suspicious_results,
"unknown": number_of_unknown_results,
}
if results.is_denylisted or is_unsafe(
number_of_safe_results,
number_of_unsafe_results,
number_of_suspicious_results,
):
return scores
scores["unsafe"] = 0
scores["suspicious"] = 0
return scores
@functools.lru_cache(maxsize=None)
def security_scan(
pickle_bytes: bytes,
force_scan: bool = False,
recursion_depth: int = 0,
) -> Dict[str, int]:
"""Security scan to detect malicious content in pickle files.
Args:
pickle_bytes: Pickle bytecode to scan.
force_scan: If True, force scan even if the file is not a pickle file.
recursion_depth: Current recursion depth for nested archives.
Returns:
A dictionary containing the scores for unsafe, suspicious, and unknown
results.
"""
if recursion_depth > 10:
raise MaxRecursionDepthExceededError("Max recursion depth of 10 exceeded.")
if recursion_depth > 3:
logging.warning("Suspiciously deep recursion depth of %d", recursion_depth)
# Check for compression signatures
if utils.is_zip_bytes(pickle_bytes):
return _extract_and_scan_archive(pickle_bytes, "zip", recursion_depth)
elif utils.is_bz2_bytes(pickle_bytes):
return _extract_and_scan_archive(pickle_bytes, "bz2", recursion_depth)
elif utils.is_lzma_bytes(pickle_bytes):
return _extract_and_scan_archive(pickle_bytes, "lzma", recursion_depth)
elif utils.is_gzip_bytes(pickle_bytes):
return _extract_and_scan_archive(pickle_bytes, "gzip", recursion_depth)
elif utils.is_tar_bytes(pickle_bytes):
return _extract_and_scan_archive(pickle_bytes, "tar", recursion_depth)
return _security_scan_internal(pickle_bytes, force_scan)
def _merge_scores(total: Dict[str, int], new: Dict[str, int]):
total["unsafe"] += new.get("unsafe", 0)
total["suspicious"] += new.get("suspicious", 0)
total["unknown"] += new.get("unknown", 0)
def _extract_and_scan_archive(
data: bytes, archive_type: str, recursion_depth: int
) -> Dict[str, int]:
"""Extracts and scans contents of an archive."""
all_scores = {"unsafe": 0, "suspicious": 0, "unknown": 0}
try:
if archive_type == "zip":
with zipfile.ZipFile(io.BytesIO(data)) as zf:
for name in zf.namelist():
if ".." in name or name.startswith("/"):
# Zip slip detection
logging.warning("Zip slip detected: %s", name)
return {
"unsafe": constants.HIGH_SEVERITY_ZIPSLIP,
"suspicious": 0,
"unknown": 0,
} # Return early
with zf.open(name) as f:
content = f.read()
scores = security_scan(content, recursion_depth=recursion_depth + 1)
_merge_scores(all_scores, scores)
elif archive_type == "bz2":
content = utils.extract_bz2_contents(data)
scores = security_scan(content, recursion_depth=recursion_depth + 1)
_merge_scores(all_scores, scores)
elif archive_type == "lzma":
content = utils.extract_lzma_contents(data)
scores = security_scan(content, recursion_depth=recursion_depth + 1)
_merge_scores(all_scores, scores)
elif archive_type == "gzip":
content = utils.extract_gzip_contents(data)
scores = security_scan(content, recursion_depth=recursion_depth + 1)
_merge_scores(all_scores, scores)
elif archive_type == "tar":
for name, content in utils.extract_tar_contents(data):
if ".." in name or name.startswith("/"):
logging.warning("Tar slip detected: %s", name)
return {
"unsafe": constants.HIGH_SEVERITY_ZIPSLIP,
"suspicious": 0,
"unknown": 0,
} # Return early
scores = security_scan(content, recursion_depth=recursion_depth + 1)
_merge_scores(all_scores, scores)
else:
logging.warning("Unsupported archive type: %s", archive_type)
return {
"unsafe": 0,
"suspicious": 0,
"unknown": constants.HIGH_SEVERITY_ZIPSLIP,
}
except MaxRecursionDepthExceededError:
raise
except (
zipfile.BadZipFile,
tarfile.TarError,
lzma.LZMAError,
OSError,
EOFError,
ValueError,
) as e:
logging.exception("Error processing %s archive: %s", archive_type, e)
# Fallback to normal scan if extraction fails
return _security_scan_internal(data, force_scan=False)
return all_scores
def _security_scan_internal(
pickle_bytes: bytes, force_scan: bool = False
) -> Dict[str, int]:
"""Security scan to detect malicious content in pickle files.
Args:
pickle_bytes: Pickle bytecode to scan.
force_scan: If True, force scan even if the file is not a pickle file.
Returns:
A dictionary containing the scores for unsafe, suspicious, and unknown
finds.
"""
if utils.is_zip_bytes(pickle_bytes):
total_scores = {"unsafe": 0, "suspicious": 0, "unknown": 0}
unzipped_files = utils.extract_zip_contents(pickle_bytes)
for unzipped_file in unzipped_files:
filename, file_bytes = unzipped_file
if (
not utils.is_pickle_file(file_bytes) or not file_bytes
) and not force_scan:
if DEBUG_MODE:
print(f"Skipping non-pickle file: {filename}")
continue
if DEBUG_MODE:
print(f"Scanning unzipped pickle file: {filename}")
inner_scores = security_scan(file_bytes)
if inner_scores["unsafe"] > 0 or inner_scores["suspicious"] > 0:
return inner_scores # Fail fast for zips
# Accumulate scores from safe files
total_scores["unknown"] += inner_scores["unknown"]
return total_scores
if not utils.is_pickle_file(pickle_bytes) and not force_scan:
return {"unsafe": 0, "suspicious": 0, "unknown": 0}
pickle_file_path = None
shm = None
shm_name = None
if len(pickle_bytes) >= constants.MIN_SIZE_FOR_CHUNKING:
try:
shm = shared_memory.SharedMemory(create=True, size=len(pickle_bytes))
shm_name = shm.name
shm.buf[: len(pickle_bytes)] = pickle_bytes
except Exception: # pylint: disable=broad-except