fix(skills): review package text regardless of filename (#8445)

* fix(skills): review package text regardless of filename

* test(skills): cover binary markers after long text prefixes

* fix(skills): verify inferred operations and preflight model review budgets
This commit is contained in:
Nan Gao 2026-11-21 15:37:25 +08:00 committed by GitHub
parent 2abcfa4250
commit 57cc925e5b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 501 additions and 100 deletions

View File

@ -5,6 +5,7 @@ Both Gateway and Client delegate to these functions.
"""
import asyncio
import codecs
import concurrent.futures
import logging
import os
@ -15,7 +16,7 @@ import unicodedata
import zipfile
from pathlib import Path, PurePosixPath, PureWindowsPath
from deerflow.skills.package_files import is_code_path, is_executable_binary_prefix
from deerflow.skills.package_files import MAX_MODEL_BYTES, MAX_MODEL_FILE_BYTES, MAX_MODEL_FILES, is_code_path, is_executable_binary_prefix
from deerflow.skills.permissions import make_skill_tree_sandbox_readable
from deerflow.skills.security_scanner import scan_skill_content
from deerflow.skills.security_static_scanner import (
@ -26,6 +27,7 @@ from deerflow.skills.security_static_scanner import (
scan_archive_preflight,
skill_scan_enabled,
)
from deerflow.skills.skillscan.orchestrator import contains_sensitive_package_content
from deerflow.utils.host_paths import windows_incompatible_segment
logger = logging.getLogger(__name__)
@ -270,13 +272,7 @@ def safe_extract_skill_archive(
member_path.chmod(0o755 if (info.external_attr >> 16) & 0o111 else 0o644)
def _is_script_support_file(rel_path: Path) -> bool:
return bool(rel_path.parts) and rel_path.parts[0] == "scripts"
def _should_scan_support_file(rel_path: Path) -> bool:
if _is_script_support_file(rel_path):
return True
def _is_prompt_input(rel_path: Path) -> bool:
return bool(rel_path.parts) and rel_path.parts[0] in _PROMPT_INPUT_DIRS and rel_path.suffix.lower() in _PROMPT_INPUT_SUFFIXES
@ -321,16 +317,43 @@ def _findings_for_file(findings: list[StaticFinding], rel_path: str) -> list[Sta
return [finding for finding in findings if finding.get("file") in {rel_path, None}]
async def _scan_skill_file_or_raise(skill_dir: Path, path: Path, skill_name: str, *, executable: bool, static_findings: list[StaticFinding] | None = None, app_config=None) -> None:
rel_path = path.relative_to(skill_dir).as_posix()
def _read_additional_text(path: Path, rel_path: str, location: str) -> tuple[str, int] | None:
"""Recognize complete UTF-8 text while retaining at most one model input."""
decoder = codecs.getincrementaldecoder("utf-8")()
parts = []
size = 0
try:
with path.open("rb") as stream:
while chunk := stream.read(64 * 1024):
if b"\0" in chunk:
return None
decoded = decoder.decode(chunk)
size += len(chunk)
if size <= MAX_MODEL_FILE_BYTES:
parts.append(decoded)
decoder.decode(b"", final=True)
except UnicodeDecodeError:
return None
# A binary asset can have a valid text prefix past the limit, so apply the text budget only after validating EOF.
if size > MAX_MODEL_FILE_BYTES:
raise SkillSecurityScanError(f"Security scan failed for {location}: additional text file exceeds the review size limit")
content = "".join(parts)
if contains_sensitive_package_content(rel_path, content):
raise SkillSecurityScanError(f"Security scan blocked {location}: remove sensitive configuration before model review")
return content, size
def _read_required_text(path: Path, location: str) -> str:
try:
return path.read_text(encoding="utf-8")
except UnicodeDecodeError as e:
raise SkillSecurityScanError(f"Security scan failed for {location}: file must be valid UTF-8") from e
async def _scan_skill_file_or_raise(content: str, rel_path: str, skill_name: str, *, executable: bool, static_findings: list[StaticFinding], app_config=None) -> None:
location = f"{skill_name}/{rel_path}"
try:
content = await asyncio.to_thread(path.read_text, encoding="utf-8")
except UnicodeDecodeError as e:
raise SkillSecurityScanError(f"Security scan failed for skill '{skill_name}': {location} must be valid UTF-8") from e
try:
result = await scan_skill_content(content, executable=executable, location=location, app_config=app_config, static_findings=static_findings or [])
result = await scan_skill_content(content, executable=executable, location=location, app_config=app_config, static_findings=static_findings)
except Exception as e:
raise SkillSecurityScanError(f"Security scan failed for {location}: {e}") from e
@ -373,42 +396,49 @@ async def _scan_static_skill_archive_or_raise(skill_dir: Path, skill_name: str,
def _collect_scannable_files(skill_dir: Path) -> list[Path]:
"""Enumerate archive files for scanning (blocking; run off the event loop)."""
return [candidate for candidate in sorted(skill_dir.rglob("*")) if candidate.is_file()]
"""Review the required declaration first, then the remaining archive files."""
skill_md = skill_dir / "SKILL.md"
others = sorted(candidate for candidate in skill_dir.rglob("*") if candidate != skill_md and candidate.is_file())
return [skill_md, *others]
async def _prepare_model_review(skill_dir: Path, skill_name: str) -> list[tuple[str, bool, str | None]]:
"""Check the package budget before moderation. Cache only budgeted text."""
review_files = []
skill_md = skill_dir / "SKILL.md"
additional_files = additional_bytes = 0
for path in await asyncio.to_thread(_collect_scannable_files, skill_dir):
rel_path = path.relative_to(skill_dir)
if path != skill_md and path.name == "SKILL.md":
raise SkillSecurityScanError(f"Security scan failed for skill '{skill_name}': nested SKILL.md is not allowed at {skill_name}/{rel_path.as_posix()}")
rel_path_posix = rel_path.as_posix()
executable = await _is_code_file(path, rel_path)
if path == skill_md or executable or _is_prompt_input(rel_path):
review_files.append((rel_path_posix, executable, None))
continue
# An interpreter can consume text under any name. Require explicit
# approval for these files even when optional SkillScan is disabled.
location = f"{skill_name}/{rel_path_posix}"
additional = await asyncio.to_thread(_read_additional_text, path, rel_path_posix, location)
if additional is None:
continue
content, size = additional
additional_files += 1
additional_bytes += size
if additional_files > MAX_MODEL_FILES or additional_bytes > MAX_MODEL_BYTES:
raise SkillSecurityScanError(f"Security scan failed for {location}: additional text exceeds the package review budget")
review_files.append((rel_path_posix, True, content))
return review_files
async def _scan_skill_archive_contents_or_raise(skill_dir: Path, skill_name: str, *, app_config=None) -> list[StaticFinding]:
"""Run the skill security scanner against all installable text and script files."""
static_findings = await _scan_static_skill_archive_or_raise(skill_dir, skill_name, app_config=app_config)
skill_md = skill_dir / "SKILL.md"
await _scan_skill_file_or_raise(skill_dir, skill_md, skill_name, executable=False, static_findings=_findings_for_file(static_findings, "SKILL.md"), app_config=app_config)
for path in await asyncio.to_thread(_collect_scannable_files, skill_dir):
rel_path = path.relative_to(skill_dir)
if rel_path == Path("SKILL.md"):
continue
if path.name == "SKILL.md":
raise SkillSecurityScanError(f"Security scan failed for skill '{skill_name}': nested SKILL.md is not allowed at {skill_name}/{rel_path.as_posix()}")
rel_path_posix = rel_path.as_posix()
if await _is_code_file(path, rel_path):
await _scan_skill_file_or_raise(
skill_dir,
path,
skill_name,
executable=True,
static_findings=_findings_for_file(static_findings, rel_path_posix),
app_config=app_config,
)
elif _should_scan_support_file(rel_path):
await _scan_skill_file_or_raise(
skill_dir,
path,
skill_name,
executable=False,
static_findings=_findings_for_file(static_findings, rel_path_posix),
app_config=app_config,
)
for rel_path, executable, content in await _prepare_model_review(skill_dir, skill_name):
if content is None:
content = await asyncio.to_thread(_read_required_text, skill_dir / rel_path, f"{skill_name}/{rel_path}")
await _scan_skill_file_or_raise(content, rel_path, skill_name, executable=executable, static_findings=_findings_for_file(static_findings, rel_path), app_config=app_config)
return static_findings

View File

@ -10,15 +10,13 @@ from dataclasses import dataclass
from pathlib import Path
from deerflow.skills.mutations.assets import PackageSnapshot
from deerflow.skills.mutations.validation import MAX_MAIN_BYTES, PARSER_VERSION
from deerflow.skills.package_files import is_code_file
from deerflow.skills.mutations.validation import PARSER_VERSION
from deerflow.skills.package_files import MAX_MODEL_BYTES, MAX_MODEL_FILE_BYTES, MAX_MODEL_FILES, is_code_file
from deerflow.skills.security_scanner import scan_skill_content
from deerflow.skills.skillscan.orchestrator import scan_skill_dir
from deerflow.utils.file_io import await_drained
CHECK_POLICY_VERSION = "skill-mutation-check-v1"
MAX_MODEL_FILES = 32
MAX_MODEL_BYTES = 1024 * 1024
CHECK_POLICY_VERSION = "skill-mutation-check-v2"
CHECK_TIMEOUT_SECONDS = 120
@ -65,7 +63,7 @@ class CandidateScanner:
return None, None
continue
total += len(item.content)
if len(item.content) > MAX_MAIN_BYTES or total > MAX_MODEL_BYTES or len(text_files) >= MAX_MODEL_FILES:
if len(item.content) > MAX_MODEL_FILE_BYTES or total > MAX_MODEL_BYTES or len(text_files) >= MAX_MODEL_FILES:
return None, None
text_files.append((item.path, content, executable))
with tempfile.TemporaryDirectory(prefix="deerflow-host-check-") as temporary:

View File

@ -7,9 +7,10 @@ import json
import yaml
from deerflow.skills.frontmatter import _FRONTMATTER_RE, ALLOWED_FRONTMATTER_PROPERTIES
from deerflow.skills.package_files import MAX_MODEL_FILE_BYTES
from deerflow.skills.validation import validate_skill_frontmatter_text
MAX_MAIN_BYTES = 128 * 1024
MAX_MAIN_BYTES = MAX_MODEL_FILE_BYTES
PARSER_VERSION = "skill-mutation-frontmatter-v1"

View File

@ -8,6 +8,11 @@ from __future__ import annotations
from pathlib import PurePath, PurePosixPath
# Bound the amount of package text admitted to a model review.
MAX_MODEL_FILES = 32
MAX_MODEL_FILE_BYTES = 128 * 1024
MAX_MODEL_BYTES = 1024 * 1024
#: Filler bytes an executable magic may hide behind: ASCII whitespace (space,
#: tab, LF, CR, vertical tab, form feed) and NUL padding.
_EXEC_SNIFF_FILLER = b" \t\n\r\x0b\x0c\x00"

View File

@ -46,6 +46,9 @@ _BLOCK_SEVERITY = "CRITICAL"
_NESTED_ZIP_PEEK_MEMBER_LIMIT = 256
_MAX_ARCHIVE_MEMBERS = 4096
_TEXT_PROBE_BYTES = 4096
# Trying the Python parser on a data file can amplify a compact JSON array into
# many AST nodes. Bound speculative parsing separately from known Python files.
_MAX_INFERRED_PYTHON_CHARS = 128 * 1024
_SPECS = [
RuleSpec("package-path-traversal", "CRITICAL", "Archive member path traverses outside the skill root.", "Remove parent-directory traversal from the package path."),
@ -65,6 +68,7 @@ _SPECS = [
RuleSpec("package-nested-archive", "HIGH", "Package contains a nested archive file.", "Unpack and review nested archives before packaging the skill."),
RuleSpec("package-hidden-sensitive-file", "HIGH", "Package contains a hidden sensitive file.", "Remove hidden credential or package-manager config files."),
RuleSpec("package-undecodable-script", "HIGH", "Code file is not NUL-free UTF-8 text, so it was analyzed from a lossy decode.", "Store code as UTF-8 text without NUL bytes, and keep compiled or binary artifacts out of scripts/."),
RuleSpec("package-python-analysis-limit", "HIGH", "Text exceeds the limit for inferring Python source.", "Review the file or split it into smaller files before installation."),
RuleSpec("package-git-directory", "MEDIUM", "Package contains a .git directory.", "Package only source files needed by the skill, excluding repository metadata."),
RuleSpec("secret-private-key", "CRITICAL", "Private key material is embedded in skill content.", "Move private keys to a managed secret store and remove them from the skill."),
RuleSpec("secret-cloud-token", "CRITICAL", "High-confidence cloud or API token is embedded in skill content.", "Move tokens to environment variables or a secret store."),
@ -370,19 +374,39 @@ def _scan_file_package_properties(rel_path: str, file_bytes: bytes, file_size: i
def _scan_text_file(rel_path: str, text: str) -> list[SecurityFinding]:
findings: list[SecurityFinding] = []
findings.extend(_scan_secrets(rel_path, text))
# Python accepts a leading UTF-8 BOM in a source file. ast.parse(str)
# expects it to have been consumed by the decoder.
text = text.removeprefix("\ufeff")
named_python = _is_python_path(rel_path, text)
over_python_limit = not named_python and len(text) > _MAX_INFERRED_PYTHON_CHARS
tree = None if over_python_limit else _parse_python(text)
findings = _scan_secrets(rel_path, text, tree, named_python=named_python)
if PurePosixPath(rel_path).name == "SKILL.md":
findings.extend(_scan_declaration(rel_path, text))
if _is_python_path(rel_path, text):
findings.extend(_scan_python(rel_path, text))
if _is_shell_path(rel_path, text):
findings.extend(_scan_shell(rel_path, text))
# A JSON array/object is valid Python syntax too. A literal-only document
# with path or URL labels does not perform a sensitive read or network call.
if tree is not None and (named_python or _has_python_operations(tree)):
findings.extend(_scan_python(rel_path, tree, named_python=named_python))
if over_python_limit:
findings.append(_finding("package-python-analysis-limit", file=rel_path, evidence=f"{len(text)} characters"))
shell_findings = _scan_shell(rel_path, text)
if shell_findings and tree is not None and not _is_shell_path(rel_path, text):
_moderate_quoted_shell_findings(shell_findings, tree)
findings.extend(shell_findings)
findings.extend(_scan_network_and_resource(rel_path, text))
return findings
def _scan_secrets(rel_path: str, text: str) -> list[SecurityFinding]:
def contains_sensitive_package_content(rel_path: str, text: str) -> bool:
"""Keep newly reviewed package data with recognizable secrets local."""
if _is_hidden_sensitive_path(rel_path):
return True
text = text.removeprefix("\ufeff")
tree = _parse_python(text) if len(text) <= _MAX_INFERRED_PYTHON_CHARS else None
return bool(_scan_secrets(rel_path, text, tree, named_python=False))
def _scan_secrets(rel_path: str, text: str, python_tree: ast.Module | None, *, named_python: bool) -> list[SecurityFinding]:
findings: list[SecurityFinding] = []
private_key = re.search(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----", text)
if private_key:
@ -398,11 +422,11 @@ def _scan_secrets(rel_path: str, text: str) -> list[SecurityFinding]:
continue
break
if _is_python_path(rel_path, text):
findings.extend(_scan_python_secret_assignments(rel_path, text))
return findings
findings.extend(_scan_secret_assignments_by_text(rel_path, text))
if python_tree is None or not named_python:
text_bindings = _scan_secret_assignments_by_text(rel_path, text)
if text_bindings or python_tree is None:
return [*findings, *text_bindings]
findings.extend(_scan_python_secret_assignments(rel_path, python_tree, data_text=None if named_python else text))
return findings
@ -659,7 +683,7 @@ def _python_secret_literal_candidates(expr: ast.expr) -> list[tuple[ast.expr, st
return candidates
def _scan_python_secret_assignments(rel_path: str, text: str) -> list[SecurityFinding]:
def _scan_python_secret_assignments(rel_path: str, tree: ast.Module, *, data_text: str | None) -> list[SecurityFinding]:
"""Report embedded Python secrets from real literal bindings, not from raw text.
A line-oriented sweep cannot tell an annotation (``token: Optional[str]``), a
@ -680,14 +704,21 @@ def _scan_python_secret_assignments(rel_path: str, text: str) -> list[SecurityFi
separates from its name (``[token, version] = ["…", 2]``): those two shapes are
reported while the file parses and go quiet once it carries a syntax error.
"""
try:
tree = ast.parse(text)
except SyntaxError:
return _scan_secret_assignments_by_text(rel_path, text)
source: bytes | None = None
line_starts: list[int] = []
for name, value in _python_secret_bindings(tree):
if not _SECRET_ASSIGNMENT_NAME_RE.match(name or ""):
continue
if data_text is not None and (name or "").lower() == "tokens" and value is not None:
# Preserve the text format's usage-counter exemption when the data
# also parses as Python. AST column offsets count UTF-8 bytes.
if source is None:
source = data_text.replace("\r\n", "\n").replace("\r", "\n").encode()
line_starts = [0, *(match.end() for match in re.finditer(b"\n", source))]
start = line_starts[value.lineno - 1] + value.col_offset
sample = "tokens=" + source[start : start + 512].decode("utf-8", errors="ignore")
if (match := _SECRET_ASSIGNMENT_RE.match(sample)) and _is_token_usage_measurement(sample, match):
continue
for node, literal in _python_secret_literal_candidates(value):
if _looks_like_placeholder(literal):
continue
@ -717,12 +748,38 @@ def _scan_declaration(rel_path: str, text: str) -> list[SecurityFinding]:
return findings
def _scan_python(rel_path: str, text: str) -> list[SecurityFinding]:
findings: list[SecurityFinding] = []
def _parse_python(text: str) -> ast.Module | None:
try:
tree = ast.parse(text)
return ast.parse(text)
except SyntaxError:
return findings
return None
def _has_python_operations(tree: ast.Module) -> bool:
return any(not isinstance(statement, ast.Expr) for statement in tree.body) or any(isinstance(node, (ast.Call, ast.Attribute)) for node in ast.walk(tree))
def _inferred_sensitive_file_read(node: ast.Call, call_name: str, aliases: dict[str, str]) -> bool:
"""Recognize literal operands of file reads in text that only resembles Python."""
mode: ast.expr | None = None
if call_name in {"open", "builtins.open", "io.open"}:
path = node.args[0] if node.args else next((kw.value for kw in node.keywords if kw.arg == "file"), None)
mode = node.args[1] if len(node.args) > 1 else next((kw.value for kw in node.keywords if kw.arg == "mode"), None)
elif isinstance(node.func, ast.Attribute) and node.func.attr in {"read_text", "read_bytes", "open"}:
path = node.func.value
if node.func.attr == "open":
mode = node.args[0] if node.args else next((kw.value for kw in node.keywords if kw.arg == "mode"), None)
else:
return False
if mode is not None and not (isinstance(mode, ast.Constant) and isinstance(mode.value, str) and ("r" in mode.value or "+" in mode.value)):
return False
if isinstance(path, ast.Call) and _python_call_name(path, aliases) == "pathlib.Path":
return any(isinstance(arg, ast.Constant) and isinstance(arg.value, str) and _SENSITIVE_PATH_RE.search(arg.value) for arg in path.args)
return isinstance(path, ast.Constant) and isinstance(path.value, str) and bool(_SENSITIVE_PATH_RE.search(path.value))
def _scan_python(rel_path: str, tree: ast.Module, *, named_python: bool) -> list[SecurityFinding]:
findings: list[SecurityFinding] = []
aliases = _collect_python_aliases(tree)
has_sensitive_read = False
@ -731,17 +788,21 @@ def _scan_python(rel_path: str, text: str) -> list[SecurityFinding]:
sensitive_node: ast.AST | None = None
env_node: ast.AST | None = None
network_node: ast.AST | None = None
# The environment-dump rule retains its established URL/constructor signals.
env_network_hint: ast.AST | None = None
reverse_shell_parts: set[str] = set()
reverse_shell_node: ast.AST | None = None
for node in ast.walk(tree):
if isinstance(node, ast.Constant) and isinstance(node.value, str):
if _SENSITIVE_PATH_RE.search(node.value):
if named_python and _SENSITIVE_PATH_RE.search(node.value):
has_sensitive_read = True
sensitive_node = sensitive_node or node
if _is_outbound_url(node.value):
has_network_sink = True
network_node = network_node or node
env_network_hint = env_network_hint or node
if named_python:
has_network_sink = True
network_node = network_node or node
if isinstance(node, (ast.Attribute, ast.Name)) and _python_name(node, aliases) == "os.environ":
has_env_dump = True
@ -763,9 +824,15 @@ def _scan_python(rel_path: str, text: str) -> list[SecurityFinding]:
elif call_name in {"pickle.load", "pickle.loads"} or (call_name == "yaml.load" and not _yaml_load_uses_safe_loader(node)):
findings.append(_finding_for_node("python-unsafe-deserialization", rel_path, node, call_name))
if _call_is_network_sink(call_name):
if not named_python and _inferred_sensitive_file_read(node, call_name, aliases):
has_sensitive_read = True
sensitive_node = sensitive_node or node
if _call_is_network_sink(call_name) and (named_python or call_name != "socket.socket"):
has_network_sink = True
network_node = network_node or node
elif call_name == "socket.socket":
env_network_hint = env_network_hint or node
if call_name == "os.dup2":
reverse_shell_parts.add("dup2")
@ -792,8 +859,8 @@ def _scan_python(rel_path: str, text: str) -> list[SecurityFinding]:
findings.append(_finding_for_node("python-sensitive-exfil", rel_path, sensitive_node or network_node, "sensitive read + network sink"))
elif has_sensitive_read:
findings.append(_finding_for_node("python-sensitive-path-read", rel_path, sensitive_node, "sensitive path read"))
if has_env_dump and has_network_sink:
findings.append(_finding_for_node("python-env-dump-exfil", rel_path, env_node or network_node, "environment dump + network sink"))
if has_env_dump and (has_network_sink or env_network_hint):
findings.append(_finding_for_node("python-env-dump-exfil", rel_path, env_node or network_node or env_network_hint, "environment dump + network sink"))
return findings
@ -1230,9 +1297,73 @@ def _scan_shell(rel_path: str, text: str) -> list[SecurityFinding]:
continue
findings.append(_finding("shell-env-dump", file=rel_path, line=_line_number(code, match.start("cmd")), evidence=command))
break
# The original shell rules also flag prose mentions. Preserve those signals
# for contextual review; reserve blocking inferred files for command use.
criticals = [finding for finding in findings if finding["severity"] == "CRITICAL"]
if criticals and not _is_shell_path(rel_path, text):
confirmed = _inferred_shell_critical_evidence(code)
for finding in criticals:
if command := confirmed.get(finding["rule_id"]):
finding["line"], finding["evidence"] = command
else:
finding["severity"] = "HIGH"
return findings
def _inferred_shell_critical_evidence(code: str) -> dict[str, tuple[int, str]]:
"""Corroborate raw path/tool matches with shell operators or command arguments."""
evidence: dict[str, tuple[int, str]] = {}
sensitive_path: tuple[int, str] | None = None
transfer_command = False
transfers = {"curl", "wget", "nc", "scp"}
path_commands = transfers | {"test", "[", "[[", "cat", "head", "tail", "grep", "awk", "sed", "cut", "read", "tee"}
markers = ("/dev/tcp/", "/etc/passwd", "/etc/shadow", *transfers)
for number, line in enumerate(code.split("\n"), 1):
if not any(marker in line for marker in markers):
continue
for tokens in _inferred_shell_commands(line):
words = [token for token in tokens if isinstance(token, _ShellWord)]
head = next((i for i, word in enumerate(words) if word not in {"!", "if", "then", "elif", "else", "while", "until", "do", "command", "exec", "env", "sudo"} and not re.match(r"[A-Za-z_]\w*=", word)), None)
name = PurePosixPath(words[head]).name if head is not None else ""
if name == "nc" and "-e" in words[head + 1 :]:
evidence.setdefault("shell-reverse-shell", (number, "nc -e"))
transfer_command |= name in transfers
for index, token in enumerate(tokens):
redirected = index > 0 and not isinstance(tokens[index - 1], _ShellWord) and _ENV_REDIRECTION_RE.fullmatch(tokens[index - 1]) is not None
if not redirected and name not in path_commands:
continue
if token.startswith("/dev/tcp/"):
evidence.setdefault("shell-reverse-shell", (number, "/dev/tcp/"))
if token.removeprefix("@") in {"/etc/passwd", "/etc/shadow"}:
sensitive_path = sensitive_path or (number, "/etc")
if transfer_command and sensitive_path:
evidence["shell-sensitive-exfil"] = sensitive_path
return evidence
def _inferred_shell_commands(line: str) -> Iterable[list[str]]:
# A backtick-delimited mention in ordinary Markdown is not a command
# boundary. The original raw finding remains available for model review.
line = line.replace("`", '"')
start = 0
while start < len(line):
budget = _ShellTokenBudget(len(line) - start)
tokens = _tokenize_shell(line, start, budget=budget)
if tokens:
yield tokens
# The tokenizer stops at the next unquoted command separator.
start = len(line) - budget.remaining + 1
def _moderate_quoted_shell_findings(findings: list[SecurityFinding], tree: ast.Module) -> None:
"""Send a shell idiom quoted as data to contextual review at warning severity."""
for finding in findings:
if finding["severity"] != "CRITICAL" or not (line_number := finding["line"]) or not (evidence := finding["evidence"]):
continue
if any(isinstance(node, ast.Constant) and isinstance(node.value, str) and node.lineno <= line_number <= (node.end_lineno or node.lineno) and evidence in node.value for node in ast.walk(tree)):
finding["severity"] = "HIGH"
def _scan_network_and_resource(rel_path: str, text: str) -> list[SecurityFinding]:
findings: list[SecurityFinding] = []
if match := re.search(r"(169\.254\.169\.254|metadata\.google\.internal)", text, re.IGNORECASE):
@ -1590,6 +1721,7 @@ class _ClientSpec:
# Keep response-only operations such as `getresponse()` out: this signal needs outbound I/O.
_PYTHON_CLIENT_SPECS = {
"socket.socket": _ClientSpec(frozenset({"connect", "connect_ex", "send", "sendall", "sendto", "sendmsg", "sendfile"}), sync_context=True),
"http.client.HTTPConnection": _ClientSpec(frozenset({"request", "connect", "send"})),
"http.client.HTTPSConnection": _ClientSpec(frozenset({"request", "connect", "send"})),
"requests.Session": _ClientSpec(frozenset({"request", "get", "post", "put", "patch", "delete", "head", "options", "send"}), sync_context=True),

View File

@ -45,12 +45,14 @@ Drives the full install pipeline under the Blockbuster gate.
"""
_SUPPORT_MD = "Reference notes scanned by the per-file security pass.\n"
_CALCULATION = "total = 2 + 3\n"
def _build_archive(archive: Path) -> None:
with zipfile.ZipFile(archive, "w") as zf:
zf.writestr("loop-skill/SKILL.md", _SKILL_MD)
zf.writestr("loop-skill/references/usage.md", _SUPPORT_MD)
zf.writestr("loop-skill/data/calculation.dat", _CALCULATION)
async def test_install_skill_archive_does_not_block_event_loop(tmp_path: Path, monkeypatch) -> None:
@ -89,8 +91,10 @@ async def test_user_scoped_install_skill_archive_does_not_block_event_loop(tmp_p
archive = tmp_path / "loop-skill.skill"
await asyncio.to_thread(_build_archive, archive)
reviewed = []
async def _allow_scan(content: str, *, executable: bool = False, location: str = "SKILL.md", app_config=None, static_findings=None):
reviewed.append((location, executable, content))
return SimpleNamespace(decision="allow", reason="anchor stub")
monkeypatch.setattr("deerflow.skills.installer.scan_skill_content", _allow_scan)
@ -104,6 +108,7 @@ async def test_user_scoped_install_skill_archive_does_not_block_event_loop(tmp_p
result = await storage.ainstall_skill_from_archive(archive)
assert result["success"] is True
assert ("loop-skill/data/calculation.dat", True, _CALCULATION) in reviewed
assert result["skill_name"] == "loop-skill"
installed_md = tmp_path / "users" / "anchoruser" / "skills" / "custom" / "loop-skill" / "SKILL.md"
assert await asyncio.to_thread(installed_md.is_file)

View File

@ -40,12 +40,13 @@ async def test_host_scan_covers_support_files_and_forces_fail_closed(monkeypatch
@pytest.mark.asyncio
async def test_static_block_prevents_model_scan(monkeypatch):
@pytest.mark.parametrize(("path", "executable"), [("scripts/run.py", True), ("data/calculation.dat", False)])
async def test_static_block_prevents_model_scan(monkeypatch, path, executable):
from deerflow.skills.mutations.scanner import CandidateScanner
model = AsyncMock(return_value=ScanResult("allow", "fine"))
monkeypatch.setattr("deerflow.skills.mutations.scanner.scan_skill_content", model)
package = PackageSnapshot((PackageFile("SKILL.md", CONTENT, False), PackageFile("scripts/run.py", b"eval(input())", True)))
package = PackageSnapshot((PackageFile("SKILL.md", CONTENT, False), PackageFile(path, b'eval("1 + 2")', executable)))
result = await CandidateScanner(configuration).scan(package, "example")
assert result.decision == "reject"
model.assert_not_called()

View File

@ -6,6 +6,7 @@ import stat
import threading
import zipfile
from pathlib import Path
from types import SimpleNamespace
import pytest
@ -20,6 +21,7 @@ from deerflow.skills.installer import (
from deerflow.skills.security_scanner import ScanResult
from deerflow.skills.security_static_scanner import StaticScannerError
from deerflow.skills.storage import get_or_new_skill_storage
from deerflow.skills.storage.local_skill_storage import LocalSkillStorage
# ---------------------------------------------------------------------------
# is_unsafe_zip_member
@ -373,6 +375,13 @@ class TestSafeExtract:
# ---------------------------------------------------------------------------
def _make_storage(skills_root: Path, *, skill_scan_enabled: bool) -> LocalSkillStorage:
return LocalSkillStorage(
host_path=str(skills_root),
app_config=SimpleNamespace(skill_scan=SimpleNamespace(enabled=skill_scan_enabled)),
)
class TestEntryCountCapAppliesRegardlessOfSkillScan:
@pytest.fixture(autouse=True)
def _allow_security_scan(self, monkeypatch):
@ -381,16 +390,6 @@ class TestEntryCountCapAppliesRegardlessOfSkillScan:
monkeypatch.setattr("deerflow.skills.installer.scan_skill_content", _scan)
def _make_storage(self, skills_root: Path, *, skill_scan_enabled: bool):
from types import SimpleNamespace
from deerflow.skills.storage.local_skill_storage import LocalSkillStorage
return LocalSkillStorage(
host_path=str(skills_root),
app_config=SimpleNamespace(skill_scan=SimpleNamespace(enabled=skill_scan_enabled)),
)
def _make_many_entry_zip(self, tmp_path: Path, *, entry_count: int, skill_name: str = "test-skill") -> Path:
"""A real archive with ``entry_count`` tiny members and a small total size —
matches the reported shape (50,000 entries, ~5MB total)."""
@ -408,7 +407,7 @@ class TestEntryCountCapAppliesRegardlessOfSkillScan:
zip_path = self._make_many_entry_zip(tmp_path, entry_count=50_000)
skills_root = tmp_path / "skills"
skills_root.mkdir()
storage = self._make_storage(skills_root, skill_scan_enabled=False)
storage = _make_storage(skills_root, skill_scan_enabled=False)
with pytest.raises(ValueError, match="too many entries"):
storage.install_skill_from_archive(zip_path)
@ -432,7 +431,7 @@ class TestEntryCountCapAppliesRegardlessOfSkillScan:
zip_path = self._make_many_entry_zip(tmp_path, entry_count=5, skill_name="small-skill")
skills_root = tmp_path / "skills"
skills_root.mkdir()
storage = self._make_storage(skills_root, skill_scan_enabled=False)
storage = _make_storage(skills_root, skill_scan_enabled=False)
result = storage.install_skill_from_archive(zip_path)
@ -576,8 +575,7 @@ class TestInstallSkillFromArchive:
zf.writestr("test-skill/templates/prompt.txt", "Use care.\n")
zf.writestr("test-skill/scripts/run.sh", "#!/bin/sh\necho ok\n")
zf.writestr("test-skill/assets/logo.png", b"\x89PNG\r\n\x1a\n")
zf.writestr("test-skill/references/.env", "TOKEN=secret\n")
zf.writestr("test-skill/templates/config.cfg", "TOKEN=secret\n")
zf.writestr("test-skill/templates/config.cfg", "format = plain\n")
skills_root = tmp_path / "skills"
skills_root.mkdir()
calls = []
@ -606,13 +604,39 @@ class TestInstallSkillFromArchive:
"executable": True,
"location": "test-skill/scripts/run.sh",
},
{
"content": "format = plain\n",
"executable": True,
"location": "test-skill/templates/config.cfg",
},
{
"content": "Use care.\n",
"executable": False,
"location": "test-skill/templates/prompt.txt",
},
]
assert all("secret" not in call["content"] for call in calls)
@pytest.mark.parametrize("static_enabled", [True, False])
@pytest.mark.parametrize(("rel_path", "value"), [("references/.env", "MODE=demo\n"), ("templates/config.cfg", "TOKEN=secret\n")])
def test_sensitive_additional_files_stay_local(self, tmp_path, monkeypatch, rel_path, value, static_enabled):
zip_path = self._make_skill_zip(tmp_path)
with zipfile.ZipFile(zip_path, "a") as zf:
zf.writestr(f"test-skill/{rel_path}", value)
calls = []
async def _scan(content, **kwargs):
calls.append(content)
return ScanResult(decision="allow", reason="ok")
monkeypatch.setattr("deerflow.skills.installer.scan_skill_content", _scan)
skills_root = tmp_path / "skills"
storage = _make_storage(skills_root, skill_scan_enabled=static_enabled)
with pytest.raises(SkillSecurityScanError, match="sensitive configuration") as error:
storage.install_skill_from_archive(zip_path)
assert value not in str(error.value)
assert value not in calls
assert not (skills_root / "custom" / "test-skill").exists()
def test_scans_code_files_anywhere_in_tree(self, tmp_path, monkeypatch):
zip_path = tmp_path / "test-skill.skill"
@ -640,7 +664,81 @@ class TestInstallSkillFromArchive:
assert {"executable": True, "location": "test-skill/bin/tool"} in calls
scanned_locations = {call["location"] for call in calls}
assert "test-skill/assets/logo.png" not in scanned_locations
assert "test-skill/assets/data.txt" not in scanned_locations
assert {"executable": True, "location": "test-skill/assets/data.txt"} in calls
@pytest.mark.parametrize("rel_path", ["data/helper.dat", "assets/helper"])
@pytest.mark.parametrize("static_enabled", [True, False])
def test_review_of_unmarked_text_can_stop_install(self, tmp_path, monkeypatch, rel_path, static_enabled):
zip_path = self._make_skill_zip(tmp_path)
marker = "print('review marker')\n"
with zipfile.ZipFile(zip_path, "a") as zf:
zf.writestr(f"test-skill/{rel_path}", marker)
reviewed = []
async def _scan(content, *, location, executable, **kwargs):
reviewed.append((location, content, executable))
return ScanResult(decision="warn" if content == marker else "allow", reason="fixture decision")
monkeypatch.setattr("deerflow.skills.installer.scan_skill_content", _scan)
skills_root = tmp_path / "skills"
storage = _make_storage(skills_root, skill_scan_enabled=static_enabled)
with pytest.raises(SkillSecurityScanError, match="fixture decision"):
storage.install_skill_from_archive(zip_path)
assert (f"test-skill/{rel_path}", marker, True) in reviewed
assert not (skills_root / "custom" / "test-skill").exists()
@pytest.mark.parametrize(
("limit", "cap", "contents"),
[("MAX_MODEL_FILE_BYTES", 3, ["abcd"]), ("MAX_MODEL_BYTES", 3, ["ab", "cd"]), ("MAX_MODEL_FILES", 1, ["a", "b"])],
)
def test_additional_text_over_review_limits_prevents_model_calls_and_install(self, tmp_path, monkeypatch, limit, cap, contents):
import deerflow.skills.installer as installer
monkeypatch.setattr(installer, limit, cap)
reviewed = []
async def _scan(content, *, location, **kwargs):
reviewed.append(location)
return ScanResult(decision="allow", reason="fixture decision")
monkeypatch.setattr(installer, "scan_skill_content", _scan)
zip_path = self._make_skill_zip(tmp_path)
with zipfile.ZipFile(zip_path, "a") as zf:
zf.writestr("test-skill/a.py", "print('ready')\n")
for index, content in enumerate(contents):
zf.writestr(f"test-skill/data/{index}.dat", content)
skills_root = tmp_path / "skills"
with pytest.raises(SkillSecurityScanError, match="additional text"):
get_or_new_skill_storage(skills_path=skills_root).install_skill_from_archive(zip_path)
assert reviewed == []
assert not (skills_root / "custom" / "test-skill").exists()
@pytest.mark.parametrize("ending", [b"\x00", b"\xff", b"\xc3"], ids=["nul", "invalid-utf8", "truncated-utf8"])
def test_binary_asset_with_text_prefix_does_not_consume_text_budget(self, tmp_path, monkeypatch, ending):
import deerflow.skills.installer as installer
monkeypatch.setattr(installer, "MAX_MODEL_FILE_BYTES", 2)
monkeypatch.setattr(installer, "MAX_MODEL_BYTES", 2)
monkeypatch.setattr(installer, "MAX_MODEL_FILES", 1)
zip_path = self._make_skill_zip(tmp_path)
with zipfile.ZipFile(zip_path, "a") as zf:
zf.writestr("test-skill/data/asset", b"asset" + b" " * 65536 + ending)
zf.writestr("test-skill/data/letter", "é")
reviewed = []
async def _scan(content, *, location, **kwargs):
reviewed.append((location, content))
return ScanResult(decision="allow", reason="fixture decision")
monkeypatch.setattr(installer, "scan_skill_content", _scan)
skills_root = tmp_path / "skills"
get_or_new_skill_storage(skills_path=skills_root).install_skill_from_archive(zip_path)
assert reviewed[1:] == [("test-skill/data/letter", "é")]
assert (skills_root / "custom/test-skill/data/asset").is_file()
def test_shebang_sniff_only_reads_extensionless_files(self, tmp_path, monkeypatch):
"""Suffix/scripts classification is name-based; only extensionless files are opened."""

View File

@ -698,6 +698,47 @@ def test_secret_cloud_token_matches_canonical_token_families(tmp_path: Path, tok
assert token not in (finding["evidence"] or "")
@pytest.mark.parametrize("filename", ["references/shell.md", "references/notes.dat"])
def test_plain_shell_documentation_reaches_contextual_review(tmp_path: Path, filename: str) -> None:
path = tmp_path / filename
path.parent.mkdir()
path.write_bytes(b"Bash documents the virtual path `/dev/tcp/` and the spelling nc -e.\nThe glossary also lists /etc/passwd and curl.\n")
result = scan_skill_dir(tmp_path)
assert result["scanner_errors"] == []
assert result["blocked"] is False
assert {(item["rule_id"], item["severity"]) for item in result["findings"]} == {("shell-reverse-shell", "HIGH"), ("shell-sensitive-exfil", "HIGH")}
@pytest.mark.parametrize("filename", ["check.md", "check.dat", "check"])
def test_inferred_shell_command_after_prose_still_blocks(tmp_path: Path, filename: str) -> None:
path = tmp_path / filename
path.write_bytes(b"# Bash documents the virtual path /dev/tcp/.\ntest -d /dev/tcp/\n")
result = scan_skill_dir(tmp_path)
assert result["scanner_errors"] == []
finding = _finding_by_rule(result["findings"], "shell-reverse-shell")
assert (finding["file"], finding["line"], finding["severity"]) == (filename, 2, "CRITICAL")
assert result["blocked"] is True
def test_inferred_shell_critical_evidence_uses_operators_and_file_operands(tmp_path: Path) -> None:
(tmp_path / "redirect.dat").write_bytes(b"if false; then : </dev/tcp/; fi\n")
(tmp_path / "check.dat").write_bytes(b"test -f /etc/passwd && curl --version\n")
(tmp_path / "notes.txt").write_bytes(b"See /etc/passwd in the glossary.\ncurl --version\n")
result = scan_skill_dir(tmp_path)
assert result["scanner_errors"] == []
assert [(item["file"], item["rule_id"], item["severity"]) for item in result["findings"]] == [
("check.dat", "shell-sensitive-exfil", "CRITICAL"),
("notes.txt", "shell-sensitive-exfil", "HIGH"),
("redirect.dat", "shell-reverse-shell", "CRITICAL"),
]
def test_shell_weak_reverse_shell_idioms_warn_not_block(tmp_path: Path) -> None:
skill_dir = tmp_path / "demo-skill"
_write_skill(skill_dir)
@ -742,6 +783,86 @@ def test_zsh_script_without_shebang_is_scanned_as_shell(tmp_path: Path) -> None:
assert result["blocked"] is True
@pytest.mark.parametrize("filename", ["helper.dat", "helper"])
@pytest.mark.parametrize(
("source", "rule_id", "severity"),
[
('compile("1 + 1", "<fixture>", "exec")\n', "python-dynamic-exec", "CRITICAL"),
('\ufeffcompile("1 + 1", "<fixture>", "exec")\n', "python-dynamic-exec", "CRITICAL"),
('from os import environ\nlabel = "https://example.invalid/"\nvariables = environ\n', "python-env-dump-exfil", "CRITICAL"),
("printenv DEERFLOW_TEST_MARKER\n", "shell-env-dump", "MEDIUM"),
("MARKER=sample printenv DEERFLOW_TEST_MARKER\n", "shell-env-dump", "MEDIUM"),
],
)
def test_native_analyzers_cover_text_without_script_names(tmp_path: Path, filename: str, source: str, rule_id: str, severity: str) -> None:
skill_dir = tmp_path / "demo-skill"
_write_skill(skill_dir)
data = skill_dir / "data"
data.mkdir()
(data / filename).write_text(source, encoding="utf-8", newline="\n")
(data / "labels.dat").write_bytes(b"red,green,blue\n")
(data / "notes.md").write_bytes(b"To display a single variable, use printenv DEERFLOW_TEST_MARKER.\n")
(data / "messages.py").write_bytes(b'note = "Use printenv for one named variable."\n')
result = scan_skill_dir(skill_dir)
assert result["scanner_errors"] == []
assert [(finding["file"], finding["rule_id"], finding["severity"]) for finding in result["findings"]] == [(f"data/{filename}", rule_id, severity)]
assert result["blocked"] == (severity == "CRITICAL")
def test_inferred_languages_distinguish_data_from_shell_commands(tmp_path: Path) -> None:
(tmp_path / "labels.json").write_bytes(b'["/etc/passwd", "https://example.invalid/", true]\n')
(tmp_path / "notes.dat").write_bytes(b'note = "Bash documents /dev/tcp/ paths."\n')
(tmp_path / "check.dat").write_bytes(b"test -d /dev/tcp/\n")
result = scan_skill_dir(tmp_path)
assert result["scanner_errors"] == []
assert [(item["file"], item["rule_id"], item["severity"]) for item in result["findings"]] == [
("check.dat", "shell-reverse-shell", "CRITICAL"),
("notes.dat", "shell-reverse-shell", "HIGH"),
]
@pytest.mark.parametrize(
("filename", "extra", "expected_rule"),
[
("settings.toml", "", None),
("settings.toml", "print(reference, help_url)", None),
("helper.dat", "open('fixtures/etc/passwd').close()", "python-sensitive-path-read"),
("helper.dat", "import requests\nrequests.head(help_url)", None),
("helper.dat", "open('fixtures/etc/passwd').close()\nimport requests\nrequests.head(help_url)", "python-sensitive-exfil"),
("helper.dat", "open('fixtures/etc/passwd').close()\nimport socket\ns = socket.socket()", "python-sensitive-path-read"),
("helper.dat", "open('fixtures/etc/passwd').close()\nimport socket\ns = socket.socket()\ns.connect(('localhost', 0))", "python-sensitive-exfil"),
("helper.dat", "open('README.md').close()\nimport requests\nrequests.head(help_url)", None),
("helper.dat", "open(file='fixtures/etc/passwd', mode='x').close()\nimport requests\nrequests.head(help_url)", None),
("helper.dat", "from pathlib import Path as P\nP('fixtures/etc/passwd').read_text()", "python-sensitive-path-read"),
("settings.py", "", "python-sensitive-exfil"),
],
)
def test_inferred_python_requires_io_for_sensitive_exfil(tmp_path: Path, filename: str, extra: str, expected_rule: str | None) -> None:
# Only parse these fixtures. The I/O expressions are never evaluated.
source = 'reference = "fixtures/etc/passwd"\nhelp_url = "https://docs.example.invalid/"\n' + extra
(tmp_path / filename).write_text(source, encoding="utf-8", newline="\n")
result = scan_skill_dir(tmp_path)
assert result["scanner_errors"] == []
assert [finding["rule_id"] for finding in result["findings"] if finding["rule_id"].startswith("python-sensitive-")] == ([expected_rule] if expected_rule else [])
assert result["blocked"] == (expected_rule == "python-sensitive-exfil")
def test_inferred_python_analysis_reports_its_budget(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("deerflow.skills.skillscan.orchestrator._MAX_INFERRED_PYTHON_CHARS", 32)
(tmp_path / "helper.dat").write_bytes(b"# sample\n" * 8 + b"printenv DEERFLOW_TEST_MARKER\n")
result = scan_skill_dir(tmp_path)
assert result["scanner_errors"] == []
assert {item["rule_id"] for item in result["findings"]} == {"package-python-analysis-limit", "shell-env-dump"}
@pytest.mark.parametrize(
("rel_path", "script_bytes", "rule_id", "evidence"),
[

View File

@ -418,6 +418,16 @@ If a trusted operator manages the configured skills directory through an externa
Skill installs and agent-managed skill edits run through **SkillScan**, a native deterministic safety scanner before the LLM-based skill scanner. Phase 1 runs offline with no Semgrep/OpenGrep dependency, blocks high-confidence `CRITICAL` findings such as private keys or shell execution, and passes warning findings to the LLM scanner for contextual review. Code files (anything under `scripts/`, a script suffix such as `.py`, `.sh`, or `.js`, or an extensionless file starting with `#!`) that are not NUL-free UTF-8 text raise a warning and are still analyzed over a lossy decode, so a single stray byte cannot hide them from `CRITICAL` checks. The moderation adapter normalizes both plain-text model responses and LangChain Responses API text blocks before parsing the required JSON decision. Python instance-client exfiltration checks follow a minimal same-scope evidence chain: a simple name bound to a known client constructor, optional name-to-name aliases, and an actual outbound method or context-manager use supported by that constructor. Constructor roots must be proven imports; bare canonical-looking names are not inferred as modules. Nested scopes do not inherit client handles and inherit only constructor import aliases that are never rebound in the enclosing scope. Comprehensions, walrus-bearing statements, annotations, complex binding targets, unsupported operations, and ambiguous branch flows produce no finding from this signal; skipped constructs conservatively invalidate every name they may bind so stale client state cannot create a finding. A deterministic work budget or recursion limit reached by this best-effort analysis does not discard findings already collected for the file. Set `skill_scan.enabled: false` in `config.yaml` to disable only the deterministic analyzers; safe archive extraction and the LLM scanner still run.
Windows scripts (`.bat`, `.cmd`, `.ps1`, `.psm1`, `.js`, `.jse`, `.vbs`, `.vbe`, `.wsf`), HTML applications (`.hta`), and scriptlets (`.sct`) count as code even outside `scripts/`, regardless of filename case. They receive both SkillScan analysis and the installer's executable-code policy.
SkillScan also inspects text for Python and shell code when the file has an unfamiliar name or no shebang.
Shell terminology in a reference document can go to the model for contextual review. A critical shell finding in inferred code needs command evidence.
For inferred Python, the sensitive-read and network rule requires evidence of a file read and an outbound network operation. Configuration values can contain a path and a help URL without triggering this rule.
For text over 131,072 characters without a Python filename or shebang, it reports a Python analysis limit and continues the other checks.
During archive installation, NUL-free UTF-8 files outside the usual script and prompt paths go to the configured review model and require an explicit `allow`.
The installer rejects additional files containing recognized credentials or sensitive configuration before sending their contents to the model.
Before the first model call, the installer checks that each additional text file is at most 128 KiB and that the package contains at most 32 of these files totaling at most 1 MiB. Exceeding any limit stops installation.
These model-review safeguards also apply when `skill_scan.enabled` is false.
SkillScan warns about remote downloads piped into common shells, including `env` launchers, sudo, interpreter paths, and shell line continuations. It distinguishes environment dumps from `env` commands, including assignments and GNU split-string escapes. Shell parsing and split expansion are bounded; reaching a limit preserves critical findings already detected. Pipes to non-shell tools such as `jq` and `tee` do not trigger this warning.
SkillScan treats HTTP/HTTPS scheme spellings and HTTP hostnames case-insensitively and recognizes bracketed IPv6