Skip to content

Add a CI gate for code shapes that heuristic antivirus scanners quarantine - #12178

Merged
danielhanchen merged 9 commits into
mainfrom
av-shape-lint
Sep 28, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
av-shape-lint

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

Summary

Every recent antivirus false positive on Unsloth came from our own repository content, and the existing guard (tests/studio/test_installer_av_shapes.py) only reads the seven shipped installer files. This adds a repo-wide, deterministic lint that fails a PR which introduces a code shape heuristic scanners are known to quarantine, and tells the author why and what to write instead.

Incident Where Shape Rule
Bitdefender CMD:Heur.BZC.PZQ.Boxter tests/python/test_windows_setup_output_encoding.py a written .ps1 declaring a kernel32 import AV001
Bitdefender Generic.PY.STEALER scripts/scan_packages.py credential-store paths beside env and network code AV008
Skyhigh install.ps1 (before #11193) reflection emit AV003
renamed system binary 9979, signing and concurrency tests System32\where.exe / PING.EXE copied under another name AV009
"Unsupported 16-Bit Application" dialog rollback test a text file named .exe that gets started AV010

How it works

scripts/lint_av_shapes.py, standard library only, modelled on scripts/lint_exec_literals.py:

  • Scans every tracked .ps1 .psm1 .psd1 .bat .cmd .sh .py .rs .js .ts .tsx .yml file (vendored bundles excluded). PowerShell embedded in Python, Rust, shell or YAML strings is covered because the rules read raw text, which is also what scanners read.
  • 15 rules. Errors fail the build: native imports in script source, process-memory APIs, reflection emit, encoded payloads, remote text piped into the expression engine, security-product tampering, hidden window plus policy bypass, credential paths beside network code, copied system binaries, living-off-the-land download chains. Warnings are printed and never fail: non-PE .exe writes, persistence, obfuscation, scanner vocabulary in shipped installer comments, [scriptblock]::Create and curl | sh.
  • Each finding prints file:line: [AVnnn] error|warn, the line, why: and fix:. --json writes the same as a report.
  • Existing findings live in scripts/av_shapes_baseline.json, keyed on the matched line's text with a count, so only new occurrences fail and moving code does not churn it. Every error group carries a written reason; a stale entry fails so it cannot silently re-permit a future line.
  • lint-allow: AVnnn <reason> on or above a line excuses it, except in the shipped installers, where only the baseline counts.
  • The trigger tokens are joined from fragments at import time, and the self-test fixtures are built in memory, so neither the lint nor its test carries the shapes it looks for.
  • About 3 s for the whole repository on a 4-core runner (process pool, per-rule substring prefilter).

Wired into Lint CI next to the exec-literals gate: --self-test, then the check.

Fixed instead of baselined

  • tests/studio/test_path_resolver_degrades.ps1 kept a here-string with Add-Type, a dynamic assembly, a P/Invoke stub and a kernel32 import attribute side by side in a .ps1 on disk. The same checks now join those tokens at run time.
  • tests/python/test_windows_installer_concurrency_guard.py copied System32\PING.EXE to guard-probe.exe, worker.exe and unsloth.exe. It now writes a pip-style console launcher (tests/_shared/windows_console_stub.py, which gains a source= argument) that sleeps for the -n seconds ping did.

Validation

  • Self-test: every rule fires on its shape and stays quiet on the rewrite (57 fixtures across 15 rules).
  • History: the lint flags each incident at the commit that shipped it and raises no error on the fixed version (scan_packages.py around 99c392887, install.ps1 around bd612c863, and the test files at 268b771b9). These run in tests/security/test_lint_av_shapes.py and skip only on a shallow clone.
  • Replay of the last 200 commits on main: 4 would have failed. One was a real shape in shipped code (Studio: add Windows MXC Preview sandboxing #11390 launches PowerShell with an encoded command in studio/install_mxc_prebuilt.py), two were tests spelling out the banned tokens (the fix hint now says to join them from fragments), and one was a read of a Defender setting, which the tamper rule no longer matches.
  • Windows x64 and ARM64: the concurrency guard tests with the launcher stand-in, base vs head (results in a comment below).

Follow-ups (baselined with a reason, not changed here)

  • studio/install_mxc_prebuilt.py passes its elevated script as -EncodedCommand.
  • studio/backend/core/inference/tools.py keeps the sandbox's credential-path deny list in the same file as network code (the Generic.PY.STEALER shape), as does scripts/scan_npm_packages.py.
  • install.sh's WSL shortcut helper still emits the SHChangeNotify stub that Remove the reflection-emit apparatus and all four emitted types #11193 removed from install.ps1; the Windows side of a WSL install cannot assume the Python that install.ps1 now uses.

Not covered

The lint pins known shapes; it does not predict a vendor engine's verdict, and it does not follow payloads built dynamically beyond simple concatenation. Binary artifacts stay with virustotal-installer-delta.yml.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-28T08:44:34.896777Z 49e17f5 Manual request
🔒 Security Review ✅ Completed 2026-09-28T07:22:57.483585Z 2cd84e6 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 2cd84e6f96

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…alls, case, UTF-16, quoted forms, baseline counts and severity
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2103f584f6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/lint_av_shapes.py
hit = False
for match in piped.finditer(line):
ours = _FIRST_PARTY.match(match.group(1)) is not None
if not (ours and (quoted_doc or _inside_literal(line, match.start(2)))):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Treat expandable-string subexpressions as executable

Fresh evidence after the quoted-string fix: Write-Host "$(irm https://unsloth.ai/install.ps1 | iex)" still executes the pipeline because PowerShell evaluates $() inside a double-quoted string, but _inside_literal causes this condition to exempt it as documentation. Detect executable subexpressions within expandable strings rather than treating every quoted occurrence as inert.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: a download piped into the engine inside a string subexpression is not something a contributor writes as documentation or code here, and the gate targets the shapes that actually land.

Comment thread scripts/lint_av_shapes.py
Comment on lines +645 to +647
for i, line in enumerate(lines):
if any(p.search(line) for p in patterns):
hits.append((i + 1, rule.severity))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Report patterns that span source lines

This per-line reporting pass discards matches that only exist across line boundaries, even after the whole-file precheck succeeds. For example, legal C# embedded in PowerShell can format a native attribute as [DllImport followed by ("kernel32.dll")] on the next line; AV001's \s* matches that in text, but neither individual line matches, so the known native-import quarantine shape produces no finding.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: a native import attribute split across two lines is unusual formatting; the per-line pass covers every form in the repository and in the incidents it pins.

Comment thread scripts/lint_av_shapes.py
Comment on lines +669 to +671
folded = relative.lower()
if not folded.endswith(SUFFIXES) or folded.endswith(".min.js"):
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scan tracked Dockerfiles for executable shapes

Requiring one of these suffixes silently excludes all four tracked docker/Dockerfile* build recipes, even though they contain executable shell commands; for example, docker/Dockerfile.studio currently contains curl ... | bash. Thus AV015 does not even report that existing shape, and any future AV004/AV005 error shape added to a Docker build also bypasses the advertised repository-wide gate.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: the Dockerfiles build Linux containers and are not the Windows desktop surface these scanners score.

…refilter all wallet paths, and require WindowStyle for a hidden launch
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1a31be13c0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/lint_av_shapes.py
Comment on lines +345 to +349
match = write.search(line)
if not match:
continue
args = match.group("args") if match.group("args") is not None else match.group("ps")
if not literal.search(args) or re.search(r"\bb?['\"]MZ", args):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Inspect literals in multiline executable writes

For a normally formatted call such as (path / "probe.exe").write_bytes( followed by b"not an executable" on the next line, this match captures an empty same-line argument string and skips the write. Even if the file later passes that path to subprocess.run, AV010 therefore emits no warning for the non-PE executable shape that can trigger the modal Windows dialog; inspect the full call or its following argument lines.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: AV010 only warns, and a write split across lines is not how these tests are written; the single-line form covers the incidents.

Comment thread scripts/lint_av_shapes.py
Comment on lines +392 to +395
def _check_vendor_prose(path, lines, text):
prose = re.compile(_VENDOR_PROSE, re.I)
return [
(i + 1, "warn") for i, line in enumerate(lines) if _is_comment(line) and prose.search(line)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Track PowerShell block-comment state when scanning prose

Only the opening <# line of a PowerShell block comment is classified as a comment; ordinary interior lines are not. Therefore scanner vocabulary placed in the comment-based help block already present at the top of studio/setup.ps1, such as an interior line mentioning a quarantine heuristic, receives no AV014 warning even though those comment bytes are exactly what this rule is intended to keep out of shipped installers. Parse <# through #> as comment context rather than checking each line independently.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: AV014 only warns, and the help blocks in the shipped installers are already clean.

…opy aliases, quoted tool paths and shell credential access
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 360011dc13

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

def _write_sleeper(path: Path) -> None:
from windows_console_stub import console_stub_bytes

stub = console_stub_bytes(source = _SLEEPER_SOURCE)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Terminate the interpreter spawned by the launcher

On Windows, the distlib executable created here is a launcher that starts sys.executable as a child and waits for it; the Popen object used by these tests therefore represents the launcher, not the Python process executing _SLEEPER_SOURCE. Each finally block calls child.terminate(), which terminates only that launcher on Windows, leaving the interpreter sleeping for 6–120 seconds after the test; use process-tree/job cleanup or another sleeper whose lifetime is controlled directly.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a leak: the distlib launcher runs its Python child in a job object with kill-on-close (the same design as py.exe), so terminating the launcher ends the sleeper; only grandchildren escape, and the sleeper starts none.

Comment thread scripts/lint_av_shapes.py
Comment on lines +171 to +174
_COPY_CALL = (
r"(?i)(?<![\w.])copy(?:file|2)?\s*\(|shutil\.copy\w*\s*\(|\bCopy-Item\b"
r"|\[(?:System\.)?IO\.File\]::Copy\s*\(|\bCopyFileW?\s*\(|fs::copy\s*\("
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include qualified Node copy APIs in AV009

For tracked JavaScript and TypeScript files, normal Node calls such as fs.copyFileSync("C:\\Windows\\System32\\where.exe", "tool.exe") produce no AV009 finding: the generic copy alternative rejects a preceding dot and does not accept the Sync suffix, while the remaining alternatives only cover Python, PowerShell, Win32, and Rust APIs. This leaves the same renamed-system-binary operation ungated whenever it is implemented with Node's standard qualified file-copy APIs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: no Node code in the repository copies Windows binaries, and the rule targets the shapes that have actually landed.

Comment thread scripts/lint_av_shapes.py
) # fmt: skip
POWERSHELL_LIKE = (".ps1", ".psm1", ".psd1", ".bat", ".cmd")
# Where a PowerShell launch or a Windows process start can be written: not the web frontend.
LAUNCHERS = POWERSHELL_LIKE + (".sh", ".py", ".rs", ".yml", ".yaml")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scan Node process launchers for AV004 and AV007

JavaScript and TypeScript are in the repository scan scope, but excluding all of their suffixes here prevents the hard AV004 and AV007 rules from examining Node launch code. This is not limited to browser code: unsloth_cli/pi_subagent.ts imports node:child_process at line 1 and calls spawn at line 236, yet a call such as spawn("powershell.exe", ["-EncodedCommand", payload]) produces no finding in a .ts, .js, .mjs, or .cjs file while the same text is rejected in Python.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: the Node launch code here does not build PowerShell command lines, and scanning every TS/JS file for window flags would mostly match frontend CSS words.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@shimmyshimmer shimmyshimmer added new-feature# security# Moves a security boundary: sandbox, allowlist, permission or network guard labels Sep 28, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cd5b1707eb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/lint_av_shapes.py
Comment on lines +119 to +123
"Set",
"-Mp",
r"Preference\b[^\n]*-Disable\w*(?::\s*\$true|:\s*1\b|(?!\s+\$false)(?:\s+\$true|\s+1\b|\s*$|\s+`))",
),
(r"(?:Add|Set)", "-Mp", r"Preference\b[^\n]*-Exclusion"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Follow continued Set-MpPreference commands

When PowerShell formats a settings change as Set-MpPreference \`` followed by -DisableRealtimeMonitoring $trueor-ExclusionPath ...` on the next line, these patterns cannot match because they require the command and parameter before the same newline. That is conventional PowerShell formatting for a long command, yet it lets the exact Defender-tampering shapes covered by AV006 pass the hard gate; correlate continued command lines before matching the parameters.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: no command in the repository is continued this way, and the single-line form is what lands.

…terpreter, follow one-per-line argv, and refuse --update with --paths
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 49e17f51ca

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit b91172e into main Sep 28, 2026
36 of 41 checks passed
@danielhanchen
danielhanchen deleted the av-shape-lint branch September 28, 2026 08:48
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…ntine (unslothai#12178)

* Add a repo-wide gate for code shapes heuristic scanners quarantine

* Stand in for PING.EXE with the console launcher in the concurrency guard tests

* Close the gaps review found: executed first-party pipes, split copy calls, case, UTF-16, quoted forms, baseline counts and severity

* Match every encoded-command prefix and Set-MpPreference exclusions, prefilter all wallet paths, and require WindowStyle for a hidden launch

* Trim comments

* Match options before the pipe, colon-bound launch flags, PowerShell copy aliases, quoted tool paths and shell credential access

* Search the shell download pattern line by line

* Count distinct credential paths, fail base64 only when it feeds an interpreter, follow one-per-line argv, and refuse --update with --paths
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

new-feature# security# Moves a security boundary: sandbox, allowlist, permission or network guard

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants