Skip to content

fix: harden pipe and filesystem trust boundaries - #10

Draft
lumenpearson wants to merge 383 commits into
mainfrom
audit-defects
Draft

lumenpearson wants to merge 383 commits into
mainfrom
audit-defects

Conversation

@lumenpearson

@lumenpearson lumenpearson commented Nov 1, 2026 •

Copy link
Copy Markdown
Owner

Кратко

Продолжение аудита дефектов и файловых границ безопасности CDPI UI. PR исправляет отмену и обрыв pipe, усиливает доверие к повышенным запускам и MSI, а также переводит критические Windows-операции с пакетами, обновлениями, настройками, ссылками и каталогами Store на работу с проверенными открытыми объектами.

Описание сверено с HEAD ee47716: 38 коммитов, 135 изменённых файлов относительно main (d72ad478). PR остаётся черновым; полный аудит и приёмка релиза не завершены.

Что изменено

Pipe и сообщения об ошибках

  • Чтение именованного pipe корректно завершается при отмене и оборванном пакете; добавлены регрессии на настоящем pipe.
  • Потеря соединения с tray отображается как ERR_PROCESS_DIED, без ложного ERR_ACCESS_DENIED; обновлены обработка и представление критической ошибки.

Повышенные запуски, задачи и MSI

  • Доверенные пути отклоняют reparse points, включая ссылки и junction в корне и предках. DirectoryAclGuard меняет ACL через проверенный directory handle.
  • Условные задачи ограничены по размеру, числу файлов, действий и параметров; DTD запрещён. Каталог задач создаёт GUI, повышенный tray его не создаёт.
  • Portable-запуск отклоняется при несовпадении desktop-пользователя/владельца каталога. Launcher и tray проверяют защищённость зарегистрированной MSI-папки, её предков и файлов; одной записи HKLM недостаточно.
  • Native AOT launcher использует системный PATH. MSI cleanup запускается через встроенный launcher, требует SYSTEM и повторно проверяет путь установки; выполняется до удаления регистрационных значений.
  • MSI-пакет связывается с SHA-256 полученных или выбранных байтов. Источник удерживается при копировании, staging-копия проверяется по хешу и подписи.

Проверенные файлы, staging и каталоги

  • Добавлены Windows leases для чтения, записи и операций с именами: проверка обычного типа, no-follow открытие, закрепление родителей, отказ от небезопасных имён, ADS и недопустимых hard links. Намеренные файловые ссылки обрабатываются отдельным API.
  • Пакеты помещаются в защищённый CDPIUI-Staging с владельцем Administrators и DACL Administrators/SYSTEM. Защита сохраняется после выхода tray; потребитель удерживает собственный lease. При старте tray оставшиеся пакеты больше не удаляются без подтверждения завершения потребителя.
  • Signed ZIP проверяется и копируется из одного удерживаемого снимка. Состав каталога сопоставляется с этим снимком; Windows catalog/SIP-хеши вычисляются по открытым handles. Поздно добавленные файлы не попадают в установку.
  • Публикация проверенного набора файлов сначала подготавливает весь набор, затем заменяет файлы с удержанием originals/backups. При ошибке выполняется откат; конфликт восстановления сохраняет оригинал и сообщает recovery path.
  • Общие atomic write/copy helpers и проба прав записи используют проверенные Windows-объекты и собственные temporary-файлы. При отказе или отмене исходные данные сохраняются; сохранение DACL проверяется отдельно.

Обновление приложения

  • Update.exe вычисляет SHA-256 во время ограниченной распаковки и сверяет план с удерживаемым staging-снимком до изменения установленного файла.
  • UpdateFileTransaction выполняет публикацию и откат через открытые объекты. Неизвестный конфликтующий файл не перезаписывается; при неудаче восстановления сохраняется backup.
  • UpdateInstallationGate сериализует кооперирующие updater-процессы для одного target root через проверенный .update-lock; per-instance guard защищает жизненный цикл операции.
  • Staging/backup cleanup и лог updater переведены на проверенные файловые операции. Очистка staging, завершившаяся отказом, останавливает дальнейшую распаковку.
  • Общие исходники включены в updater как linked source: новая зависимость от DLL из заменяемой установки не добавляется.

