andreahlert commented on code in PR #818:
URL: https://github.com/apache/burr/pull/818#discussion_r3485687368
##########
burr/integrations/serde/pickle.py:
##########
@@ -18,12 +18,94 @@
# Pickle serde registration
# This is not automatically registered because we want to register
# it based on class type.
+import io
import pickle
+import warnings
+from typing import Iterable, List, Optional, Tuple
from burr.core import serde
+# Type alias: an allowlist entry is ``(module, qualname)``.
+# ``qualname`` may be ``"*"`` to permit any class in the given module.
+AllowlistEntry = Tuple[str, str]
-def register_type_to_pickle(cls):
+
+class SecurityWarning(Warning):
+ """Warning issued when pickle deserialization proceeds without an
allowlist."""
+
+
+# Global allowlist for pickle deserialization. When set, only
+# ``(module, qualname)`` pairs in this list are permitted to be
+# reconstructed during ``pickle.loads``.
+_global_allowlist: Optional[List[AllowlistEntry]] = None
+
+
+def set_pickle_serde_allowlist(allowlist: Optional[Iterable[AllowlistEntry]])
-> None:
+ """Set a process-wide allowlist of ``(module, qualname)`` pairs that may be
+ reconstructed by ``deserialize_pickle``.
+
+ Each entry is a tuple ``(module_name, class_name)``. Use ``"*"`` as the
class
+ name to permit any class in that module:
+
+ .. code-block:: python
+
+ from burr.integrations.serde import pickle as burr_pickle
+
+ burr_pickle.set_pickle_serde_allowlist([
+ ("myapp.models", "User"),
+ ("myapp.models", "Address"),
+ ("myapp.types", "*"), # any class in myapp.types
+ ])
+
+ When the allowlist is set, any attempt to deserialize a class outside the
+ allowlist raises ``pickle.UnpicklingError``. Pass ``None`` to clear it.
+
+ :param allowlist: Iterable of ``(module, qualname)`` tuples, or ``None``.
+ """
+ global _global_allowlist
+ _global_allowlist = list(allowlist) if allowlist is not None else None
+
+
+def _is_allowed(module: str, name: str, allowlist: Iterable[AllowlistEntry])
-> bool:
+ for allowed_module, allowed_name in allowlist:
+ if module == allowed_module and (allowed_name == "*" or allowed_name
== name):
+ return True
+ return False
+
+
+class _RestrictedUnpickler(pickle.Unpickler):
+ """Pickle unpickler that only resolves classes present in an allowlist.
+
+ See https://docs.python.org/3/library/pickle.html#restricting-globals
+ for the standard library guidance this is modeled on.
+ """
+
+ def __init__(self, file, allowlist: Iterable[AllowlistEntry], **kwargs):
+ super().__init__(file, **kwargs)
+ self._allowlist = list(allowlist)
+
+ def find_class(self, module: str, name: str):
+ if not _is_allowed(module, name, self._allowlist):
+ raise pickle.UnpicklingError(
+ f"Refusing to load pickled class '{module}.{name}': not in the
"
+ f"pickle serde allowlist. Add it via the ``allowlist``
argument "
+ f"to register_type_to_pickle()/deserialize, or call "
+
f"burr.integrations.serde.pickle.set_pickle_serde_allowlist([...])."
+ )
+ return super().find_class(module, name)
+
+
+def _restricted_loads(data: bytes, allowlist: Iterable[AllowlistEntry],
**kwargs):
+ return _RestrictedUnpickler(io.BytesIO(data), allowlist, **kwargs).load()
+
+
+# Tracks call sites that have already received a "no allowlist" warning, so the
+# warning is emitted at most once per registration site rather than once per
+# deserialization (which could be noisy on hot paths).
+_warned_call_sites: set = set()
+
+
+def register_type_to_pickle(cls, allowlist: Optional[Iterable[AllowlistEntry]]
= None):
Review Comment:
this is fail-open. key's static `"pickle"`, so registering another class w/o
a list later wipes this one's allowlist. tested it. lvl-2 should just go —
per-call + global is enough (#794 already does it that way).
##########
burr/integrations/serde/pickle.py:
##########
@@ -18,12 +18,94 @@
# Pickle serde registration
# This is not automatically registered because we want to register
# it based on class type.
+import io
import pickle
+import warnings
+from typing import Iterable, List, Optional, Tuple
from burr.core import serde
+# Type alias: an allowlist entry is ``(module, qualname)``.
+# ``qualname`` may be ``"*"`` to permit any class in the given module.
+AllowlistEntry = Tuple[str, str]
-def register_type_to_pickle(cls):
+
+class SecurityWarning(Warning):
+ """Warning issued when pickle deserialization proceeds without an
allowlist."""
+
+
+# Global allowlist for pickle deserialization. When set, only
+# ``(module, qualname)`` pairs in this list are permitted to be
+# reconstructed during ``pickle.loads``.
+_global_allowlist: Optional[List[AllowlistEntry]] = None
+
+
+def set_pickle_serde_allowlist(allowlist: Optional[Iterable[AllowlistEntry]])
-> None:
Review Comment:
two setters + two SecurityWarnings now (this and pydantic's). worth merging
into one `burr.serde` someday?
##########
tests/integrations/serde/test_pickle.py:
##########
@@ -25,22 +31,176 @@ def __init__(self, name, email):
self.email = email
+class Address:
+ def __init__(self, city):
+ self.city = city
+
+
+class _ReduceCanary:
+ """When unpickled, would call ``int("1")`` instead of doing the normal
+ object reconstruction. We use this to exercise the ``find_class`` hook of
+ the restricted unpickler without invoking anything actually dangerous.
+ """
+
+ def __reduce__(self):
+ return (int, ("1",))
+
+
def test_serde_of_pickle_object():
pickle.register_type_to_pickle(User)
user = User(name="John Doe", email="[email protected]")
og = state.State({"user": user, "test": "test"})
- serialized = og.serialize()
- assert serialized == {
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", SecurityWarning)
+ serialized = og.serialize()
+ ng = state.State.deserialize(serialized)
+ assert serialized["user"][serde.KEY] == "pickle"
+ assert isinstance(ng["user"], User)
+ assert ng["user"].name == "John Doe"
+ assert ng["user"].email == "[email protected]"
+
+
+def test_is_allowed_logic():
+ assert _is_allowed("m", "C", [("m", "C")]) is True
+ assert _is_allowed("m", "C", [("m", "*")]) is True
+ assert _is_allowed("m", "C", [("other", "*")]) is False
+ assert _is_allowed("m", "C", [("m", "D")]) is False
+ assert _is_allowed("m", "C", []) is False
+
+
+def test_malicious_reduce_payload_blocked_with_allowlist():
Review Comment:
only catches a top-level `builtins.int`. one where an allowed obj nests a
blocked class would be a stronger test.
##########
burr/integrations/serde/pickle.py:
##########
@@ -40,9 +122,40 @@ def __init__(self, name, email):
from burr.integrations.serde import pickle
pickle.register_type_to_pickle(User) # this will register the User
class to be serialized/deserialized using pickle.
+ Trust model
+ -----------
+ Pickle is, by design, capable of executing arbitrary code during
+ deserialization. If the persistence backend (SQLite file, Redis, S3, the
+ local filesystem, etc.) can be written to by an untrusted party, a tampered
+ payload can trigger remote code execution when burr restores application
+ state.
Review Comment:
restricting globals isn't a full fix (cpython docs say so) — softening this
+ mentioning signed payloads:
```suggestion
state.
Note: an allowlist restricts *which* globals can be imported — necessary
but not sufficient (see CPython "Restricting Globals"). For fully
untrusted
backends, prefer not unpickling, or sign payloads (HMAC) as defense in
depth.
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]