-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpickle_scanner.py
More file actions
6406 lines (5869 loc) · 265 KB
/
pickle_scanner.py
File metadata and controls
6406 lines (5869 loc) · 265 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
"""Scanner for Python pickle serialized files (.pkl, .pickle)."""
import io
import os
import pickletools
import struct
import time
from typing import Any, BinaryIO, ClassVar, TypeGuard
from modelaudit.analysis.enhanced_pattern_detector import EnhancedPatternDetector, PatternMatch
from modelaudit.analysis.entropy_analyzer import EntropyAnalyzer
from modelaudit.analysis.framework_patterns import FrameworkKnowledgeBase
from modelaudit.analysis.ml_context_analyzer import MLContextAnalyzer
from modelaudit.analysis.opcode_sequence_analyzer import OpcodeSequenceAnalyzer
from modelaudit.analysis.semantic_analyzer import SemanticAnalyzer
from modelaudit.detectors.suspicious_symbols import (
BINARY_CODE_PATTERNS,
CVE_BINARY_PATTERNS,
EXECUTABLE_SIGNATURES,
SUSPICIOUS_GLOBALS,
SUSPICIOUS_STRING_PATTERNS,
)
from modelaudit.utils.helpers.code_validation import (
is_code_potentially_dangerous,
validate_python_syntax,
)
from modelaudit.utils.helpers.ml_context import get_ml_context_explanation
from ..config.explanations import (
get_import_explanation,
get_opcode_explanation,
get_pattern_explanation,
)
from ..detectors.cve_patterns import analyze_cve_patterns, enhance_scan_result_with_cve
from ..detectors.suspicious_symbols import DANGEROUS_OPCODES
from .base import BaseScanner, CheckStatus, IssueSeverity, ScanResult, logger
from .rule_mapper import (
get_embedded_code_rule_code,
get_encoding_rule_code,
get_generic_rule_code,
get_import_rule_code,
get_pickle_opcode_rule_code,
)
_RESYNC_BUDGET = 8192 # Max bytes to scan forward when resyncing after an unknown opcode
COPYREG_EXTENSION_MODULE = "__copyreg_extension__"
COPYREG_EXTENSION_PREFIX = "code_"
def _scan_structural_tamper_findings(file_data: bytes) -> list[dict[str, Any]]:
"""Detect structurally suspicious pickle stream patterns.
This scanner intentionally focuses on true pickle-structure violations and keeps
severity low so malformed/truncated payloads are visible without overshadowing
direct code-execution signals.
"""
findings: list[dict[str, Any]] = []
if not file_data:
return findings
offset = 0
max_separator_skip = 256
while offset < len(file_data):
stream = file_data[offset:]
bio = io.BytesIO(stream)
stream_opcode_count = 0
stream_had_stop = False
seen_proto_version: int | None = None
try:
for opcode, arg, pos in pickletools.genops(bio):
stream_opcode_count += 1
opcode_pos = int(pos) if pos is not None else 0
absolute_pos = offset + opcode_pos
if opcode.name == "PROTO":
if stream_opcode_count > 1:
findings.append(
{
"kind": "misplaced_proto",
"stream_offset": offset,
"position": absolute_pos,
"protocol": arg,
}
)
if seen_proto_version is not None:
findings.append(
{
"kind": "duplicate_proto",
"stream_offset": offset,
"position": absolute_pos,
"protocol": arg,
"previous_protocol": seen_proto_version,
}
)
seen_proto_version = int(arg) if isinstance(arg, int) else None
if opcode.name == "STOP":
stream_had_stop = True
offset = absolute_pos + 1
break
except ValueError:
# Do not emit standalone invalid-opcode findings here. Legitimate
# pickle-adjacent formats can contain binary tails or protocol/
# opcode mismatches that trigger parser errors after a valid
# prefix, and surfacing those as tamper findings is too noisy.
# Instead, resync to the next likely binary pickle stream and
# continue looking for true structural violations.
probe_start = min(offset + 1, len(file_data))
probe_end = min(offset + _RESYNC_BUDGET, len(file_data))
next_offset = -1
for idx in range(probe_start, probe_end - 1):
if file_data[idx] == 0x80 and file_data[idx + 1] in (2, 3, 4, 5):
next_offset = idx
break
if next_offset >= 0:
offset = next_offset
continue
# If there is no next stream candidate, treat remaining bytes as non-pickle tail.
break
except Exception:
# Structural tamper detection is opportunistic and must not change
# the scanner's existing error-handling behavior for parse limits
# or framework-specific edge cases.
break
if stream_had_stop:
skipped = 0
while offset < len(file_data) and skipped < max_separator_skip:
if file_data[offset] == 0x80 and offset + 1 < len(file_data) and file_data[offset + 1] in (2, 3, 4, 5):
break
offset += 1
skipped += 1
if skipped >= max_separator_skip and offset < len(file_data):
break
continue
# No STOP and no exception means empty parse; advance to avoid infinite loop.
offset += 1
return findings
def _genops_with_fallback(file_obj: BinaryIO, *, multi_stream: bool = False) -> Any:
"""
Wrapper around pickletools.genops that handles protocol mismatches.
Some files (especially joblib) may declare protocol 4 but use protocol 5 opcodes
like READONLY_BUFFER (0x0f). This function attempts to parse as much as possible
before hitting unknown opcodes, then tries to resync and continue scanning
rather than terminating on partial stream errors.
When *multi_stream* is True the generator continues parsing after the first STOP
opcode so that malicious payloads hidden in a second pickle stream are not missed.
Non-pickle separator bytes between streams are skipped (up to a limit) so that a
single junk byte cannot bypass detection.
Yields: (opcode, arg, pos) tuples from pickletools.genops
"""
# Maximum number of consecutive non-pickle bytes to skip when resyncing
_MAX_RESYNC_BYTES = 256
resync_skipped = 0
# Track whether we've successfully parsed at least one complete stream
parsed_any_stream = False
while True:
stream_start = file_obj.tell()
had_opcodes = False
stream_error = False
if not parsed_any_stream:
# First stream: yield opcodes directly (no buffering needed)
try:
for item in pickletools.genops(file_obj):
had_opcodes = True
yield item
except ValueError as e:
error_str = str(e).lower()
is_unknown_opcode = "opcode" in error_str and "unknown" in error_str
is_decode_or_text_error = (
isinstance(e, UnicodeDecodeError)
or "unicode" in error_str
or "codec can't decode" in error_str
or "no newline found" in error_str
)
if is_unknown_opcode or is_decode_or_text_error:
if had_opcodes:
logger.info(
"Pickle stream parsing interrupted after partial opcode extraction; "
"continuing with partial security analysis"
)
stream_error = True
elif is_unknown_opcode:
# Keep prior behavior for joblib-style protocol/opcode mismatches.
logger.info(
f"Protocol mismatch in pickle (joblib may use protocol 5 opcodes in protocol 4 files): {e}"
)
else:
# No opcodes were parsed; allow outer error handling to report
# malformed payloads instead of silently treating as empty.
raise
else:
raise
else:
# Subsequent streams: buffer opcodes so that partial streams
# (e.g. binary tensor data misinterpreted as opcodes) don't
# produce false positives.
buffered: list[Any] = []
try:
for item in pickletools.genops(file_obj):
had_opcodes = True
buffered.append(item)
except ValueError:
# Any ValueError on a subsequent stream means we hit
# non-pickle data or a junk separator byte.
stream_error = True
if stream_error and had_opcodes:
# Partial stream: binary data was misinterpreted as opcodes.
# Discard the buffer but keep scanning — a valid malicious
# stream may follow.
if multi_stream:
continue
return
if not stream_error:
# Stream completed successfully — yield buffered opcodes
yield from buffered
if stream_error and had_opcodes:
# First stream parse interruption after yielding some opcodes.
if multi_stream:
# Mark as parsed so subsequent streams are buffered, and
# keep scanning — a malicious payload may follow.
parsed_any_stream = True
continue
# Single-stream mode: return the parsed prefix for security analysis.
return
if not multi_stream:
return
if had_opcodes and not stream_error:
parsed_any_stream = True
if not had_opcodes:
# Resync: the current byte was not a valid pickle start.
# Skip one byte and keep searching for the next stream, up to a limit.
file_obj.seek(stream_start, 0)
if not file_obj.read(1):
return # EOF
resync_skipped += 1
if resync_skipped >= _MAX_RESYNC_BYTES:
# Bounded fast-forward search for the next likely protocol header
# so simple padding cannot terminate multi-stream scanning.
probe_start = file_obj.tell()
probe = file_obj.read(64 * 1024)
candidate = next(
(idx for idx in range(len(probe) - 1) if probe[idx] == 0x80 and probe[idx + 1] in (2, 3, 4, 5)),
-1,
)
if candidate < 0:
return
file_obj.seek(probe_start + candidate, 0)
resync_skipped = 0
continue
# Found a valid stream — reset resync counter
resync_skipped = 0
# Check if there is another pickle stream after STOP
next_byte = file_obj.read(1)
if not next_byte:
return # EOF
file_obj.seek(-1, 1) # put the byte back for the next genops call
def _compute_pickle_length(path: str) -> int:
"""
Compute the exact length of pickle data by finding the STOP opcode position.
Args:
path: Path to the file containing pickle data
Returns:
The byte position where pickle data ends, or a fallback estimate
"""
try:
with open(path, "rb") as f:
for opcode, _arg, pos in pickletools.genops(f):
if opcode.name == "STOP" and pos is not None:
return pos + 1 # Include the STOP opcode itself
# If no STOP found, fallback to file size (malformed pickle)
return os.path.getsize(path)
except Exception:
# Fallback to conservative estimate on any error
file_size = os.path.getsize(path)
return min(file_size // 2, 64)
# ============================================================================
# ML CONTEXT FILTERING SYSTEM
# ============================================================================
# ML Framework Detection Patterns
ML_FRAMEWORK_PATTERNS: dict[str, dict[str, list[str] | float]] = {
"pytorch": {
"modules": [
"torch",
"torchvision",
"torch.nn",
"torch.optim",
"torch.utils",
"_pickle",
"collections",
],
"classes": [
"OrderedDict",
"Parameter",
"Module",
"Linear",
"Conv2d",
"BatchNorm2d",
"ReLU",
"MaxPool2d",
"AdaptiveAvgPool2d",
"Sequential",
"ModuleList",
"Tensor",
],
"patterns": [r"torch\..*", r"_pickle\..*", r"collections\.OrderedDict"],
"confidence_boost": 0.9,
},
"yolo": {
"modules": ["ultralytics", "yolo", "models"],
"classes": ["YOLO", "YOLOv8", "Detect", "C2f", "Conv", "Bottleneck", "SPPF"],
"patterns": [
r"yolo.*",
r"ultralytics\..*",
r".*\.detect",
r".*\.backbone",
r".*\.head",
],
"confidence_boost": 0.9,
},
"tensorflow": {
"modules": ["tensorflow", "keras", "tf"],
"classes": ["Model", "Layer", "Dense", "Conv2D", "Flatten"],
"patterns": [r"tensorflow\..*", r"keras\..*"],
"confidence_boost": 0.8,
},
"sklearn": {
"modules": ["sklearn", "joblib", "numpy", "numpy.core", "numpy._core", "numpy.dtype", "scipy.sparse"],
"classes": [
"Pipeline",
"StandardScaler",
"PCA",
"LogisticRegression",
"DecisionTreeClassifier",
"SVC",
"RandomForestClassifier",
"RandomForestRegressor",
"GradientBoostingClassifier",
"KMeans",
"AgglomerativeClustering",
"Ridge",
"Lasso",
],
"patterns": [
r"sklearn\..*",
r"joblib\..*",
r"numpy\..*",
r"numpy\.core\..*",
r"numpy\._core\..*",
r"scipy\.sparse\..*",
],
"confidence_boost": 0.9,
},
"huggingface": {
"modules": ["transformers", "tokenizers"],
"classes": ["AutoModel", "AutoTokenizer", "BertModel", "GPT2Model"],
"patterns": [r"transformers\..*", r"tokenizers\..*"],
"confidence_boost": 0.8,
},
"xgboost": {
"modules": ["xgboost", "xgboost.core", "xgboost.sklearn"],
"classes": [
"Booster",
"DMatrix",
"XGBClassifier",
"XGBRegressor",
"XGBRanker",
"XGBRFClassifier",
"XGBRFRegressor",
],
"patterns": [r"xgboost\..*"],
"confidence_boost": 0.9,
},
}
# SECURITY: ALWAYS flag these as dangerous, regardless of ML context
# These functions can execute arbitrary code and should NEVER be whitelisted
# Based on Fickling analysis and security best practices
ALWAYS_DANGEROUS_FUNCTIONS: set[str] = {
# System commands
"os.system",
"os.popen",
"os.popen2",
"os.popen3",
"os.popen4",
"os.execl",
"os.execle",
"os.execlp",
"os.execlpe",
"os.execv",
"os.execve",
"os.execvp",
"os.execvpe",
"os.spawn",
"os.spawnl",
"os.spawnle",
"os.spawnlp",
"os.spawnlpe",
"os.spawnv",
"os.spawnve",
"os.spawnvp",
"os.spawnvpe",
# Subprocess
"subprocess.Popen",
"subprocess.call",
"subprocess.check_call",
"subprocess.check_output",
"subprocess.run",
"subprocess.getoutput",
"subprocess.getstatusoutput",
# Code execution
"eval",
"exec",
"compile",
"__import__",
"importlib.import_module",
# File operations (can be dangerous in wrong context)
"open",
"file",
"io.open",
"builtins.open",
# Dynamic attribute access (Fickling: operator module)
"getattr",
"setattr",
"delattr",
"operator.getitem",
"operator.attrgetter",
"operator.itemgetter",
"operator.methodcaller",
# Code objects
"code",
"types.CodeType",
"types.FunctionType",
# Other dangerous operations
"pickle.loads",
"pickle.load",
"joblib.load",
"marshal.loads",
"marshal.load",
# Torch dangerous functions (Fickling)
"torch.load",
"torch.hub.load",
"torch.hub.load_state_dict_from_url",
"torch.storage._load_from_bytes",
# CVE-2024-5480 / CVE-2024-48063: PyTorch RPC functions
"torch.distributed.rpc.rpc_sync",
"torch.distributed.rpc.rpc_async",
"torch.distributed.rpc.remote",
"torch.distributed.rpc.RemoteModule",
# NumPy dangerous functions (Fickling)
"numpy.testing._private.utils.runstring",
"numpy.load",
# pip as callable (CVE-2025-1716: picklescan bypass via pip.main)
"pip.main",
"pip._internal.main",
"pip._internal.cli.main.main",
"pip._vendor.distlib.scripts.ScriptMaker",
# Shell utilities
"shutil.rmtree",
"shutil.move",
"shutil.copy",
"shutil.copytree",
# Dynamic resolution trampolines (can resolve arbitrary callables)
"pkgutil.resolve_name",
# uuid internal functions that call subprocess.Popen
"uuid._get_command_stdout",
"uuid._popen",
# Profiling/debugging modules that execute arbitrary Python code
"cProfile.run",
"cProfile.runctx",
"profile.run",
"profile.runctx",
"pdb.run",
"pdb.runeval",
"pdb.runcall",
"pdb.runctx",
"timeit.timeit",
"timeit.repeat",
# Native code execution
"ctypes.CDLL",
"ctypes.WinDLL",
"ctypes.OleDLL",
"ctypes.PyDLL",
"ctypes.cdll",
"ctypes.windll",
"ctypes.oledll",
"ctypes.pydll",
"ctypes.pythonapi",
"ctypes.cast",
"ctypes.CFUNCTYPE",
"ctypes.WINFUNCTYPE",
# Expanded exact dangerous primitives validated against PickleScan
"site.main",
"_io.FileIO",
"test.support.script_helper.assert_python_ok",
"_osx_support._read_output",
"_aix_support._read_cmd_output",
"_pyrepl.pager.pipe_pager",
"torch.serialization.load",
"torch._inductor.codecache.compile_file",
}
# Module prefixes that are always dangerous (Fickling-based + additional)
# This must be a superset of fickling's 68-module blocklist (PR #215)
ALWAYS_DANGEROUS_MODULES: set[str] = {
# Original modules
"__builtin__",
"__builtins__",
"builtins",
"os",
"posix",
"nt",
"subprocess",
"sys",
"socket",
"urllib",
"urllib2",
"http",
"httplib",
"ftplib",
"telnetlib",
"pty",
"commands",
"shutil",
"code",
"torch.hub",
# Native code execution (ctypes)
"ctypes",
"ctypes.util",
"_ctypes",
# Profiling/debugging - can execute arbitrary Python code via run()
"cProfile",
"profile",
"pdb",
"timeit",
"bdb",
"trace",
# Thread/process spawning
"_thread",
"multiprocessing",
"signal",
"_signal",
"threading",
# Package manager as callable (CVE-2025-1716: picklescan bypass)
"pip",
"pip._internal",
"pip._internal.cli",
"pip._internal.cli.main",
"pip._vendor",
"pip._vendor.distlib",
"pip._vendor.distlib.scripts",
# Module loading from untrusted sources
"zipimport",
"importlib",
"runpy",
# Dynamic resolution / import trampolines
"pkgutil",
# Network / exfiltration
"smtplib",
"imaplib",
"poplib",
"nntplib",
"xmlrpc",
"socketserver",
"ssl",
"requests",
"aiohttp",
# Code execution / compilation
"codeop",
"marshal",
"types",
"compileall",
"py_compile",
# Operator / functools bypasses
"_operator",
"functools",
# Pickle recursion
"pickle",
"_pickle",
"dill",
"cloudpickle",
"joblib",
# Filesystem / shell
"tempfile",
"filecmp",
"fileinput",
"glob",
"distutils",
"pydoc",
"pexpect",
# Virtual environments / package install
"venv",
"ensurepip",
# Other dangerous
"webbrowser",
"asyncio",
"mmap",
"select",
"selectors",
"logging",
"syslog",
"tarfile",
"zipfile",
"shelve",
"sqlite3",
"_sqlite3",
"doctest",
"idlelib",
"lib2to3",
# uuid — _get_command_stdout internally calls subprocess.Popen
"uuid",
# NOTE: linecache and logging.config are intentionally NOT in this set.
# - linecache.getline: file read (not code execution), flagged as WARNING
}
# Modules that are suspicious but should only be flagged at WARNING severity.
# These modules appear frequently in legitimate ML pipelines and cannot directly
# execute arbitrary code, so CRITICAL would cause too many false positives.
WARNING_SEVERITY_MODULES: set[str] = {
# functools.partial is heavily used in PyTorch models; functools.reduce is
# the only genuinely dangerous entry and is still in SUSPICIOUS_GLOBALS.
"functools",
# glob.glob / glob.iglob are common in dataset loading pipelines and
# cannot directly execute code.
"glob",
}
def _is_dangerous_module(mod: str) -> bool:
"""Check if module is in ALWAYS_DANGEROUS_MODULES (exact or prefix match).
Prefix matching ensures deeper sub-modules like pip._internal.cli.main_parser
are still caught when their parent (pip) is in the blocklist.
"""
if mod in ALWAYS_DANGEROUS_MODULES:
return True
return any(mod.startswith(f"{m}.") for m in ALWAYS_DANGEROUS_MODULES)
# String opcodes that push text onto the pickle stack.
# Used for STACK_GLOBAL reconstruction and suspicious string detection.
STRING_OPCODES: frozenset[str] = frozenset(
{
"STRING",
"BINSTRING",
"SHORT_BINSTRING",
"UNICODE",
"SHORT_BINUNICODE",
"BINUNICODE",
"BINUNICODE8",
}
)
# Safe ML-specific global patterns (SECURITY: NO WILDCARDS - explicit lists only)
ML_SAFE_GLOBALS: dict[str, list[str]] = {
# PyTorch - explicit functions only (no wildcards)
"torch": [
"Tensor",
"FloatTensor",
"LongTensor",
"IntTensor",
"DoubleTensor",
"HalfTensor",
"BFloat16Tensor",
"ByteTensor",
"CharTensor",
"ShortTensor",
"BoolTensor",
# Storage types (used in PyTorch serialization)
"FloatStorage",
"LongStorage",
"IntStorage",
"DoubleStorage",
"HalfStorage",
"BFloat16Storage",
"ByteStorage",
"CharStorage",
"ShortStorage",
"BoolStorage",
"Size",
"device",
"dtype",
"storage",
"_utils",
"nn",
"optim",
"jit",
"cuda",
"distributed",
"multiprocessing",
"autograd",
"save",
"load",
"no_grad",
"enable_grad",
"set_grad_enabled",
"inference_mode",
# PyTorch dtypes (safe built-in types)
"bfloat16",
],
"torch.nn": [
"Module",
"Parameter",
"Linear",
"Conv1d",
"Conv2d",
"Conv3d",
"ConvTranspose1d",
"ConvTranspose2d",
"ConvTranspose3d",
"BatchNorm1d",
"BatchNorm2d",
"BatchNorm3d",
"GroupNorm",
"LayerNorm",
"InstanceNorm1d",
"InstanceNorm2d",
"InstanceNorm3d",
"ReLU",
"LeakyReLU",
"PReLU",
"ELU",
"GELU",
"Sigmoid",
"Tanh",
"Softmax",
"LogSoftmax",
"Dropout",
"Dropout2d",
"Dropout3d",
"MaxPool1d",
"MaxPool2d",
"MaxPool3d",
"AvgPool1d",
"AvgPool2d",
"AvgPool3d",
"AdaptiveMaxPool1d",
"AdaptiveMaxPool2d",
"AdaptiveMaxPool3d",
"AdaptiveAvgPool1d",
"AdaptiveAvgPool2d",
"AdaptiveAvgPool3d",
"Sequential",
"ModuleList",
"ModuleDict",
"ParameterList",
"ParameterDict",
"Embedding",
"EmbeddingBag",
"RNN",
"LSTM",
"GRU",
"Transformer",
"TransformerEncoder",
"TransformerDecoder",
"MultiheadAttention",
],
"torch.optim": [
"Adam",
"AdamW",
"SGD",
"RMSprop",
"Adagrad",
"Adadelta",
"Adamax",
"ASGD",
"LBFGS",
"Optimizer",
],
"torch.utils": [
"data",
"checkpoint",
"tensorboard",
],
"torch.utils.data": [
"Dataset",
"DataLoader",
"TensorDataset",
"ConcatDataset",
"Subset",
"random_split",
],
# torch._utils - internal PyTorch utilities used in serialization
"torch._utils": [
"_rebuild_tensor",
"_rebuild_tensor_v2",
"_rebuild_parameter",
"_rebuild_parameter_v2",
"_rebuild_device_tensor_from_numpy",
"_rebuild_qtensor",
"_rebuild_sparse_tensor",
],
"_pickle": [
"Unpickler",
"Pickler",
],
# Python builtins - safe built-in types and functions
# NOTE: eval, exec, compile, __import__, open, file are NOT in this list (they remain dangerous)
# NOTE: getattr, setattr, delattr, hasattr are NOT in this list
# because attribute-access primitives must never be allowlisted.
"__builtin__": [ # Python 2 builtins
"set",
"frozenset",
"dict",
"list",
"tuple",
"int",
"float",
"str",
"bytes",
"bytearray",
"bool",
"object",
"type",
"range",
"slice",
"enumerate",
"zip",
"map",
"filter",
"reversed",
"sorted",
"len",
"min",
"max",
"sum",
"abs",
"round",
"divmod",
"pow",
"hash",
"id",
"isinstance",
"issubclass",
"callable",
"repr",
"ascii",
"bin",
"hex",
"oct",
"chr",
"ord",
"all",
"any",
"iter",
"next",
# Python 2 type names used by frameworks like fastai during serialization
"long",
"unicode",
"print",
"basestring",
"xrange",
"complex",
"memoryview",
"property",
"staticmethod",
"classmethod",
"super",
],
"builtins": [ # Python 3 builtins
"set",
"frozenset",
"dict",
"list",
"tuple",
"int",
"float",
"str",
"bytes",
"bytearray",
"bool",
"object",
"type",
"range",
"slice",
"enumerate",
"zip",
"map",
"filter",
"reversed",
"sorted",
"len",
"min",
"max",
"sum",
"abs",
"round",
"divmod",
"pow",
"hash",
"id",
"isinstance",
"issubclass",
"callable",
"repr",
"ascii",
"bin",
"hex",
"oct",
"chr",
"ord",
"all",
"any",
"iter",
"next",
],
"collections": ["OrderedDict", "defaultdict", "namedtuple", "Counter", "deque"],
# _codecs is used by NumPy/PyTorch for binary data serialization (e.g., RNG states)
# encode() only transforms string encodings, it cannot execute code
"_codecs": ["encode"],
"typing": [
"Any",
"Union",
"Optional",
"List",
"Dict",
"Tuple",
"Set",
"Callable",
],
"numpy": [
"ndarray",
"array",
"zeros",
"ones",
"empty",
"arange",
"linspace",
"dtype",
"int8",
"int16",
"int32",
"int64",
"uint8",
"uint16",
"uint32",
"uint64",
"float16",
"float32",
"float64",
"complex64",
"complex128",
"bool_",
],
"numpy.core": [
"multiarray",
"numeric",
"_internal",
],
"numpy.core.multiarray": [
"_reconstruct",
"scalar",
],
"numpy.core.numeric": [
"_frombuffer",
],
# numpy._core is the internal path used in NumPy 2.x+
"numpy._core": [
"multiarray",
"numeric",
"_internal",
],
"numpy._core.multiarray": [
"_reconstruct",
"scalar",
],
"numpy._core.numeric": [
"_frombuffer",
],
"numpy.random._pickle": [