Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serde: limit decode code execution #3175

Merged
merged 7 commits into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/gluonts/core/serde/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,15 @@ def encode_partial(v: partial) -> Any:
}


decode_disallow = [
eval,
exec,
compile,
open,
input,
]


def decode(r: Any) -> Any:
"""
Decodes a value from an intermediate representation `r`.
Expand All @@ -312,7 +321,10 @@ def decode(r: Any) -> Any:
kind = r["__kind__"]
cls = cast(Any, locate(r["class"]))

assert cls is not None, f"Can not locate {r['class']}."
if cls is None:
raise ValueError(f"Cannot locate {r['class']}.")
if cls in decode_disallow:
raise ValueError(f"{r['class']} cannot be run.")

if kind == Kind.Type:
return cls
Expand Down
23 changes: 23 additions & 0 deletions test/core/test_serde.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,26 @@ def test_serde_method():
def test_np_str_dtype():
a = np.array(["foo"])
serde.decode(serde.encode(a.dtype)) == a.dtype


@pytest.mark.parametrize(
"obj",
[
{"__kind__": 42, "class": cls_str}
for cls_str in [
"builtins.eval",
"builtins.exec",
"builtins.compile",
"builtins.open",
"builtins.input",
"eval",
"exec",
"compile",
"open",
"input",
]
],
)
def test_decode_disallow(obj):
with pytest.raises(ValueError):
serde.decode(obj)
Loading