Skip to content

Commit 40e4fc9

Browse files
authored
fix: restrict algo_from_json _target_ to Algo subclasses (GHSA-2wx3) (#9115)
Addresses **GHSA-2wx3-8x3w-r8qv** (`Auto3DSeg algo_from_json` target instantiation). ## What `algo_object.json`'s `_target_` is located and instantiated from a user-supplied file, so it could name `subprocess.call` and execute it. `_reject_non_algo_target()` resolves `_target_` with `pydoc.locate` and requires it to be an `Algo` subclass — checked **before** `ConfigParser` instantiates anything — plus an `isinstance(cls, Algo)` check on the result. ## Why this is a real narrowing (not just a warning) I disagree with the "config DSL is the feature" framing that applies to the FL case. `algo_from_json` has exactly one legal target type, so the check costs nothing and closes the `subprocess.call`-style payload without breaking a legitimate use. This is the same class of fix as the nnUNet path confinement (GHSA-8f32), not a trust-boundary deferral. ## Residual risk (stated) Importing the named module still runs that module's top-level code. This shrinks the sink; it does not close it. An untrusted `algo_object.json` plus an attacker-controlled template directory remains dangerous. Documented in the docstring. ## Test changes New `tests/auto3dseg/test_algo_target_allowlist.py` covering: - `subprocess.call` rejection - `builtins.eval` rejection - non-class target rejection - legitimate `Algo` subclass still loads - `Algo` base class itself rejected (must be a *subclass*) ## Verification - `tests/auto3dseg`: 5/5 pass, 5 subtests pass - `black` / `ruff` / DCO clean This is the 1.6.1 "complete fix" for GHSA-2wx3, replacing the warning-only PR #9085. --------- Signed-off-by: R. Garcia-Dias <rafaelagd@gmail.com>
1 parent db6f171 commit 40e4fc9

3 files changed

Lines changed: 126 additions & 17 deletions

File tree

‎monai/auto3dseg/utils.py‎

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import warnings
2121
from copy import deepcopy
2222
from numbers import Number
23+
from pydoc import locate
2324
from typing import Any, cast
2425

2526
import numpy as np
@@ -62,6 +63,42 @@ def _require_pickle_allowed() -> None:
6263
raise RuntimeError(_PICKLE_DISABLED_MSG)
6364

6465

66+
def _reject_non_algo_target(target: Any, filename: str) -> None:
67+
"""
68+
Require that ``target`` names an ``Algo`` subclass before it is instantiated.
69+
70+
``algo_from_json`` resolves ``_target_`` through ``ConfigParser``, which imports the dotted path
71+
and calls it. ``algo_object.json`` has exactly one legitimate target type -- an ``Algo``
72+
subclass -- so resolving the name and checking it here rejects payloads such as
73+
``subprocess.call`` or ``os.system`` before they are ever invoked.
74+
75+
Importing the named module still runs that module's top-level code, so this narrows the sink
76+
rather than closing it: an untrusted ``algo_object.json`` combined with an attacker-controlled
77+
template directory remains dangerous.
78+
79+
Args:
80+
target: the ``_target_`` value read from the file.
81+
filename: the file the value came from, used in the error message.
82+
83+
Raises:
84+
ValueError: if ``target`` is not a string, or does not resolve to a concrete ``Algo`` subclass.
85+
ModuleNotFoundError: if the module cannot be imported, so callers can try the next
86+
template path.
87+
"""
88+
if not isinstance(target, str):
89+
raise ValueError(f"Invalid `_target_` in {filename}: expected a string, got {type(target).__name__}.")
90+
resolved = locate(target)
91+
if resolved is None:
92+
raise ModuleNotFoundError(f"Cannot resolve `_target_` {target!r} from {filename}.")
93+
if not (isinstance(resolved, type) and resolved is not Algo and issubclass(resolved, Algo)):
94+
raise ValueError(
95+
f"Refusing to instantiate `_target_` {target!r} from {filename}: it resolves to "
96+
f"{resolved!r}, which is not a subclass of `monai.auto3dseg.Algo`. Only Algo subclasses "
97+
"may be named in a configuration "
98+
"(see https://github.com/Project-MONAI/MONAI/security/advisories/GHSA-2wx3-8x3w-r8qv)."
99+
)
100+
101+
65102
measure_np, has_measure = optional_import("skimage.measure", "0.14.2", min_version)
66103
cp, has_cp = optional_import("cupy")
67104

@@ -493,16 +530,16 @@ def algo_from_json(filename: str, template_path: PathLike | None = None, **kwarg
493530
if state_template_path:
494531
algo_config["template_path"] = state_template_path
495532

496-
warnings.warn(
497-
f"Loading {filename}: the file's `_target_` value is resolved to an imported callable and "
498-
"invoked, and template directories from the file may be added to `sys.path`; only load "
499-
"algo_object.json files from a source you trust "
500-
"(see https://github.com/Project-MONAI/MONAI/security/advisories/GHSA-2wx3-8x3w-r8qv).",
501-
stacklevel=2,
502-
)
533+
_reject_non_algo_target(target, filename)
503534

504535
parser = ConfigParser(algo_config)
505536
algo = parser.get_parsed_content()
537+
if not isinstance(algo, Algo):
538+
raise ValueError(
539+
f"refusing to return the object built from '{target}' in {filename}: it is a "
540+
f"{type(algo).__name__}, not an Algo instance "
541+
"(see https://github.com/Project-MONAI/MONAI/security/advisories/GHSA-2wx3-8x3w-r8qv)."
542+
)
506543
used_template_path = path
507544
break
508545
except ModuleNotFoundError as e:

‎tests/apps/test_auto3dseg.py‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
import os
1616
import tempfile
1717
import unittest
18-
import warnings
1918
from copy import deepcopy
2019
from numbers import Number
2120

@@ -637,22 +636,20 @@ def tearDown(self) -> None:
637636

638637

639638
class TestAlgoFromJsonSecurityWarning(unittest.TestCase):
640-
def test_warns_about_untrusted_target(self) -> None:
639+
def test_rejects_untrusted_target(self) -> None:
640+
"""Verify that a ``_target_`` pointing to a non-``Algo`` class is rejected.
641+
642+
``_DummyAlgo`` is a plain class (not an ``Algo`` subclass); loading it must raise
643+
``ValueError`` rather than instantiate the class, per GHSA-2wx3.
644+
"""
641645
with tempfile.TemporaryDirectory() as tmpdir:
642646
algo_file = os.path.join(tmpdir, "algo_object.json")
643647
with open(algo_file, "w", encoding="utf-8") as f:
644648
json.dump({"_target_": f"{__name__}._DummyAlgo"}, f)
645649

646-
with warnings.catch_warnings(record=True) as caught:
647-
warnings.simplefilter("always")
650+
with self.assertRaisesRegex(ValueError, "(?i)refusing to instantiate"):
648651
algo_from_json(algo_file)
649652

650-
messages = [str(w.message) for w in caught]
651-
self.assertTrue(
652-
any("algo_object.json" in msg and "trust" in msg for msg in messages),
653-
f"Keywords 'algo_object.json' and 'trust' not found in warning messages: {messages}",
654-
)
655-
656653

657654
if __name__ == "__main__":
658655
unittest.main()
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Copyright (c) MONAI Consortium
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
# http://www.apache.org/licenses/LICENSE-2.0
6+
# Unless required by applicable law or agreed to in writing, software
7+
# distributed under the License is distributed on an "AS IS" BASIS,
8+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9+
# See the License for the specific language governing permissions and
10+
# limitations under the License.
11+
12+
from __future__ import annotations
13+
14+
import json
15+
import os
16+
import tempfile
17+
import unittest
18+
19+
from monai.auto3dseg.utils import _reject_non_algo_target, algo_from_json
20+
21+
22+
class TestAlgoTargetAllowlist(unittest.TestCase):
23+
"""Regression tests for GHSA-2wx3-8x3w-r8qv.
24+
25+
``algo_from_json`` resolves the file's ``_target_`` through ``ConfigParser``, which imports the
26+
dotted path and calls it. ``algo_object.json`` has exactly one legitimate target type, so a
27+
``_target_`` that is not an ``Algo`` subclass is rejected before it is instantiated.
28+
"""
29+
30+
def test_code_execution_targets_are_rejected(self):
31+
for target in ("subprocess.call", "os.system", "builtins.eval", "builtins.exec", "shutil.rmtree"):
32+
with self.subTest(target=target):
33+
with self.assertRaises(ValueError) as ctx:
34+
_reject_non_algo_target(target, "algo_object.json")
35+
self.assertIn("GHSA-2wx3-8x3w-r8qv", str(ctx.exception))
36+
37+
def test_non_class_target_is_rejected(self):
38+
"""A module or plain function is not an Algo subclass."""
39+
with self.assertRaisesRegex(ValueError, r"GHSA-2wx3-8x3w-r8qv"):
40+
_reject_non_algo_target("json.dumps", "algo_object.json")
41+
42+
def test_unresolvable_target_raises_module_not_found(self):
43+
"""Unresolvable names raise ModuleNotFoundError so the caller can try the next path."""
44+
with self.assertRaises(ModuleNotFoundError):
45+
_reject_non_algo_target("no_such_module.NoSuchAlgo", "algo_object.json")
46+
47+
def test_algo_subclass_is_accepted(self):
48+
"""A real Algo subclass passes the check."""
49+
_reject_non_algo_target("monai.apps.auto3dseg.BundleAlgo", "algo_object.json")
50+
51+
def test_non_string_target_is_rejected(self):
52+
"""A JSON ``null`` ``_target_`` raises the documented ``ValueError``, not ``AttributeError``."""
53+
with self.assertRaisesRegex(ValueError, r"expected a string"):
54+
_reject_non_algo_target(None, "algo_object.json")
55+
56+
def test_bare_algo_base_class_is_rejected(self):
57+
"""The abstract ``Algo`` base class is not itself a valid instantiation target."""
58+
with self.assertRaisesRegex(ValueError, r"GHSA-2wx3-8x3w-r8qv"):
59+
_reject_non_algo_target("monai.auto3dseg.algo_gen.Algo", "algo_object.json")
60+
61+
def test_algo_from_json_rejects_payload_target(self):
62+
"""End to end: a malicious algo_object.json never reaches instantiation."""
63+
with tempfile.TemporaryDirectory() as tempdir:
64+
path = os.path.join(tempdir, "algo_object.json")
65+
marker = os.path.join(tempdir, "PWNED")
66+
with open(path, "w") as f:
67+
json.dump({"_target_": "subprocess.call", "args": ["/bin/sh", "-c", f"touch {marker}"]}, f)
68+
69+
with self.assertRaisesRegex(ValueError, r"GHSA-2wx3-8x3w-r8qv"):
70+
algo_from_json(path)
71+
self.assertFalse(os.path.exists(marker), "the algo_object.json payload executed")
72+
73+
74+
if __name__ == "__main__":
75+
unittest.main()

0 commit comments

Comments
 (0)