Skip to content

Защита Tools/gen.bat от инъекции метасимволов cmd.exe - #135

Closed
SashaRX wants to merge 1 commit into
mainfrom
codex/fix-command-injection-in-gen.bat
Closed

Защита Tools/gen.bat от инъекции метасимволов cmd.exe#135
SashaRX wants to merge 1 commit into
mainfrom
codex/fix-command-injection-in-gen.bat

Conversation

@SashaRX

@SashaRX SashaRX commented Aug 6, 2026

Copy link
Copy Markdown
Owner

Motivation

  • Исправить уязвимость в Windows-обёртке для build_gallery.py, где незаключённое присваивание и прямая передача %* позволяли метасимволам cmd.exe (например &, |) изменить структуру команд и выполнить произвольные команды локально.
  • Сделать так, чтобы запуск wrapper'а безопасно принимал только поддерживаемые формы аргументов и не повторно интерпретировал исходную командную строку оболочкой.

Description

  • В Tools/gen.bat значение SCRIPT теперь присваивается с кавычками с помощью set "SCRIPT=%~dp0build_gallery.py", чтобы путь не разбивался при наличии метасимволов в каталоге.
  • Диагностический вывод теперь заключает "%SCRIPT%" в кавычки, чтобы диагностическая echo не могла быть использована для инъекции.
  • Убрана небезопасная передача python "%SCRIPT%" %* и реализована явная, безопасная маршрутизация аргументов для поддерживаемых форм: базовый вызов data-folder, опции --out и --gallery-id в любом порядке, их совместное использование и сообщение об ошибке для неподдерживаемых комбинаций; все значения аргументов оборачиваются в кавычки.
  • Добавлено короткое сообщение о корректном использовании при неподдерживаемых или сложных сочетаниях аргументов.

Testing

  • Выполнен скрипт-проверка, подтверждающий наличие set "SCRIPT=%~dp0build_gallery.py", отсутствие python "%SCRIPT%" %*, и присутствие обработок опций --out и --gallery-id, и он завершился успешно.
  • Скомпилирован Tools/build_gallery.py через python -m py_compile, проверка прошла успешно (файл валиден для запуска на Python).
  • Прогнаны git diff --check и git show --check для выявления потенциальных проблем в патче, оба завершились без ошибок.
  • git status показал рабочее дерево в ожидаемом состоянии после изменений.

Codex Task

@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 52 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9236879c-7906-4256-ba5c-4b19de7bef5d

📥 Commits

Reviewing files that changed from the base of the PR and between 21d382e and 81ff18d.

📒 Files selected for processing (1)
  • Tools~/gen.bat

Comment @coderabbitai help to get the list of available commands.

SashaRX commented Aug 6, 2026

Copy link
Copy Markdown
Owner Author

Фикс вошёл в консолидированную ветку claude/security-pr-analysis-fmpzf0 коммитом ab237f5. Закрыт как superseded.


Generated by Claude Code

@SashaRX SashaRX closed this Aug 6, 2026
SashaRX pushed a commit that referenced this pull request Aug 6, 2026
…eview)

Confirmed the #135 whitelist only constrains the option NAMES (%~2 / %~4).
The values — %~1, %~3 and %~5 — went through untouched, and cmd.exe
substitutes an argument into the python line before parsing that line, so a
value carrying a double quote could close the quoting and run whatever
followed it.

Each forwarded value is now matched against a strict charset (letters,
digits, _ - . ~ : \ / and space) and rejected with exit /b 3 otherwise. The
test runs through delayed expansion, which substitutes the value after the
line is parsed, so the value under test cannot itself be read as syntax.

No cmd.exe in this environment, so the batch flow was desk-checked and the
charset decisions were verified with the equivalent POSIX class: the example
invocation, Windows drive paths and paths with spaces are accepted; quotes,
& | < > ^ % ! ( ) ; and apostrophes are rejected.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0195YC4HWo1rQqEdFBb8p8jE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant