|
3 | 3 | import datetime |
4 | 4 | import heapq |
5 | 5 | import itertools |
| 6 | +import json |
6 | 7 | import os # noqa |
7 | 8 | import pathlib |
8 | 9 | import pickle |
|
37 | 38 | _SIMPLE_COOKIE = SimpleCookie() |
38 | 39 |
|
39 | 40 |
|
| 41 | +class _RestrictedCookieUnpickler(pickle.Unpickler): |
| 42 | + """A restricted unpickler that only allows cookie-related types. |
| 43 | +
|
| 44 | + This prevents arbitrary code execution when loading pickled cookie data |
| 45 | + from untrusted sources. Only types that are expected in a serialized |
| 46 | + CookieJar are permitted. |
| 47 | +
|
| 48 | + See: https://docs.python.org/3/library/pickle.html#restricting-globals |
| 49 | + """ |
| 50 | + |
| 51 | + _ALLOWED_CLASSES: frozenset[tuple[str, str]] = frozenset( |
| 52 | + { |
| 53 | + # Core cookie types |
| 54 | + ("http.cookies", "SimpleCookie"), |
| 55 | + ("http.cookies", "Morsel"), |
| 56 | + # Container types used by CookieJar._cookies |
| 57 | + ("collections", "defaultdict"), |
| 58 | + # builtins that pickle uses for reconstruction |
| 59 | + ("builtins", "tuple"), |
| 60 | + ("builtins", "set"), |
| 61 | + ("builtins", "frozenset"), |
| 62 | + ("builtins", "dict"), |
| 63 | + } |
| 64 | + ) |
| 65 | + |
| 66 | + def find_class(self, module: str, name: str) -> type: |
| 67 | + if (module, name) not in self._ALLOWED_CLASSES: |
| 68 | + raise pickle.UnpicklingError( |
| 69 | + f"Forbidden class: {module}.{name}. " |
| 70 | + "CookieJar.load() only allows cookie-related types for security. " |
| 71 | + "See https://docs.python.org/3/library/pickle.html#restricting-globals" |
| 72 | + ) |
| 73 | + return super().find_class(module, name) |
| 74 | + |
| 75 | + |
40 | 76 | class CookieJar(AbstractCookieJar): |
41 | 77 | """Implements cookie storage adhering to RFC 6265.""" |
42 | 78 |
|
@@ -117,9 +153,108 @@ def save(self, file_path: PathLike) -> None: |
117 | 153 | pickle.dump(self._cookies, f, pickle.HIGHEST_PROTOCOL) |
118 | 154 |
|
119 | 155 | def load(self, file_path: PathLike) -> None: |
| 156 | + """Load cookies from a pickled file using a restricted unpickler. |
| 157 | +
|
| 158 | + .. warning:: |
| 159 | +
|
| 160 | + Cookie files loaded from untrusted sources could previously |
| 161 | + execute arbitrary code. This method now uses a restricted |
| 162 | + unpickler that only allows cookie-related types. |
| 163 | +
|
| 164 | + For new code, consider using :meth:`save_json` and |
| 165 | + :meth:`load_json` instead, which use a safe JSON format. |
| 166 | +
|
| 167 | + :param file_path: Path to file from where cookies will be |
| 168 | + imported, :class:`str` or :class:`pathlib.Path` instance. |
| 169 | + """ |
120 | 170 | file_path = pathlib.Path(file_path) |
121 | 171 | with file_path.open(mode="rb") as f: |
122 | | - self._cookies = pickle.load(f) |
| 172 | + self._cookies = _RestrictedCookieUnpickler(f).load() |
| 173 | + |
| 174 | + def save_json(self, file_path: PathLike) -> None: |
| 175 | + """Save cookies to a JSON file (safe alternative to :meth:`save`). |
| 176 | +
|
| 177 | + This method serializes cookies using JSON, which is inherently safe |
| 178 | + against deserialization attacks unlike the pickle-based :meth:`save`. |
| 179 | +
|
| 180 | + :param file_path: Path to file where cookies will be serialized, |
| 181 | + :class:`str` or :class:`pathlib.Path` instance. |
| 182 | +
|
| 183 | + .. versionadded:: 3.14 |
| 184 | + """ |
| 185 | + file_path = pathlib.Path(file_path) |
| 186 | + data: dict[str, dict[str, dict[str, str]]] = {} |
| 187 | + for (domain, path), cookie in self._cookies.items(): |
| 188 | + key = f"{domain}|{path}" |
| 189 | + data[key] = {} |
| 190 | + for name, morsel in cookie.items(): |
| 191 | + morsel_data: dict[str, str] = { |
| 192 | + "key": morsel.key, |
| 193 | + "value": morsel.value, |
| 194 | + "coded_value": morsel.coded_value, |
| 195 | + } |
| 196 | + # Save all morsel attributes that have values |
| 197 | + for attr in morsel._reserved: |
| 198 | + attr_val = morsel[attr] |
| 199 | + if attr_val: |
| 200 | + if isinstance(attr_val, bool): |
| 201 | + morsel_data[attr] = "true" |
| 202 | + else: |
| 203 | + morsel_data[attr] = str(attr_val) |
| 204 | + data[key][name] = morsel_data |
| 205 | + with file_path.open(mode="w", encoding="utf-8") as f: |
| 206 | + json.dump(data, f, indent=2) |
| 207 | + |
| 208 | + def load_json(self, file_path: PathLike) -> None: |
| 209 | + """Load cookies from a JSON file (safe alternative to :meth:`load`). |
| 210 | +
|
| 211 | + This method deserializes cookies from JSON format, which is inherently |
| 212 | + safe against code execution attacks. |
| 213 | +
|
| 214 | + :param file_path: Path to file from where cookies will be imported, |
| 215 | + :class:`str` or :class:`pathlib.Path` instance. |
| 216 | +
|
| 217 | + .. versionadded:: 3.14 |
| 218 | + """ |
| 219 | + file_path = pathlib.Path(file_path) |
| 220 | + with file_path.open(mode="r", encoding="utf-8") as f: |
| 221 | + data = json.load(f) |
| 222 | + cookies: defaultdict[tuple[str, str], SimpleCookie] = defaultdict( |
| 223 | + SimpleCookie |
| 224 | + ) |
| 225 | + for compound_key, cookie_data in data.items(): |
| 226 | + parts = compound_key.split("|", 1) |
| 227 | + domain = parts[0] |
| 228 | + path = parts[1] if len(parts) > 1 else "" |
| 229 | + key = (domain, path) |
| 230 | + for name, morsel_data in cookie_data.items(): |
| 231 | + morsel: Morsel[str] = Morsel() |
| 232 | + morsel_key = morsel_data.get("key", name) |
| 233 | + morsel_value = morsel_data.get("value", "") |
| 234 | + morsel_coded_value = morsel_data.get("coded_value", morsel_value) |
| 235 | + # Use __setstate__ to bypass validation, same pattern |
| 236 | + # used in _build_morsel and _cookie_helpers. |
| 237 | + morsel.__setstate__( # type: ignore[attr-defined] |
| 238 | + { |
| 239 | + "key": morsel_key, |
| 240 | + "value": morsel_value, |
| 241 | + "coded_value": morsel_coded_value, |
| 242 | + } |
| 243 | + ) |
| 244 | + # Restore morsel attributes |
| 245 | + for attr in morsel._reserved: |
| 246 | + if attr in morsel_data and attr not in ( |
| 247 | + "key", |
| 248 | + "value", |
| 249 | + "coded_value", |
| 250 | + ): |
| 251 | + attr_val = morsel_data[attr] |
| 252 | + if attr in ("secure", "httponly"): |
| 253 | + morsel[attr] = True if attr_val == "true" else attr_val # type: ignore[assignment] |
| 254 | + else: |
| 255 | + morsel[attr] = attr_val |
| 256 | + cookies[key][name] = morsel |
| 257 | + self._cookies = cookies |
123 | 258 |
|
124 | 259 | def clear(self, predicate: ClearCookiePredicate | None = None) -> None: |
125 | 260 | if predicate is None: |
|
0 commit comments