forked from google/saferpickle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafer_pickle.py
More file actions
1355 lines (1137 loc) · 41.6 KB
/
safer_pickle.py
File metadata and controls
1355 lines (1137 loc) · 41.6 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 enum
import functools
import importlib
import io
import math
import pickle
import pickletools
import re
import sys
import threading
from typing import Any, Callable, Dict, Iterator, Optional, Set, Tuple
from absl import logging
from third_party.corrupy import picklemagic
import multiprocessing
from lib import config
from lib import constants
from lib import utils
class IllegalArgumentCombinationError(Exception):
"""Custom exception for using allow_unsafe and strict_check together."""
def __init__(self, m: str) -> None:
self.message = m
def __str__(self) -> str:
return self.message
class StrictCheckError(Exception):
"""Custom exception for strict check failures."""
def __init__(self, m: str) -> None:
self.message = m
def __str__(self) -> str:
return self.message
class UnsafePickleDetectedError(Exception):
"""Custom exception for unsafe pickle files."""
def __init__(self, m: str) -> None:
self.message = m
def __str__(self) -> str:
return self.message
# Global flag for debug mode
DEBUG_MODE = False
IS_COLAB_ENABLED = "google.colab" in sys.modules
@enum.unique
class Classification(enum.Enum):
"""Classification of a class name."""
SAFE = "SAFE"
UNSAFE = "UNSAFE"
SUSPICIOUS = "SUSPICIOUS"
UNKNOWN = "UNKNOWN"
@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 Exception: # pylint: disable=broad-except
# 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_bytes: bytes,
chunk_range: Tuple[int, int],
) -> Iterator[tuple[pickletools.OpcodeInfo, Any | None]]:
"""Generates string-declaring opcodes and arguments from a chunk of pickle data.
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_bytes: The pickle data 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.
"""
if isinstance(pickle_bytes, bytes):
pickle_file = io.BytesIO(pickle_bytes)
else:
pickle_file = pickle_bytes
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 Exception: # pylint: disable=broad-except
# 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 get_optimal_workers(file_size: int) -> int:
"""Calculates the optimal number of workers based on the file size using tiers.
Args:
file_size: The size of the file in bytes.
Returns:
The optimal number of workers to use.
"""
for threshold, workers in constants.WORKER_TIERS:
if file_size < threshold:
return min(constants.MAX_NUM_CHUNKS or 1, workers)
# If file size is larger than or equal to the largest threshold,
# use logarithmic scaling.
largest_threshold, largest_workers = constants.WORKER_TIERS[-1]
# Ensure largest_workers is capped at MAX_NUM_CHUNKS before scaling up.
largest_workers = min(largest_workers, constants.MAX_NUM_CHUNKS or 1)
scaled_workers = largest_workers + int(
math.log(file_size / largest_threshold, 2)
)
# Cap at around half the number of available CPU cores.
return min(constants.MAX_NUM_CHUNKS or 1, scaled_workers)
def _process_chunk_for_generate_ops(
pickle_bytes: bytes, chunk_range: Tuple[int, int]
) -> Set[str]:
"""Helper function for generate_ops to process a chunk of pickle data."""
chunked_operands = set()
try:
for _, operand in _custom_chunked_genops(pickle_bytes, chunk_range):
if operand is None:
continue
chunked_operands.add(str(operand))
except StopIteration:
pass
return chunked_operands
def generate_ops(pickle_bytes: bytes) -> Set[str]:
"""Returns opcodes that declare strings from a pickle file.
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()
pickle_length = len(pickle_bytes)
num_workers = get_optimal_workers(pickle_length)
# If sys.executable does not have a value or is not a valid
# Python interpreter, we don't use multiprocessing.
if (
pickle_length < constants.MIN_SIZE_FOR_CHUNKING
or not utils.is_sys_executable_patched()
):
# Use the original non-chunked version for smaller files
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, pickle_bytes, range_tuple
): 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 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
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 = getattr(
unpickler, "has_blocked_unsafe_build_instr", False
)
return picklemagic_output, is_build_instr_blocked
@functools.lru_cache(maxsize=None)
def classify_class_name(class_name: str) -> Classification | None:
"""Classifies a class name based on the safe, unsafe, and suspicious patterns."""
if re.search(utils.safe_pattern, class_name):
return Classification.SAFE
if re.search(utils.unsafe_pattern, class_name):
return Classification.UNSAFE
if re.search(utils.suspicious_pattern, class_name):
return Classification.SUSPICIOUS
if re.search(utils.unknown_pattern, class_name):
return Classification.UNKNOWN
return None
def categorize_strings(
filtered_output: Set[str] | io.StringIO,
use_picklemagic: bool = False,
) -> ScanResults:
"""Counts the relevant strings from the 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 = 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 = 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:
new_unknown_results.add(result)
else:
# Fallback: Check against original categories if
# classify_class_name returns None.
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 to detect 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 to detect 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,
) -> ScanResults:
"""Genops scan to detect malicious content in pickle files.
Args:
pickle_bytes: Pickle bytecode to scan.
Returns:
A ScanResults object.
"""
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[[bytes], ScanResults],
pickle_bytes: bytes,
) -> 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.
Returns:
A dictionary of the resulting scores.
"""
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
) -> 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}
final_scores = {"unsafe": 0, "suspicious": 0, "unknown": 0}
# Fastest to slowest scan (tiered approach)
for scan_approach in [picklemagic_scan, genops_scan]:
scores = apply_approach(scan_approach, pickle_bytes)
if scores["unsafe"] > 0 or scores["suspicious"] > 0:
return scores
final_scores["unknown"] += scores["unknown"]
return final_scores
_thread_local_storage_for_hooking = threading.local()
def _report_or_raise(
classification: Classification, report_only: bool, log_info=False
):
"""Reports or raises an error based on classification and report_only flag."""
# This attempts to catch external exceptions raised by libraries
# using SaferPickle and re-raise them to maintain the original failures for
# unit tests.
exc_info = sys.exc_info()
external_exception_caught = (
exc_info[0] is not None and exc_info[1] is not None
)
if report_only:
logging_function = logging.info if log_info else logging.error
logging_function(
constants.ERROR_STRING.substitute(classification=classification.value)
)
if external_exception_caught:
# Re-raise the exception that was active when _report_or_raise was called.
if exc_info[2] is not None:
raise exc_info[1].with_traceback(exc_info[2])
raise exc_info[1]
return
raise UnsafePickleDetectedError(
constants.ERROR_STRING.substitute(classification=classification.value)
)
def _scan_and_load(
pickle_file_or_bytes: io.IOBase | bytes,
allow_unsafe: bool,
strict_check: bool,
report_only: bool,
force_scan: bool,
hooked_mod_name: str,
is_load: bool,
log_info: bool,
*args: Any,
**kwargs: Any,
):
"""Internal helper to scan and load pickle data."""
if is_load:
if not isinstance(pickle_file_or_bytes, io.IOBase):
raise TypeError("pickle_file_or_bytes must be IOBase when is_load=True")
pickle_file = pickle_file_or_bytes
data_bytes = pickle_file.read()
if hasattr(pickle_file, "seek"):
pickle_file.seek(0)
else:
pickle_file = io.BytesIO(data_bytes)
else:
if not isinstance(pickle_file_or_bytes, bytes):
raise TypeError("pickle_file_or_bytes must be bytes when is_load=False")
data_bytes = pickle_file_or_bytes
pickle_file = None
loader_mod = COPIED_MODS_MAP.get(hooked_mod_name)
if not loader_mod:
loader_mod = pickle_copy
if strict_check and allow_unsafe:
error_string_illegal_combination = (
"Strict scanning and allow_unsafe cannot be used together."
)
if report_only:
logging.error(error_string_illegal_combination)
return
raise IllegalArgumentCombinationError(error_string_illegal_combination)
if is_load:
load_func = loader_mod.load
load_args = (pickle_file,)
else:
load_func = loader_mod.loads
load_args = (data_bytes,)
if allow_unsafe:
if report_only:
logging.info("Loading pickle file with allow_unsafe set to True.")
try:
return load_func(*load_args, *args, **kwargs)
except AttributeError as exc:
logging.info("Could not load an absent class: %s", exc)
return
if strict_check:
if strict_security_scan(data_bytes):
error_string_strict_check = "Pickle file failed strict security check."
if report_only:
logging.error(error_string_strict_check)
return
raise StrictCheckError(error_string_strict_check)
try:
return load_func(*load_args, *args, **kwargs)
except (AttributeError, pickle.UnpicklingError) as exc:
if "persistent load" in str(exc):
logging.info("Persistent load error: %s", exc)
return
elif "Can't get attribute" in str(exc):
logging.exception(
"Could not load an absent class: %s", exc, exc_info=True
)
raise UnsafePickleDetectedError(
constants.ERROR_STRING.substitute(
classification=Classification.SUSPICIOUS.value
)
) from exc
elif "underflow" in str(exc):
raise
logging.exception("Unknown error: %s", exc, exc_info=True)
return
# If we get here, we are not in strict check or allow_unsafe mode.
# We perform non-strict scanning as usual with force_scan if needed.
scan_scores = security_scan(data_bytes, force_scan=force_scan)
number_of_unsafe_results = scan_scores["unsafe"]
number_of_suspicious_results = scan_scores["suspicious"]
number_of_unknown_results = scan_scores["unknown"]
if number_of_suspicious_results == 0 and number_of_unsafe_results == 0:
if report_only:
logging.info("Loading safe pickle file")
if number_of_unknown_results > 0:
logging.warning(
"SaferPickle: File contains %d unknown items that were ignored.",
number_of_unknown_results,
)
try:
return load_func(*load_args, *args, **kwargs)
except (AttributeError, pickle.UnpicklingError) as exc:
if "persistent load" in str(exc):
logging.info("Persistent load error: %s", exc)
return
elif "Can't get attribute" in str(exc):
logging.exception(
"Could not load an absent class: %s", exc, exc_info=True
)
raise UnsafePickleDetectedError(
constants.ERROR_STRING.substitute(