|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | +""" |
| 4 | +Secure pickle utilities to prevent arbitrary code execution through deserialization. |
| 5 | +
|
| 6 | +This module provides a secure alternative to pickle.load() and pickle.loads() |
| 7 | +that restricts deserialization to a whitelist of safe classes. |
| 8 | +""" |
| 9 | + |
| 10 | +import io |
| 11 | +import pickle |
| 12 | +from typing import Any, BinaryIO, Set, Tuple |
| 13 | + |
| 14 | +# Whitelist of safe classes that are allowed to be unpickled |
| 15 | +# These are common data types used in qlib that should be safe to deserialize |
| 16 | +SAFE_PICKLE_CLASSES: Set[Tuple[str, str]] = { |
| 17 | + # python builtins |
| 18 | + ("builtins", "slice"), |
| 19 | + ("builtins", "range"), |
| 20 | + ("builtins", "dict"), |
| 21 | + ("builtins", "list"), |
| 22 | + ("builtins", "tuple"), |
| 23 | + ("builtins", "set"), |
| 24 | + ("builtins", "frozenset"), |
| 25 | + ("builtins", "bytearray"), |
| 26 | + ("builtins", "bytes"), |
| 27 | + ("builtins", "str"), |
| 28 | + ("builtins", "int"), |
| 29 | + ("builtins", "float"), |
| 30 | + ("builtins", "bool"), |
| 31 | + ("builtins", "complex"), |
| 32 | + ("builtins", "type"), |
| 33 | + ("builtins", "property"), |
| 34 | + # common utility classes |
| 35 | + ("datetime", "datetime"), |
| 36 | + ("datetime", "date"), |
| 37 | + ("datetime", "time"), |
| 38 | + ("datetime", "timedelta"), |
| 39 | + ("datetime", "timezone"), |
| 40 | + ("decimal", "Decimal"), |
| 41 | + ("collections", "OrderedDict"), |
| 42 | + ("collections", "defaultdict"), |
| 43 | + ("collections", "Counter"), |
| 44 | + ("collections", "namedtuple"), |
| 45 | + ("enum", "Enum"), |
| 46 | + ("pathlib", "Path"), |
| 47 | + ("pathlib", "PosixPath"), |
| 48 | + ("pathlib", "WindowsPath"), |
| 49 | + ("qlib.data.dataset.handler", "DataHandler"), |
| 50 | + ("qlib.data.dataset.handler", "DataHandlerLP"), |
| 51 | + ("qlib.data.dataset.loader", "StaticDataLoader"), |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +TRUSTED_MODULE_PREFIXES = ( |
| 56 | + "pandas", |
| 57 | + "numpy", |
| 58 | +) |
| 59 | + |
| 60 | + |
| 61 | +class RestrictedUnpickler(pickle.Unpickler): |
| 62 | + """Custom unpickler that only allows safe classes to be deserialized. |
| 63 | +
|
| 64 | + This prevents arbitrary code execution through malicious pickle files by |
| 65 | + restricting deserialization to a whitelist of safe classes. |
| 66 | +
|
| 67 | + Example: |
| 68 | + >>> with open("data.pkl", "rb") as f: |
| 69 | + ... data = RestrictedUnpickler(f).load() |
| 70 | + """ |
| 71 | + |
| 72 | + def find_class(self, module: str, name: str): |
| 73 | + """Override find_class to restrict allowed classes. |
| 74 | +
|
| 75 | + Args: |
| 76 | + module: Module name of the class |
| 77 | + name: Class name |
| 78 | +
|
| 79 | + Returns: |
| 80 | + The class object if it's in the whitelist |
| 81 | +
|
| 82 | + Raises: |
| 83 | + pickle.UnpicklingError: If the class is not in the whitelist |
| 84 | + """ |
| 85 | + if module.startswith(TRUSTED_MODULE_PREFIXES): |
| 86 | + return super().find_class(module, name) |
| 87 | + |
| 88 | + # 2. explicit whitelist (qlib internal) |
| 89 | + if (module, name) in SAFE_PICKLE_CLASSES: |
| 90 | + return super().find_class(module, name) |
| 91 | + |
| 92 | + raise pickle.UnpicklingError( |
| 93 | + f"Forbidden class: {module}.{name}. " |
| 94 | + f"Only whitelisted classes are allowed for security reasons. " |
| 95 | + f"This is to prevent arbitrary code execution through pickle deserialization." |
| 96 | + ) |
| 97 | + |
| 98 | + |
| 99 | +def restricted_pickle_load(file: BinaryIO) -> Any: |
| 100 | + """Safely load a pickle file with restricted classes. |
| 101 | +
|
| 102 | + This is a drop-in replacement for pickle.load() that prevents |
| 103 | + arbitrary code execution by only allowing whitelisted classes. |
| 104 | +
|
| 105 | + Args: |
| 106 | + file: An opened file object in binary mode |
| 107 | +
|
| 108 | + Returns: |
| 109 | + The unpickled Python object |
| 110 | +
|
| 111 | + Raises: |
| 112 | + pickle.UnpicklingError: If the pickle contains forbidden classes |
| 113 | +
|
| 114 | + Example: |
| 115 | + >>> with open("data.pkl", "rb") as f: |
| 116 | + ... data = restricted_pickle_load(f) |
| 117 | + """ |
| 118 | + return RestrictedUnpickler(file).load() |
| 119 | + |
| 120 | + |
| 121 | +def restricted_pickle_loads(data: bytes) -> Any: |
| 122 | + """Safely load a pickle from bytes with restricted classes. |
| 123 | +
|
| 124 | + This is a drop-in replacement for pickle.loads() that prevents |
| 125 | + arbitrary code execution by only allowing whitelisted classes. |
| 126 | +
|
| 127 | + Args: |
| 128 | + data: Bytes object containing pickled data |
| 129 | +
|
| 130 | + Returns: |
| 131 | + The unpickled Python object |
| 132 | +
|
| 133 | + Raises: |
| 134 | + pickle.UnpicklingError: If the pickle contains forbidden classes |
| 135 | +
|
| 136 | + Example: |
| 137 | + >>> data = b'\\x80\\x04\\x95...' |
| 138 | + >>> obj = restricted_pickle_loads(data) |
| 139 | + """ |
| 140 | + file_like = io.BytesIO(data) |
| 141 | + return RestrictedUnpickler(file_like).load() |
| 142 | + |
| 143 | + |
| 144 | +def add_safe_class(module: str, name: str) -> None: |
| 145 | + """Add a class to the whitelist of safe classes for unpickling. |
| 146 | +
|
| 147 | + Use this function to extend the whitelist if your code needs to deserialize |
| 148 | + additional classes. However, be very careful when adding classes, as this |
| 149 | + could potentially introduce security vulnerabilities. |
| 150 | +
|
| 151 | + Args: |
| 152 | + module: Module name of the class (e.g., 'my_package.my_module') |
| 153 | + name: Class name (e.g., 'MyClass') |
| 154 | +
|
| 155 | + Warning: |
| 156 | + Only add classes that you fully control and trust. Adding arbitrary |
| 157 | + classes from external packages could introduce security risks. |
| 158 | +
|
| 159 | + Example: |
| 160 | + >>> add_safe_class('my_package.models', 'CustomModel') |
| 161 | + """ |
| 162 | + SAFE_PICKLE_CLASSES.add((module, name)) |
| 163 | + |
| 164 | + |
| 165 | +def get_safe_classes() -> Set[Tuple[str, str]]: |
| 166 | + """Get a copy of the current whitelist of safe classes. |
| 167 | +
|
| 168 | + Returns: |
| 169 | + A set of (module, name) tuples representing allowed classes |
| 170 | + """ |
| 171 | + return SAFE_PICKLE_CLASSES.copy() |
0 commit comments