Skip to content
Open
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
106 changes: 103 additions & 3 deletions src/skillspector/nodes/analyzers/static_patterns_tool_misuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@
USES_PYTHON_IMPORT_BOUNDS = True
USES_PREPARED_PARSER_ANALYSIS = True
USES_RST_SOURCE_TYPE = True
USES_BATCH_SOURCE_TYPE = True
USES_SOLE_ORIGINAL_SHELL = True
ANALYZE_USES_POSTPROCESS = True
POSTPROCESS_USES_PYTHON_AST = True
Expand Down Expand Up @@ -4456,6 +4457,7 @@ def _has_shell_command_word_exhaustion(
shell_fences: tuple[tuple[int, int], ...] = (),
native_argument_spans: tuple[tuple[int, int], ...] = (),
native_argument_work: list[int] | None = None,
batch_operand_starts: frozenset[int] = frozenset(),
) -> StaticParserDiagnostic | None:
"""Find candidate command words whose deterministic parse hit a safety bound.

Expand Down Expand Up @@ -4751,6 +4753,16 @@ def retain_operand_bounds(
# Opening/inner command candidates remain independent.
backtick_closers.add(end - 1)
if parsed is None:
if (
start in batch_operand_starts
and word_diagnostics
and word_diagnostics[0].start == start
and word_diagnostics[0].cause is ParserCause.BOUNDARY_UNRESOLVED
and word_diagnostics[0].check is ParserCheck.COMMAND_WORD_BOUNDARY
):
# CMD closes this directory operand at the quote after the
# backslash. Keep looking for independent raw diagnostics.
continue
substitution_start = (
start + 1
if content[start : start + 1] in {"'", '"'} and content.startswith("$(", start + 1)
Expand Down Expand Up @@ -13240,13 +13252,27 @@ def owns(
return True


@dataclass(frozen=True)
class _BatchParserSource:
content: str


def prepare_parser_analysis(
content: str,
file_type: str,
check_runtime: Callable[[], None],
*,
sole_original_shell: bool = False,
) -> JSONSourceOwnership | _YamlParserAnalysis | _PythonGeneratedText | _FiniteShellSource | None:
) -> (
JSONSourceOwnership
| _YamlParserAnalysis
| _PythonGeneratedText
| _FiniteShellSource
| _BatchParserSource
| None
):
if file_type == "batch":
return _BatchParserSource(content)
if (
file_type == "python"
and ".textContent" in content
Expand Down Expand Up @@ -14956,7 +14982,7 @@ def bounded_parse_diagnostic(
)
if (
complete_context
and file_type in {"other", "xml"}
and file_type in {"batch", "other", "xml"}
and "wordprocessingml/" in content[:8192]
and content.removeprefix("\ufeff").lstrip().startswith("<")
):
Expand Down Expand Up @@ -15157,6 +15183,63 @@ def bounded_parse_diagnostic(
return exhausted


_CMD_IF_EXIST_QUOTED_PATH = re.compile(
r"^[ \t]*(?:@[ \t]*)?if[ \t]+(?:not[ \t]+)?exist[ \t]+"
r"""(?P<operand>"[^"\x00-\x1f$^&();<=>|\x60']*\\")[ \t]+[^ \t\r\n]""",
re.ASCII | re.IGNORECASE | re.MULTILINE,
)


def _batch_shell_word_text(
content: str,
check_runtime: Callable[[], None],
source_view: SecurityTextView | None,
prepared_analysis: object | None,
) -> tuple[str, frozenset[int]]:
"""Keep CMD path delimiters out of the generic shell command-word walk."""
if '\\"' not in content:
return content, frozenset()
if source_view is None or source_view.name == "raw":
original = content
source_view = None
elif isinstance(prepared_analysis, _BatchParserSource) and source_view.name in {
"normalized",
"compact",
"obfuscated-instruction",
}:
original = prepared_analysis.content
else:
return content, frozenset()
pieces: list[str] = []
operand_starts: set[int] = set()
cursor = 0
for match in _CMD_IF_EXIST_QUOTED_PATH.finditer(content):
check_runtime()
line_start = match.start()
if source_view is not None:
line_start = source_view.source_offset(line_start)
source_end = source_view.source_end_offset(match.end() - 1)
if original[line_start:source_end] != match[0] or (
line_start and original[line_start - 1] != "\n"
):
continue
preceding_end = line_start - 1 # LF before the physical line
if preceding_end > 0 and original[preceding_end - 1] == "\r":
preceding_end -= 1
if preceding_end > 0 and original[preceding_end - 1] == "^":
continue
start, end = match.span("operand")
# The path quotes cannot close a preceding shell quote. Keep offsets
# and the branch command intact; findings still use the original text.
pieces.extend((content[cursor:start], " " * (end - start)))
operand_starts.add(start)
cursor = end
if not pieces:
return content, frozenset()
pieces.append(content[cursor:])
return "".join(pieces), frozenset(operand_starts)


def _has_bounded_parse_exhaustion(
content: str,
check_runtime: Callable[[], None],
Expand Down Expand Up @@ -15398,6 +15481,11 @@ def _has_bounded_parse_exhaustion(
)
if file_type == "python" and complete_context:
shell_word_content = python_browser_template_shell_text(content, check_runtime)
batch_operand_starts: frozenset[int] = frozenset()
if file_type == "batch" and complete_context:
shell_word_content, batch_operand_starts = _batch_shell_word_text(
content, check_runtime, source_view, prepared_analysis
)
if json_projection is not None:
# Only validated host punctuation terminates command words. Every byte
# inside strings stays in the parser and original finding views remain raw.
Expand Down Expand Up @@ -15490,7 +15578,19 @@ def _has_bounded_parse_exhaustion(
shell_word_content = "".join(view)
# Perl ``eval BLOCK`` is recognized from its clause-initial ``eval`` and the
# adjacent brace alone, so unlike quote ownership it needs no full context.
diagnostic = _has_shell_command_word_exhaustion(
# Raw command words and nested command strings can have their own quote
# context. Only exempt the boundary at a proven CMD operand.
raw_batch_diagnostic = (
_has_shell_command_word_exhaustion(
content,
check_runtime,
file_type=file_type,
batch_operand_starts=batch_operand_starts,
)
if batch_operand_starts
else None
)
diagnostic = raw_batch_diagnostic or _has_shell_command_word_exhaustion(
shell_word_content,
check_runtime,
structural_quote_closers=structural_quote_closers,
Expand Down
44 changes: 25 additions & 19 deletions src/skillspector/nodes/analyzers/static_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -1406,6 +1406,26 @@ class _StaticScanMetrics(dict[str, int | float]):
pattern_limits: tuple[_StaticResourceLimitError, ...] = ()


def _parser_source_type(path: str, file_type: str, module: object) -> str:
# Finding applicability keeps its established inventory type.
if file_type != "other":
return file_type
lower_path = path.lower()
if lower_path.endswith(".rst") and getattr(module, "USES_RST_SOURCE_TYPE", False) is True:
return "rst"
if (
lower_path.endswith((".bat", ".cmd"))
and getattr(module, "USES_BATCH_SOURCE_TYPE", False) is True
):
return "batch"
return {
"jsx": "javascript",
"tsx": "tsx",
"mts": "typescript",
"cts": "typescript",
}.get(lower_path.rsplit(".", 1)[-1], file_type)


def _bounded_parser_incomplete(
module: object,
view: SecurityTextView,
Expand All @@ -1419,24 +1439,10 @@ def _bounded_parser_incomplete(
python_import_bounds: PythonImportBounds | None = None,
prepared_analysis: object | None = None,
) -> bool:
# Parser hooks consume the native dialect for the actual source path,
# including marker and derived views. Finding applicability keeps its
# established inventory type.
if file_type == "other":
suffix = path.lower().rsplit(".", 1)[-1]
file_type = {
"jsx": "javascript",
"tsx": "tsx",
"mts": "typescript",
"cts": "typescript",
}.get(suffix, file_type)
kwargs = {"file_type": file_type, "complete_context": complete_context}
if (
file_type == "other"
and path.lower().endswith(".rst")
and getattr(module, "USES_RST_SOURCE_TYPE", False) is True
):
kwargs["file_type"] = "rst"
kwargs = {
"file_type": _parser_source_type(path, file_type, module),
"complete_context": complete_context,
}
if vars(module).get("USES_PREPARED_PARSER_ANALYSIS") is True:
kwargs.update(
prepared_analysis=prepared_analysis,
Expand Down Expand Up @@ -3586,7 +3592,7 @@ def limited_result(
if prepare_parser is not None:
parser_analyses[id(module)] = prepare_parser(
content=content,
file_type=parser_file_type,
file_type=_parser_source_type(path, parser_file_type, module),
check_runtime=finding_budget.check_runtime,
**(
{"sole_original_shell": True}
Expand Down
104 changes: 104 additions & 0 deletions tests/nodes/analyzers/test_cmd_if_exist_quoting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Regression coverage for Windows batch directory tests."""

import pytest

from skillspector.inspection_ledger import LedgerOutcome, LedgerReason, ParserCheck
from skillspector.nodes.analyzers import static_patterns_tool_misuse as tool_misuse
from skillspector.nodes.analyzers import static_runner

_DIRECTORY_TEST = r'if exist "%out%\" goto :fail_named'
_COMMENTS = "".join(f"rem Benign fixture comment for step {step:03d}\n" for step in range(120))


def _scan(path: str, content: str):
return static_runner.run_static_patterns_with_ledger(
{"components": [path], "file_cache": {path: content}}, [tool_misuse]
)


@pytest.mark.parametrize(
("path", "statement", "newline"),
[
("check.bat", _DIRECTORY_TEST, "\r\n"),
("check.CMD", r' @IF NOT EXIST "C:\Output Folder\" GOTO fail_named', "\n"),
],
)
def test_cmd_directory_operand_can_end_in_backslash(path: str, statement: str, newline: str):
source = f"{statement}\nexit /b 0\n:fail_named\nexit /b 1\n{_COMMENTS}"
result = _scan(path, source.replace("\n", newline))

assert result["inspection_ledger"][0]["outcome"] is LedgerOutcome.COMPLETED
assert not result["findings"]


@pytest.mark.parametrize("path", ["check.sh", "check.txt"])
def test_cmd_quote_semantics_do_not_apply_to_other_sources(path: str):
result = _scan(path, f"{_DIRECTORY_TEST}\n{_COMMENTS}")

assert result["inspection_ledger"][0]["reason_code"] is LedgerReason.STATIC_PARSE_LIMIT


def test_cmd_directory_operand_keeps_later_command_analysis():
result = _scan("check.cmd", f'{_DIRECTORY_TEST}\n{_COMMENTS}rm -rf /\nbash -c "$PAYLOAD"\n')

row = result["inspection_ledger"][0]
assert row["reason_code"] is LedgerReason.STATIC_PARSE_LIMIT
assert row["parser_diagnostic"]["check"] is ParserCheck.COMMAND_STRING_RUNTIME
assert row["parser_diagnostic"]["start_line"] == 123
assert any(
finding.rule_id == "TM1" and finding.start_line == 122 for finding in result["findings"]
)


def test_cmd_directory_operand_does_not_close_an_unrelated_quote():
source = f'echo "unterminated\n{_DIRECTORY_TEST}\n{_COMMENTS}'
result = _scan("check.bat", source)

row = result["inspection_ledger"][0]
assert row["reason_code"] is LedgerReason.STATIC_PARSE_LIMIT
assert row["parser_diagnostic"]["check"] is ParserCheck.COMMAND_WORD_BOUNDARY
assert row["parser_diagnostic"]["start_line"] == 1


@pytest.mark.parametrize(
("statement", "environment"),
[
(_DIRECTORY_TEST, "BASH_ENV"),
(r'if exist "%out%\" goto :fail_named', "BASH_ENV"),
],
)
def test_cmd_looking_line_inside_shell_program_keeps_runtime_diagnostic(
statement: str, environment: str
):
source = f"""bash -c 'printf "hello
{statement}
{environment}=/tmp/startup bash -c true
'
"""
result = _scan("check.cmd", source)

row = result["inspection_ledger"][0]
assert row["reason_code"] is LedgerReason.STATIC_PARSE_LIMIT
assert row["parser_diagnostic"]["check"] is ParserCheck.COMMAND_STRING_RUNTIME
assert row["parser_diagnostic"]["start_line"] == 3


def test_cmd_operand_in_raw_source_is_recognized_in_compacted_view():
source = f"{_DIRECTORY_TEST}\nrem t e s t e x a m p l e\n{_COMMENTS}"

result = _scan("check.bat", source)

assert result["inspection_ledger"][0]["outcome"] is LedgerOutcome.COMPLETED


def test_cmd_looking_line_keeps_runtime_selected_command_diagnostic():
source = '${COMMAND:-"\n' + _DIRECTORY_TEST + "\n} -rf /\n"

result = _scan("check.bat", source)

row = result["inspection_ledger"][0]
assert row["reason_code"] is LedgerReason.STATIC_PARSE_LIMIT
assert row["parser_diagnostic"]["check"] is ParserCheck.COMMAND_IDENTITY
Loading