Skip to content

Commit 059fa80

Browse files
authored
Arm backend: Fix Metis bug in backend.py, CWE-22 (pytorch#23485)
Fix for security bug reported by Metis. cc @digantdesai @freddan80 @per @zingo @oscarandersson8218 @mansnils @Sebastian-Larsson @robell @rascani Signed-off-by: Elena Zhelezina <elena.zhelezina@arm.com>
1 parent adc0bcc commit 059fa80

2 files changed

Lines changed: 241 additions & 10 deletions

File tree

‎backends/arm/test/misc/test_vgf_backend.py‎

Lines changed: 143 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
# Copyright 2025-2026 Arm Limited and/or its affiliates.
2-
# Copyright 2026 Arm Limited and/or its affiliates.
32
#
43
# This source code is licensed under the BSD-style license found in the
54
# LICENSE file in the root directory of this source tree.
65

76
import os
7+
from pathlib import Path
88
from types import SimpleNamespace
99
from typing import cast
1010
from unittest import mock
@@ -23,6 +23,8 @@
2323
_copy_failure_artifacts,
2424
_format_repro_command,
2525
_replace_converter_input_path,
26+
_safe_output_path,
27+
_validate_tag_name,
2628
vgf_compile,
2729
)
2830
from executorch.exir.backend.backend_details import PreprocessResult
@@ -177,6 +179,83 @@ def fake_vgf_compile(tosa_flatbuffer, compile_flags, artifact_path, tag_name):
177179
assert captured_flags == ["--emit-debug-info"]
178180

179181

182+
@pytest.mark.parametrize(
183+
"tag_name",
184+
[
185+
"",
186+
"delegate_0",
187+
"delegate-1",
188+
"delegate.2",
189+
"Partition_A-1.2",
190+
],
191+
)
192+
def test_validate_tag_name_accepts_safe_values(tag_name):
193+
assert _validate_tag_name(tag_name) == tag_name
194+
195+
196+
@pytest.mark.parametrize(
197+
"tag_name",
198+
[
199+
"..",
200+
"../escape",
201+
"../../escape",
202+
"delegate/../../../escape",
203+
"/absolute/escape",
204+
r"..\escape",
205+
r"delegate\..\..\escape",
206+
r"C:\temp\escape",
207+
"delegate name",
208+
"delegate:name",
209+
"delegate$evil",
210+
],
211+
)
212+
def test_validate_tag_name_rejects_unsafe_path_values(tag_name):
213+
with pytest.raises(ValueError, match="Invalid VGF delegation tag"):
214+
_validate_tag_name(tag_name)
215+
216+
217+
def test_safe_output_path_accepts_child_path(tmp_path):
218+
output_path = _safe_output_path(str(tmp_path), "output.tosa")
219+
220+
assert output_path == os.path.realpath(tmp_path / "output.tosa")
221+
222+
223+
def test_safe_output_path_rejects_parent_traversal(tmp_path):
224+
with pytest.raises(
225+
ValueError,
226+
match="escapes the intended directory",
227+
):
228+
_safe_output_path(str(tmp_path), "../outside.tosa")
229+
230+
231+
def test_copy_failure_artifacts_rejects_unsafe_tag_name(tmp_path):
232+
tosa_path = tmp_path / "input.tosa"
233+
artifact_path = tmp_path / "artifacts"
234+
tosa_path.write_bytes(b"tosa bytes")
235+
236+
with pytest.raises(ValueError, match="Invalid VGF delegation tag"):
237+
_copy_failure_artifacts(
238+
str(tosa_path),
239+
str(artifact_path),
240+
tag_name="../../outside",
241+
)
242+
243+
assert not list(tmp_path.glob("outside*"))
244+
245+
246+
@mock.patch("executorch.backends.arm.vgf.backend.subprocess.run")
247+
def test_vgf_compile_rejects_unsafe_tag_before_converter_is_invoked(mock_run):
248+
with pytest.raises(ValueError, match="Invalid VGF delegation tag"):
249+
vgf_compile(
250+
b"serialized tosa",
251+
[],
252+
artifact_path=None,
253+
tag_name="../../outside",
254+
)
255+
256+
mock_run.assert_not_called()
257+
258+
180259
def test_format_repro_command_quotes_shell_metacharacters():
181260
command = [
182261
"model-converter",
@@ -348,7 +427,8 @@ def test_vgf_compile_failure_includes_temp_repro_command_without_artifact_path(
348427
assert "Vgf compiler failed." in error
349428
assert "Repro command:" in error
350429
assert "model-converter --some-flag -i" in error
351-
assert "output_delegate_0.tosa.vgf" in error
430+
assert "output.tosa.vgf" in error
431+
assert "output_delegate_0.tosa" not in error
352432
assert "failed_model_converter_input_delegate_0.tosa" not in error
353433
assert "Stderr:\nconverter stderr" in error
354434
assert "Stdout:\nconverter stdout" in error
@@ -390,3 +470,64 @@ def test_vgf_compile_failure_preserves_converter_error_when_artifact_copy_fails(
390470
assert "cannot copy artifact" in error
391471
assert "Stderr:\nconverter stderr" in error
392472
assert "Stdout:\nconverter stdout" in error
473+
474+
475+
@mock.patch("executorch.backends.arm.vgf.backend.model_converter_env")
476+
@mock.patch("executorch.backends.arm.vgf.backend.require_model_converter_executable")
477+
@mock.patch("executorch.backends.arm.vgf.backend.subprocess.run")
478+
def test_vgf_compile_success_artifacts_are_distinct_per_tag(
479+
mock_run,
480+
mock_require_model_converter_executable,
481+
mock_model_converter_env,
482+
tmp_path,
483+
):
484+
artifact_path = tmp_path / "artifacts"
485+
486+
mock_require_model_converter_executable.return_value = "model-converter"
487+
mock_model_converter_env.return_value = {"PATH": "/test/bin"}
488+
489+
def fake_converter_run(command, **kwargs):
490+
input_path = command[command.index("-i") + 1]
491+
output_path = command[command.index("-o") + 1]
492+
493+
# Make the generated VGF content depend on the TOSA input so the test
494+
# verifies both compilation results independently.
495+
input_bytes = Path(input_path).read_bytes()
496+
Path(output_path).write_bytes(b"vgf:" + input_bytes)
497+
498+
return backend.subprocess.CompletedProcess(
499+
command,
500+
0,
501+
stdout=b"",
502+
stderr=b"",
503+
)
504+
505+
mock_run.side_effect = fake_converter_run
506+
507+
tag0_result = vgf_compile(
508+
b"partition zero",
509+
[],
510+
artifact_path=str(artifact_path),
511+
tag_name="tag0",
512+
)
513+
tag1_result = vgf_compile(
514+
b"partition one",
515+
[],
516+
artifact_path=str(artifact_path),
517+
tag_name="tag1",
518+
)
519+
520+
tag0_artifact = artifact_path / "output_tag0.tosa.vgf"
521+
tag1_artifact = artifact_path / "output_tag1.tosa.vgf"
522+
523+
assert tag0_result == b"vgf:partition zero"
524+
assert tag1_result == b"vgf:partition one"
525+
526+
assert tag0_artifact.read_bytes() == b"vgf:partition zero"
527+
assert tag1_artifact.read_bytes() == b"vgf:partition one"
528+
529+
# Regression check: successful compilations must not collapse back onto
530+
# the basename of the fixed temporary converter output.
531+
assert not (artifact_path / "output.tosa.vgf").exists()
532+
533+
assert mock_run.call_count == 2

‎backends/arm/vgf/backend.py‎

Lines changed: 98 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import logging
1616
import os # nosec B404 - used alongside subprocess for tool invocation
17+
import re
1718
import shlex
1819
import shutil
1920
import subprocess # nosec B404 - required to drive external converter CLI
@@ -261,6 +262,79 @@ def preprocess(
261262
return PreprocessResult(processed_bytes=binary)
262263

263264

265+
_SAFE_VGF_TAG_NAME_RE = re.compile(r"[A-Za-z0-9_.-]*")
266+
267+
268+
def _validate_tag_name(tag_name: str) -> str:
269+
"""Validate a delegation tag before it is used in an artifact filename.
270+
271+
Delegation tags originate from graph metadata and must therefore be
272+
treated as untrusted when they cross into filesystem operations.
273+
274+
Args:
275+
tag_name: Delegation tag associated with the compiled partition.
276+
277+
Returns:
278+
The unchanged tag when it is safe for use as a filename component.
279+
280+
Raises:
281+
ValueError: If the tag contains path traversal, path separators, or
282+
characters outside the filename allowlist.
283+
284+
"""
285+
if (
286+
"/" in tag_name
287+
or "\\" in tag_name
288+
or ".." in tag_name
289+
or _SAFE_VGF_TAG_NAME_RE.fullmatch(tag_name) is None
290+
):
291+
raise ValueError(
292+
"Invalid VGF delegation tag: only ASCII letters, digits, '_', "
293+
"'.', and '-' are allowed, and path separators or '..' are "
294+
"forbidden."
295+
)
296+
297+
return tag_name
298+
299+
300+
def _safe_output_path(directory: str, filename: str) -> str:
301+
"""Construct an output path that is confined to ``directory``.
302+
303+
Both paths are resolved before comparison so traversal components and
304+
existing symlinks cannot move the resulting path outside the requested
305+
directory.
306+
307+
Args:
308+
directory: Directory that must contain the resulting file.
309+
filename: Filename to place inside ``directory``.
310+
311+
Returns:
312+
Absolute normalized path to the requested output.
313+
314+
Raises:
315+
ValueError: If the resulting path escapes ``directory``.
316+
317+
"""
318+
directory_path = os.path.realpath(directory)
319+
output_path = os.path.realpath(os.path.join(directory_path, filename))
320+
321+
try:
322+
is_contained = (
323+
os.path.commonpath([directory_path, output_path]) == directory_path
324+
)
325+
except ValueError:
326+
# On Windows, commonpath() also raises when paths reside on different
327+
# drives. Such a path cannot be contained in the requested directory.
328+
is_contained = False
329+
330+
if not is_contained:
331+
raise ValueError(
332+
f"VGF output path escapes the intended directory: {filename!r}"
333+
)
334+
335+
return output_path
336+
337+
264338
def _format_repro_command(command: List[str]) -> str:
265339
"""Return a shell-safe command string for reproducing converter failures."""
266340
return " ".join(shlex.quote(arg) for arg in command)
@@ -285,10 +359,12 @@ def _copy_failure_artifacts(
285359
if not artifact_path:
286360
return None
287361

362+
safe_tag_name = _validate_tag_name(tag_name)
363+
288364
os.makedirs(artifact_path, exist_ok=True)
289365

290-
suffix = f"_{tag_name}" if tag_name else ""
291-
failure_tosa_path = os.path.join(
366+
suffix = f"_{safe_tag_name}" if safe_tag_name else ""
367+
failure_tosa_path = _safe_output_path(
292368
artifact_path,
293369
f"failed_model_converter_input{suffix}.tosa",
294370
)
@@ -327,10 +403,15 @@ def vgf_compile(
327403
bytes: Compiled VGF binary emitted by ``model-converter``.
328404
329405
"""
406+
# tag_name comes from delegation metadata. Validate it before performing
407+
# any filesystem operations, including failure-artifact handling.
408+
safe_tag_name = _validate_tag_name(tag_name)
409+
330410
with tempfile.TemporaryDirectory() as tmpdir:
331-
# We currently write out a flatbuffer as input to the converter
332-
tosaname = f"output_{tag_name}.tosa"
333-
tosa_path = os.path.join(tmpdir, tosaname)
411+
# The TemporaryDirectory already provides uniqueness, so there is no
412+
# reason to put untrusted delegation metadata in this filename.
413+
tosaname = "output.tosa"
414+
tosa_path = _safe_output_path(tmpdir, tosaname)
334415
with open(tosa_path, "wb") as f:
335416
f.write(tosa_flatbuffer)
336417

@@ -361,7 +442,7 @@ def vgf_compile(
361442
failure_tosa_path = _copy_failure_artifacts(
362443
tosa_path,
363444
artifact_path,
364-
tag_name,
445+
safe_tag_name,
365446
)
366447
except Exception as artifact_error:
367448
failure_artifact_error = artifact_error
@@ -388,9 +469,18 @@ def vgf_compile(
388469
)
389470

390471
if artifact_path:
391-
logger.info(f"Emitting debug output to: {vgf_path=}")
392472
os.makedirs(artifact_path, exist_ok=True)
393-
shutil.copy2(vgf_path, artifact_path)
473+
474+
# Keep delegation metadata out of the temporary converter paths,
475+
# but preserve it in the persistent debug artifact name. The tag
476+
# has already been validated above.
477+
suffix = f"_{safe_tag_name}" if safe_tag_name else ""
478+
artifact_vgf_path = _safe_output_path(
479+
artifact_path,
480+
f"output{suffix}.tosa.vgf",
481+
)
482+
logger.info(f"Emitting debug output to: {artifact_vgf_path}")
483+
shutil.copy2(vgf_path, artifact_vgf_path)
394484

395485
vgf_bytes = open(vgf_path, "rb").read()
396486
return vgf_bytes

0 commit comments

Comments
 (0)