XML-настройки и намеренные ссылки

  • Чтение settings, lock, backup, diagnostic copy и recovery используют проверенные Windows-пути. Небезопасный .lock не удаляется и не разрешает запись.
  • Initial creation и recovery берут общий lock и перечитывают источник после ожидания. Без lock восстановление выполняется только в памяти; повреждённый primary не заменяет последнюю хорошую .bak.
  • Settings публикуются атомарной заменой имени с сохранением access rules; добавлены проверки protected/inherited DACL.
  • WindowsLinkFileTransaction связывает новую symbolic link с ожидаемой целью, а hard link — с идентичностью исходного файла. Publish/backup/restore работают через удерживаемые имена. Устаревшая metadata не разрешает удалить обычный пользовательский файл; неизвестный temporary не удаляется без доказательства принадлежности.

Store, cache и ограниченная очистка

  • Валидация Store ID отклоняет device names, недопустимые имена и некорректные варианты защищённых ID. Каталог связывается с точным itemsRoot + itemId; защищённые папки исключены из destructive cleanup.
  • Неудачная файловая очистка сохраняет запись Store и состояние событий. Повторяются только допустимые transient-ошибки.
  • WindowsFileRemoval сначала захватывает ограниченное дерево без обхода directory links, затем удаляет конкретные открытые объекты. Файловые ссылки удаляются как имена, без изменения target bytes.
  • WindowsDirectoryTransaction заменяет local folders и repository cache с восстановлением прежнего root при ошибке. Старый cache не удаляется до успешной публикации нового. Конфликт отката сохраняет версии и recovery paths.
  • Распаковка и загрузчик репозитория повторно проверяют назначения после создания каталогов; для Windows создания и cleanup применяются новые native helpers.

Тесты, CI и документация

  • Добавлены Windows-регрессии для подмены путей, symbolic/dangling/hard links, sharing, ACL, catalog verification, atomic writes, settings/recovery, updater rollback/serialization и Store directory transactions.
  • Добавлен ToolsSmokeTest: запускает опубликованные Update.exe, EditHostFile.exe и Native AOT launcher с --smoke-test, а также проверяет защищённый staging. CI явно ждёт завершения GUI-runner и проверяет отчёт/exit code.
  • Обновлены README и релизная документация EN/RU. Подробные результаты проходов, воспроизведения и ограничения собраны в docs/AUDIT-STATUS.ru.md.

Проверка текущего HEAD ee47716

GitHub Actions — run 42589545837: libraries, tools, gui, secrets — success на ee4771675956fe213634675f37579362efb7e0eb.

  • libraries: 980 passed, 0 failed, 0 skipped; сборки библиотек/tray прошли без предупреждений и ошибок, проверка уязвимых зависимостей прошла.
  • tools: сборка/публикация утилит и Native AOT launcher прошли; smoke-запуски всех трёх опубликованных инструментов и проверка staging завершились успешно.
  • gui: GUI, portable layout, сверка состава установщика и Setup.msi собраны. У MSI остаются два предупреждения ICE60/ICE61, ошибок нет.
  • secrets: проверка завершилась успешно.

Локальные Windows-воспроизведения и результаты отдельных проходов перечислены в AUDIT-STATUS. Smoke-режимы не изменяют настоящий hosts и не заменяют полноценную установку/удаление MSI. Проверки и декомпозиция из других локальных веток не включены в результат этого PR.

Ограничения и оставшаяся работа

  • Полный файловый аудит не завершён: остаются другие cleanup callers, runtime code/argument/write handoff, окончательный restart и отдельные MSI-сценарии.
  • Откат покрывает ошибки работающего процесса. Durable crash journal, общая транзакция filesystem/database и единый Store/MSI/updater mutex не реализованы.
  • Native directory transaction защищает операции с root-именами; она не фиксирует mutable child bytes и не заменяет проверку подписанного snapshot. Cleanup после начала удаления может оставить частично очищенное собственное дерево.
  • Сохранение DACL не означает сохранения owner, ADS, EFS и всех metadata flags. Non-Windows fallback не получает гарантий Windows handles.
  • Сквозное доверие к Store, обязательный подписанный index/хеши всех артефактов и архитектурный перенос компонентов в admin-only хранилище остаются отдельными задачами.
  • Live MSI install/uninstall, системное восстановление после crash и полная пользовательская приёмка требуют отдельного контролируемого прогона. Зелёный CI не является заключением о безопасности релиза.

Problem

Pipe cancellation, privileged paths and mutable filesystem names need consistent trust and recovery rules. The full remaining defect audit is tracked separately.

Changes

This draft introduces protected staging, held source and destination objects, catalog snapshot validation, settings and link transactions, bounded cleanup and Store root identity. The original detailed technical record above remains preserved.

Verification

The recorded CI on ee4771675956fe213634675f37579362efb7e0eb passed secrets, libraries, gui and tools, with 980 tests and no skips. Native tests used isolated Windows scratch data. Full installed MSI/portable, live components and release qualification remain outstanding. Recheck all required jobs on any new HEAD.

Risk and recovery

The change affects elevated execution, filesystem writes and update recovery. Keep retained backups and reported recovery paths when rollback conflicts. Exception rollback does not prove power-loss durability. This PR remains draft until independent acceptance under #13. No human reviewer or release approval is fabricated.

Related work

Refs #12, #13 and #21. File findings: #81, #82, #83, #84, #85, #86, #87, #88, #89, #90, #91 and #92. Installed-product acceptance: #16. Release qualification: #19 and #20. Delivery contract: #11.

Current comparison boundary

The earlier 38-commit / 135-file figures describe the recorded comparison with d72ad478bc05c6ab9e53f46da1a2b6c58690b202. Another session replaced that main history with 7ead95f7756057f67cd113671a7f84cf422e8d32; those two revisions have the same tree 33323ba54f948dc7379061e805330bcb08fd610d.

At the governance handoff, the PR API records base 7ead95f7756057f67cd113671a7f84cf422e8d32 and reports 383 commits / 1197 changed files. The default branch has since received the governance configuration through PR #111 and PR #121, reaching 6a54391663995baf8cf70b0b97711ab0bd617a7b. Do not treat the earlier counts as a fresh comparison with that default-branch head.

The product branch owner must reconcile ancestry, regenerate the final comparison and rerun independent review and required CI before integration. The successful Contribution metadata status validates the issue links and required PR fields only. This governance setup does not change head ee4771675956fe213634675f37579362efb7e0eb, remove draft state or approve product integration.

…h a warning

Presets of older zapret1 versions use split2, disorder2, split and disorder, which zapret 67 renamed to multisplit, multidisorder, fakedsplit and fakeddisorder, and options such as --wssize and --hostcase; each of them failed the conversion of the whole preset. The old names are mapped to the current ones, and the tuning options without a Zapret2 counterpart are left out with a warning.
…d line changes

With hash validation turned off, the Zapret2 cache returned the stored startup string whenever the cached files existed, so converter fixes in a new version and changed toggles or variables of the preset were ignored. The manifest now records the application version and a hash of the expanded command line, and the fast path uses the cache only when both match.
At start, variables were replaced in one case-sensitive pass, while the editor expanded nested variables ignoring case, so the editor showed other files than the component received. A variable declared twice threw ArgumentException at start, names with '-' or '.' were never replaced, a self-referencing definition such as %A%=%A%%A% grew without limit in the editor, and presets named initial-*.json were skipped as pack descriptions. Both paths now ignore case, resolve nested variables with a length limit, accept '-' and '.' in names and take the last of duplicate definitions.
… spaces

