Skip to content

armgit / rembg

Public Imported from GitHub
0

Rembg is a tool to remove images background

fix: restrict sam_model to published checkpoints (GHSA-qr6x-7v33-6qmg)

Daniel Gatisb2758c6b39bb
diff --git a/rembg/sessions/sam.py b/rembg/sessions/sam.py
index fe55aa1..e0f682d 100644
--- a/rembg/sessions/sam.py
+++ b/rembg/sessions/sam.py
@@ -124,6 +124,42 @@ def transform_masks(masks, original_size, transform_matrix):
return np.array(output_masks)
+#: md5 of every SAM release asset, keyed by filename.
+#:
+#: Two things depend on this table. `sam_model` reaches this module straight
+#: from the public `extras` payload of `/api/remove`, and its value is
+#: interpolated into both download URLs and local filenames, so a name outside
+#: these keys is rejected before it can steer a path or a URL. The digests then
+#: pin what is fetched, matching every other session; SAM used to pass no hash
+#: at all, which left a swapped asset undetected.
+SAM_CHECKSUMS = {
+ "sam_vit_b_01ec64.encoder.onnx": "md5:a780f8ba09bceceaa1435724ed354848",
+ "sam_vit_b_01ec64.decoder.onnx": "md5:c4218b16ec1cb09889fcd6eb7a42a7c9",
+ "sam_vit_b_01ec64.encoder.quant.onnx": "md5:26fc0e01d2fa34ed2d3f91259118482d",
+ "sam_vit_b_01ec64.decoder.quant.onnx": "md5:45391530307d1aee79b2a1507769e6c7",
+ "sam_vit_l_0b3195.encoder.onnx": "md5:6e7c5e3e97b50a9e833e55062ae35182",
+ "sam_vit_l_0b3195.decoder.onnx": "md5:dc760a2912862c05ec3ac2658162a1b5",
+ "sam_vit_l_0b3195.encoder.quant.onnx": "md5:83f7fe08c2f8b94b6d08c3e44cf1de0e",
+ "sam_vit_l_0b3195.decoder.quant.onnx": "md5:e78ca201f5ae92288945623f48088b7c",
+ "sam_vit_h_4b8939.encoder.onnx": "md5:2630bbbf7f256ff82455ecce70467734",
+ "sam_vit_h_4b8939.decoder.onnx": "md5:2241a15c7c5e5b6ac018223d1a795a94",
+ "sam_vit_h_4b8939.encoder.quant.onnx": "md5:391503beb5e5d7d1ae6f55d0cecabd50",
+ "sam_vit_h_4b8939.decoder.quant.onnx": "md5:4c86ebeecbe2e6325203b641b8702a5b",
+ "sam_vit_h_4b8939.encoder_data.1.bin": "md5:22316455879cd64f1414bc2cc84772ab",
+ "sam_vit_h_4b8939.encoder_data.2.bin": "md5:3ca4efe12cd9a686e60364a628546440",
+ "sam_vit_h_4b8939.encoder_data.3.bin": "md5:635041e6eac1c3e6ac7eceeef1ed1f38",
+}
+
+#: SAM checkpoints published as release assets, as an allowlist.
+SAM_MODELS = frozenset(
+ {
+ "sam_vit_b_01ec64",
+ "sam_vit_l_0b3195",
+ "sam_vit_h_4b8939",
+ }
+)
+
+
class SamSession(BaseSession):
"""
This class represents a session for the Sam model.
@@ -311,7 +347,18 @@ class SamSession(BaseSession):
tuple: A tuple containing the file paths of the downloaded encoder and decoder models.
"""
model_name = kwargs.get("sam_model", "sam_vit_b_01ec64")
- quant = kwargs.get("sam_quant", False)
+ quant = bool(kwargs.get("sam_quant", False))
+
+ if model_name not in SAM_MODELS:
+ raise ValueError(
+ f"unknown sam_model {model_name!r}; "
+ f"expected one of {', '.join(sorted(SAM_MODELS))}"
+ )
+
+ def known_hash(fname):
+ if cls.checksum_disabled(*args, **kwargs):
+ return None
+ return SAM_CHECKSUMS.get(fname)
fname_encoder = f"{model_name}.encoder.onnx"
fname_decoder = f"{model_name}.decoder.onnx"
@@ -340,7 +387,7 @@ class SamSession(BaseSession):
pooch.retrieve(
f"https://github.com/danielgatis/rembg/releases/download/v0.0.0/{fname_encoder}",
- None,
+ known_hash(fname_encoder),
fname=fname_encoder,
path=target,
progressbar=True,
@@ -348,7 +395,7 @@ class SamSession(BaseSession):
pooch.retrieve(
f"https://github.com/danielgatis/rembg/releases/download/v0.0.0/{fname_decoder}",
- None,
+ known_hash(fname_decoder),
fname=fname_decoder,
path=target,
progressbar=True,
@@ -362,7 +409,7 @@ class SamSession(BaseSession):
for i in range(1, 4):
pooch.retrieve(
f"https://github.com/danielgatis/rembg/releases/download/v0.0.0/sam_vit_h_4b8939.encoder_data.{i}.bin",
- None,
+ known_hash(f"sam_vit_h_4b8939.encoder_data.{i}.bin"),
fname=f"sam_vit_h_4b8939.encoder_data.{i}.bin",
path=target,
progressbar=True,
diff --git a/tests/test_sam_model_allowlist.py b/tests/test_sam_model_allowlist.py
new file mode 100644
index 0000000..ff399ac
--- /dev/null
+++ b/tests/test_sam_model_allowlist.py
@@ -0,0 +1,105 @@
+import pytest
+
+from rembg.sessions.sam import SAM_MODELS, SamSession
+
+
+ "sam_model",
+ [
+ "../../../../etc/rembg_evil",
+ "sam_vit_b_01ec64/../../../evil",
+ "sam_vit_b_01ec64#/../../evil",
+ "/etc/passwd",
+ "sam_vit_b_01ec64\x00evil",
+ "",
+ ],
+)
+def test_download_models_rejects_injected_names(sam_model, tmp_path, monkeypatch):
+ """A `sam_model` that could steer a path or a URL never reaches pooch.
+
+ `sam_model` arrives straight from the public `extras` payload of
+ `/api/remove`, so a traversal or fragment in it must be refused before it is
+ interpolated into a download URL or a local filename.
+ """
+ monkeypatch.setenv("REMBG_HOME", str(tmp_path))
+
+ with pytest.raises(ValueError, match="unknown sam_model"):
+ SamSession.download_models(sam_model=sam_model)
+
+
+def test_download_models_rejects_before_any_download(tmp_path, monkeypatch):
+ """Rejection happens before pooch is called at all, not after a fetch."""
+ monkeypatch.setenv("REMBG_HOME", str(tmp_path))
+
+ def explode(*args, **kwargs):
+ raise AssertionError("pooch.retrieve must not run for a rejected sam_model")
+
+ monkeypatch.setattr("rembg.sessions.sam.pooch.retrieve", explode)
+
+ with pytest.raises(ValueError, match="unknown sam_model"):
+ SamSession.download_models(sam_model="../../evil")
+
+
+def test_allowlist_holds_only_published_checkpoints():
+ """The allowlist tracks the SAM checkpoints published as release assets."""
+ assert SAM_MODELS == {
+ "sam_vit_b_01ec64",
+ "sam_vit_l_0b3195",
+ "sam_vit_h_4b8939",
+ }
+
+
+def test_injected_name_never_reaches_a_url_or_path(tmp_path, monkeypatch):
+ """The guard is what stops injection, not the shape of the call below it.
+
+ Records every URL and path pooch would be handed. Before the allowlist this
+ captured a traversal in `fname` and a `#fragment` in the URL; now nothing is
+ recorded because the call is refused first.
+ """
+ monkeypatch.setenv("REMBG_HOME", str(tmp_path))
+
+ seen = []
+
+ def record(url, known_hash, **kwargs):
+ seen.append((url, kwargs.get("fname"), kwargs.get("path")))
+ raise AssertionError(f"pooch.retrieve reached with {url!r}")
+
+ monkeypatch.setattr("rembg.sessions.sam.pooch.retrieve", record)
+
+ with pytest.raises(ValueError, match="unknown sam_model"):
+ SamSession.download_models(sam_model="sam_vit_b_01ec64#/../../../evil")
+
+ assert seen == []
+
+
+def test_every_allowed_model_has_pinned_checksums():
+ """Each allowed checkpoint has a digest for all four of its assets.
+
+ SAM previously downloaded with no hash at all. If a new checkpoint is added
+ to the allowlist without its digests, it would silently download unpinned.
+ """
+ from rembg.sessions.sam import SAM_CHECKSUMS
+
+ for model in SAM_MODELS:
+ for part in ("encoder", "decoder"):
+ for suffix in (".onnx", ".quant.onnx"):
+ fname = f"{model}.{part}{suffix}"
+ assert fname in SAM_CHECKSUMS, f"missing checksum for {fname}"
+ assert SAM_CHECKSUMS[fname].startswith("md5:")
+
+
+def test_vit_h_sidecar_blobs_are_pinned():
+ """The large encoder's three sidecar blobs are pinned too."""
+ from rembg.sessions.sam import SAM_CHECKSUMS
+
+ for i in (1, 2, 3):
+ fname = f"sam_vit_h_4b8939.encoder_data.{i}.bin"
+ assert fname in SAM_CHECKSUMS, f"missing checksum for {fname}"
+
+
+def test_checksums_cover_only_allowed_models():
+ """No digest refers to a checkpoint outside the allowlist."""
+ from rembg.sessions.sam import SAM_CHECKSUMS
+
+ for fname in SAM_CHECKSUMS:
+ assert any(fname.startswith(m + ".") for m in SAM_MODELS), fname