ReplaceFilesPath replaced paths as substrings, so replacing list.txt also changed mylist.txt, turned every apostrophe of the startup line into a quote and every empty "" into a single quote, and did not match a path written with the other separator. It now replaces whole paths with either separator, together with their quotes. $GETCURRENTDIR() and $GETSRDIR in startup lines were not quoted, so a profile path with a space split the argument (issue #2); they are quoted there unless they already stand inside quotes. A $LOCALCONDITION without $SEPARATOR split at the first colon, which broke at C:\.
… BAT files

The start line pattern needed a quoted program, so with start "t" /min %BIN%winws.exe the program stayed in the arguments; set "WF=..." kept a space before the name, so its rem alternatives were not attached to it; only the first !VAR! of a value was expanded; and any rem comment containing "set", such as "rem settings = ...", created a variable.
CopyUsedFilesToDirecrory created a failure result and dropped it, so an export reported success without its files; a file of another item resolved to ..\..\ and was copied outside the pack being built; and a preset without target threw.
… is gone

The autocorrection enumerated the folders of all items in one try block, so a single database entry whose folder no longer existed ended the search for every file.
…gative values

--blob=name:[email protected] treated "[email protected]" as the path, --lua-init=@file with ';' or '=' in the name was taken for inline Lua, and IsOption treated values such as -10000 as options, so the following file argument was lost.
Init cleared and refilled the shared list of component helpers while other threads looked components up, so a lookup during a Store change or at startup could fail or throw. The list is now built aside and replaced as a whole, and callers get a copy.
StartProcess sent the start command even when the component helper was missing, the executable did not exist or the preset gave an empty startup line, so GoodbyeDPI ran with its defaults and winws exited at once; these cases now end with an error message. ComponentHelper.GetDirectory checked its folder with File.Exists, which is always false for a folder.
install_msi with $ALL passed every file of the folder to msiexec, so a readme or a .cab next to the installers failed the installation of the pack.
Profiles were split at every "--new", also inside options such as --newfoo; any "$...(...)" in a preset name was taken for a localization script, so "Fast $5 (beta)" lost its text; a file path with '@' was cut at it by the Zapret converter; and RunAllPreferredActions awaited null for a task without process manager and iterated the live task list.
…e right hive

The system proxy settings saved before CDPI UI turned on its own proxy lived only in memory, so a killed, crashed or hard-restarted tray left the proxy pointing to a stopped component and the previous proxy of the user was lost. The snapshot is now also written to proxy-backup.json and restored at the next start of the tray. The settings are written to the hive of the user at the desktop when the tray runs elevated under another account.
The tray menu checked IsHandleCreated and then called Invoke from task event threads; when the menu was destroyed in between, the exception in the async void handler ended the tray, and no Application.ThreadException handler was registered. Invoke now goes through SafeInvoke, and unhandled UI exceptions are logged instead.
Each right click created a new menu form and left the previous one open with its subscriptions to the task list singleton.
…in ConPTY

Processes started through the pseudo console now belong to a job object that ends them with the tray, so winws, GoodbyeDPI or ProxiFyre no longer keep running after a crash or a kill of the tray. CreateProcess was declared without CharSet and called CreateProcessA, which turned characters outside the ANSI code page into '?' in paths. The output loop spun when the pipe closed, UTF-8 characters split between two reads were damaged, the process handle and the attribute list leaked on the cancel and error paths, and StopProcess waited without limit for the process to end. The generic "error" mapping overwrote specific ones, so "Error opening filter" was reported as UNKNOWN.
The tray had no single instance check while its pipe name is global, so a second tray renamed _Update.exe, started the GUI, took the notification area icon and registered hot keys before it failed on the pipe. A global mutex now ends a second tray at once; a tray started while the previous one is still exiting, as after an update, waits for it up to 10 seconds.
…lients

The tray sent component output, paths and status to any connected client before it had authorized, and a client that never authorized kept the single pipe instance, locking the real GUI out. Only service messages go out before authorization now, and a client that does not authorize within 15 seconds is disconnected.
Any write to the task folder reset the pending delayed actions of every task; now only removed or changed tasks lose their state. The folder watcher had no Error handler and stopped for good after a buffer overflow; it is created again and the tasks are reloaded. Hot keys were identified by the modifier text, so the same keys in another order were registered twice, and they were registered before the message window existed.
The list of components that use WinDivert did not contain Zapret2, so the service could be deleted under a running winws2, and ExecuteCommand wrote failures of sc to a console the tray does not have, so the error handling around it never ran.
The tray blocked the component buttons before GoodCheck started; when the job object could not be created the exception skipped the unblocking, and the job handle was never closed. Both now happen in a finally block, and a failed job is reported to the GUI.
…llections

NIN_KEYSELECT was defined as 0x403 instead of 0x401 and not handled, so Enter or Space on the notification area icon did nothing. HideWindow ran a full GC.Collect on every close of the tray menu.
The log monitor started reading at the end of the newest log file, so the lines written before the file was found were lost, and the Died event of the tray marked the run as a success and stopped the monitor without a final read, so a GoodCheck that failed its connectivity check produced an empty report with a success status (related to issue #50). Only logs created by the current run are read, from their start; when the process ends the rest of the log is read, and a run without "All Done" is an error.
… write files elsewhere

The tray starts components with administrator rights, and a .cdpiconfig or a BlockCheck2 report from someone else could carry options such as --debug=@file, --wf-save or --hostlist-auto that make winws write any file. Shared presets may now write only into their own package, and reports, whose synthesized presets never write files, are rejected when they contain such options.
…remove old merged lists

The merged site list was written with a UTF-8 BOM, lists with the same file name from different packs overwrote each other in the GoodCheck folder, and the merged {epoch}_sitelist.txt files of earlier runs were never removed.
For plain HTTP any status but 400 counted as success, so a provider's 451 or its redirect to a block page made the route look reachable and it was dropped as needing no bypass; 451 and redirects to another host now fail the check. Targets without a DNS answer are still left out of the strategy search, and the warning now says that this is often DNS blocking that needs encrypted DNS.
When winws2 or its driver could not start, every strategy failed with strategy_start_failed and only a warning, and the scan went through the whole catalog before synthesizing a preset from no results. After five strategies in a row that could not start, the scan now stops with an error.
The Intel Connectivity Network check looked for any running service with "Intel", "Connectivity" or "Network" in its name and fired on almost every computer, the VPN check reported a merely installed VPN service as running, the running check looked only at the first service with a matching name, and the WinDivert fix reported success without checking that the service stopped.
…econds

GrantAccess waited without limit for the answer of the tray, and an answer that came without a request threw.
ConfigShare limited the total size of an archive to 512 MiB but not the compression ratio, so a small .cdpiconfig could unpack to that size into memory and onto disk before the user had confirmed anything.
This was referenced Nov 10, 2026
@lumenpearson lumenpearson added type:audit Investigate a risk. A new defect is not yet confirmed. area:security Trusted paths, privileges, pipe trust, signatures and protected operations. area:reliability Cancellation, errors, races, data preservation and recovery. labels Nov 10, 2026 — with ChatGPT Codex Connector
@lumenpearson lumenpearson changed the title Аудит дефектов: завершение pipe и проверка доверенных путей fix: harden pipe and filesystem trust boundaries Nov 10, 2026
@lumenpearson lumenpearson moved this from Inbox to In progress in CDPI UI — Delivery & Release Gates Nov 10, 2026
@lumenpearson lumenpearson linked an issue Nov 10, 2026 that may be closed by this pull request
12 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:reliability Cancellation, errors, races, data preservation and recovery. area:security Trusted paths, privileges, pipe trust, signatures and protected operations. type:audit Investigate a risk. A new defect is not yet confirmed.

Projects

Status: In progress

Development

Successfully merging this pull request may close these issues.

[G1] Qualify PR #10 for independent acceptance on its final HEAD

1 participant