diff --git a/docs/operations/CURRENT_STATE.md b/docs/operations/CURRENT_STATE.md index bc109de..5bcc87e 100644 --- a/docs/operations/CURRENT_STATE.md +++ b/docs/operations/CURRENT_STATE.md @@ -21,21 +21,26 @@ cutover, canary, and rollback checks. The receiver repeats the config check before journaling/stopping services and again after backup immediately before switching refs. -- The Windows client has disabled-by-default preparation and auto-apply tasks - with a fixed `D:\Dev\akyldash` target and `akyldash_release` alias. The example - config files and Task Scheduler XML are disabled; the templates use an - interactive least-privilege owner, ignore overlapping invocations, and - does not wake the computer. No Windows task, SSH key, VPS command, helper, - or trigger action has been installed or exercised. The canonical - `C:\ProgramData\Akyldash\release-trigger.json` path is known, but its - contents/enabled state have not been read. Windows metadata confirms - `C:\Python313\python.exe`, valid Python Software Foundation Authenticode, - and protected interpreter ACLs. Linux fixtures pass for Python import and - command-path poisoning, including inherited `GIT_*` removal and fixed - `ssh.exe`/`git.exe`/`powershell.exe` resolution. The installer also checks - protected ownership/write access across each tool's parent path. These Windows - ACL checks are code-reviewed only; the installer and launcher have not run on - Windows. Production CD remains inactive. +- Windows client предназначен для подготовки и auto-apply; обе задачи по умолчанию + выключены, целевой путь фиксирован: `D:\Dev\akyldash`, SSH alias — + `akyldash_release`. Примеры config и Task Scheduler XML также выключены; задачи + запускаются от интерактивного пользователя с минимальными правами, не допускают + параллельных запусков и не будят компьютер. Windows task, SSH key, VPS command, + helper и trigger не устанавливались и не запускались. Путь canonical + `C:\ProgramData\Akyldash\release-trigger.json` известен, но содержимое и + enabled-состояние не читались. Метаданные Windows подтверждают + `C:\Python313\python.exe`, действительную Authenticode-подпись Python Software + Foundation и защищённые ACL интерпретатора. +- Linux fixtures прошли для Python import и command-path poisoning, включая очистку + унаследованных `GIT_*` и фиксацию путей `ssh.exe`/`git.exe`/`powershell.exe`. + Installer получает ограниченный bundle из точной вершины `main`: упаковщик + читает Git objects commit, tree и allowlist-файлов; elevated installer проверяет + SHA-256 ZIP и цепочку `commit → tree → файлы` из одного read-locked потока до + записи и не запускает Git. ACL проверяются явными масками мутаций и подмены; + текущая учётная запись не может владеть кодовыми путями, а право создать + соседнюю папку не считается подменой предка. Windows ACL/install проверки пока + только прошли код-ревью; installer и launcher на Windows не запускались. + Production CD остаётся выключенным. - Remaining owner prerequisites are installation of the reviewed root helper, exact forced-command/SSH host-key setup, a protected Windows client and its private state/config ACLs, private D: backup ACLs, and all previously listed diff --git a/docs/operations/DEPLOYMENT.md b/docs/operations/DEPLOYMENT.md index 982a813..e71abff 100644 --- a/docs/operations/DEPLOYMENT.md +++ b/docs/operations/DEPLOYMENT.md @@ -66,28 +66,45 @@ verified tuple exactly matches a tuple saved by a previous poll. An owner can also use `--apply-prepared`, which requires an interactive exact-SHA confirmation. Both deploy paths re-enter the existing root receiver and all backup/ACK/cutover guards. Rollback remains a separate explicit owner-run -command. The scheduler templates run as the interactive owner at least -privilege, ignore overlapping instances, and never wake the computer. No task -has been registered or enabled by this PR. +командой. Планировщик запускает задачи от интерактивного владельца с минимальными +правами, пропускает повторный запуск при активном экземпляре и не будит компьютер. +Этот PR не зарегистрировал и не включил ни одну задачу. -The reviewed bootstrap installer requires a clean `main` checkout at an -explicit SHA, verifies the signed `C:\Python313\python.exe` and protected ACLs, -and stages client files under a SHA-versioned Program Files directory without -overwriting an existing version. It preserves an existing canonical -`C:\ProgramData\Akyldash\release-trigger.json`, requires it to remain disabled, -and creates a second disabled auto-apply config only if absent. It writes two -disabled task XML files for owner review and does not register or enable tasks. -The launcher starts Python with `-B -E -s -S`, removes paths outside the standard -library and protected client folder, and checks imported module origins. Before -loading the receiver it replaces inherited command lookup with the fixed Windows, -OpenSSH, and Git directories; it clears inherited `GIT_*` variables and verifies -that `ssh.exe`, `git.exe`, and `powershell.exe` resolve to their fixed paths. The -installer checks those binaries and every parent path for reparse points, trusted -owners, and write access limited to SYSTEM, Administrators, and TrustedInstaller. -Synthetic poisoning tests ran on Linux; the launcher and installer have not -been executed on Windows. Keep both config gates and both tasks disabled until -the owner records the normal backup/restore and production readiness gates. -Do not bind a Gitea workflow or PR runner to this Windows host. +Сначала подготовьте bundle под обычной учётной записью из точной локальной +вершины `main` командой `prepare_windows_release_bundle.py`. Упаковщик читает +только Git objects указанного полного commit SHA, сверяет Git blob identity +исходников и создаёт небольшой ZIP с SHA-256; рабочее дерево он не читает и не +копирует. Elevated installer получает путь к ZIP, ожидаемый commit и SHA-256. +Он один раз открывает пакет с запретом записи/удаления, проверяет SHA-256 архива, +manifest и Git blob IDs в памяти, затем копирует только проверенные байты. +Дополнительно installer проверяет цепочку Git objects `commit → tree → файлы`. +На elevated этапе Git не запускается; `.git/config`, hooks и состояние checkout +не используются. Не изменяйте ZIP между подготовкой и установкой. + +Проверенный bootstrap installer проверяет подпись PSF у +`C:\Python313\python.exe` и защищённые ACL, затем размещает файлы клиента в +SHA-версионном каталоге `Program Files`, не перезаписывая существующую версию. +Для новых файлов кода владельцем назначается `Administrators`. У кода владельцем +могут быть только SYSTEM, Administrators или TrustedInstaller; учётная запись +задачи допускается владельцем только для отдельного private state/config. +Проверка ACL файла и защищённого каталога запрещает недоверенным субъектам запись, +добавление, удаление, удаление дочерних объектов, смену прав или владельца. Для +родительских каталогов проверяются права, способные подменить защищённый путь; +разрешение создать посторонний соседний каталог подменой не считается. +Installer сохраняет существующий canonical-файл +`C:\ProgramData\Akyldash\release-trigger.json`, только если он выключен; второй +disabled auto-apply config создаётся только при отсутствии. Installer формирует +два disabled task XML для проверки владельцем, но не регистрирует и не включает +задачи. Launcher запускает Python с `-B -E -s -S`, оставляет в import path только +стандартную библиотеку и защищённый каталог клиента, затем проверяет происхождение +импортированных модулей. До импорта receiver он заменяет унаследованный command +lookup фиксированными каталогами Windows, OpenSSH и Git, очищает `GIT_*` и +проверяет, что `ssh.exe`, `git.exe` и `powershell.exe` разрешаются в заданные пути. +Для самих бинарников и их родительских каталогов проверяются reparse points, +владельцы и ACL по правилам выше. Тесты подмены Python imports и command paths +выполнены на Linux; installer и launcher на Windows не запускались. Оставляйте оба +config gate и обе задачи выключенными до фиксации владельцем обычных backup/restore +и production readiness gate. Не привязывайте Windows-хост к Gitea workflow или PR runner. The root status/deploy helper remains the reviewed root-installed bootstrap code; it never checks out or executes target release code. A newer app release diff --git a/docs/operations/DEPLOYMENT_OWNER_PACKET.md b/docs/operations/DEPLOYMENT_OWNER_PACKET.md index 3cf535b..8a8b85f 100644 --- a/docs/operations/DEPLOYMENT_OWNER_PACKET.md +++ b/docs/operations/DEPLOYMENT_OWNER_PACKET.md @@ -1,112 +1,125 @@ -# Deployment owner evidence packet +# Пакет проверок владельца перед деплоем -This packet is a list of owner-only checks. It does not authorize a production -change. Do not include token/password values, environment-file contents, -private keys, secret material, or raw process environments. +Здесь перечислены проверки, которые выполняет владелец. Этот документ не +разрешает production-изменения. Не включайте значения токенов и паролей, +содержимое env-файлов, приватные ключи, другие секреты или полный вывод +переменных окружения. -## Required before release use +## Что требуется до использования CD -- PR #59's disabled one-shot Windows trigger is in `main`; it has not been - installed or exercised. This PR's bootstrap files are also uninstalled. - After review and merge, run `install_windows_release_client.ps1` only from a - clean `main` checkout and provide its exact SHA through `-ExpectedCommit`. - The installer verifies Python's PSF Authenticode signature and protected - ACLs, stages client files in a SHA-versioned Program Files directory without - replacing an existing version, preserves an existing canonical trigger - config only if it is still disabled, and writes two disabled task XML files - for review. It never registers or enables tasks. The canonical - `C:\ProgramData\Akyldash\release-trigger.json` path is known, but its - contents and enabled state have not been read. The launcher uses the - verified `C:\Python313\python.exe` with `-B -E -s -S` and validates module - origins. It also replaces inherited PATH, clears `GIT_*` overrides, and - requires SSH, Git, and PowerShell to resolve to fixed protected binaries; the - installer checks their parent paths for untrusted write access. The prep task - stores a protected `PREPARED` tuple and never deploys. - The separate auto-apply task is also disabled and requires a second config - gate. The `enabled` field in the preparation config alone cannot deploy. - Apply runs only when the fresh root status tuple matches a tuple saved by an - earlier poll; no per-commit owner confirmation is needed after the owner - explicitly activates unattended deployment. Enable the preparation config - and task only after the owner separately approves polling. Enable the - auto-apply config and task only after the owner approves unattended - production deployment and completes every backup/restore readiness gate. - Disabling either auto-apply control stops future automatic deploys; an - already running cold backup/deploy must be allowed to finish or be explicitly - recovered. -- The `akyldash_release` SSH key must be dedicated to the root forced-command - dispatcher, with OpenSSH `restrict` (or equivalent no-PTY/no-forwarding - options), verified host-key checking, and exact status/deploy command - matching. Do not put an unrestricted command or shell in root's - `authorized_keys`. The existing rollback key/path remains a separate manual - owner action. No key is generated, copied, or installed by this PR. -- Decide whether unattended production CD is acceptable. It currently is not - active: `deploy-handoff.yaml` remains status-only and reports `NOT DEPLOYED`; - both local tasks and both config gates remain disabled. This avoids exposing - the Windows host to repository PR workflows. Verify the root status command - is installed from reviewed bootstrap code and its forced-command key is - restricted. The host checkout need not match current `main`: status compares - root-protected Compose/Caddy bytes and the installed release policy with the - exact candidate SHA through Gitea's pinned contents API and verifies Git blob - hashes/sizes. The receiver repeats this before stopping services and cutover - repeats it after backup. A mismatch requires a reviewed owner bootstrap - update; no root checkout/helper code is automatically executed or updated. - Current `main` and CI/release provenance are still rechecked before apply. - The endpoint fails closed if the - filtered workflow-run API page is incomplete (more than ten candidates or - count mismatch), so status API behavior must be checked on the live Gitea - before activation. -- Confirm the registry package names and least-privilege writer/pull access for - `admin/akyldash/backend` and `admin/akyldash/opensearch`; record digest - retention for the rollback window. The latest read-only Gitea check found - main CI run #706 successful, image release run #708 failed because the - repository `REGISTRY_USERNAME` and `REGISTRY_PASSWORD` secrets are absent, - and status-only handoff run #709 skipped. Configure those repository secrets - through Gitea's secret settings; do not put their values in Git or logs. -- Confirm Gitea artifact retention covers the rollback window. The workflow - requests 90 days for the small release descriptor and checksum. -- Provide a dated, sanitized root audit: installed checkout SHA, Compose - services and image IDs, health state, volume paths/modes, protected-file - owner/mode, listener summary, and current recovery-journal state. -- Confirm a root-controlled SSH path exists for the fixed deploy and rollback - commands, using existing owner SSH configuration and verified host-key - checking. The repository `codex` account must not receive general sudo, - Docker-group membership, or a Docker socket. No SSH key or root alias is - provisioned by this PR. -- If required, install a narrowly scoped, read-only Gitea API token at - `/etc/akyldash/gitea-api-token` with root ownership and mode `0600`. Record - only whether it is present and its scope; never send its value. -- Verify the Gitea artifact download origin. If redirected, provision only the - exact HTTPS origin in `/etc/akyldash/gitea-download-origins` as a root-owned - mode-`0600` file. The patched helper must not send its token to that origin. -- Provide owner-approved RU and KY search canary queries in - `/etc/akyldash/release-canaries.json`, root-owned mode `0600`. Confirm they - return expected non-empty results without sending corpus documents. -- Confirm Cloudflare TLS mode, origin certificate renewal, and current public - `/review` and search health. +- Отключённый одноразовый Windows trigger из PR #59 уже находится в `main`, но + не установлен и не запускался. Bootstrap из этого PR также не установлен. + После ревью и слияния обновите локальный `main` до проверенного полного SHA. + Под обычным пользователем подготовьте bundle командой + `prepare_windows_release_bundle.py --repository D:\Dev\akyldash --commit --output `. + Упаковщик требует, чтобы SHA совпадал с локальной вершиной `main`; он читает + Git objects этого commit, а не рабочее дерево, проверяет SHA-1 объектов + commit/tree/blob и печатает SHA-256 ZIP. Передайте именно эти SHA и путь + elevated installer: + `install_windows_release_client.ps1 -ExpectedCommit -BundlePath -ExpectedBundleSha256 `. + Installer открывает ZIP один раз с запретом записи и удаления, сверяет SHA-256, + manifest и цепочку `commit → tree → файлы` в памяти и только после полной + проверки копирует эти байты. Elevated installer не запускает Git и не читает + `.git/config`, hooks или файлы checkout. Не меняйте ZIP между подготовкой и + установкой; сохраните SHA и полный commit для журнала владельца. +- Installer проверяет подпись PSF у `C:\Python313\python.exe` и защищённые + ACL, создаёт версионный каталог в `Program Files` без перезаписи существующей + версии и назначает владельцем новых файлов кода `Administrators`. Кодовые + пути должны принадлежать только SYSTEM, Administrators или TrustedInstaller; + учётная запись задачи допускается владельцем только для отдельных private + state/config. ACL-проверка файла/кодового каталога выявляет запись, добавление, + удаление, удаление дочерних объектов, смену ACL и владельца. Проверка родительских + каталогов выявляет права, позволяющие заменить защищённый путь; создание + постороннего соседнего каталога само по себе не считается подменой. +- Installer сохраняет существующий `C:\ProgramData\Akyldash\release-trigger.json` + только если он остаётся отключённым, создаёт disabled auto-apply config лишь + при отсутствии и формирует два disabled Task Scheduler XML для проверки. + Он не регистрирует и не включает задачи. Путь trigger известен, но содержимое + и его enabled-состояние не читались. +- Launcher использует проверенный `C:\Python313\python.exe` с `-B -E -s -S`, + проверяет происхождение импортированных модулей, заменяет унаследованный `PATH`, + очищает `GIT_*` и фиксирует разрешение `ssh.exe`, `git.exe` и `powershell.exe` + в доверенные пути. Задача подготовки сохраняет защищённый `PREPARED` tuple и + никогда не отправляет deploy-запрос. +- Задача auto-apply и её отдельный конфиг тоже остаются выключенными. Одного + `enabled` в preparation config недостаточно для деплоя. Auto-apply разрешён, + только если свежий root status точно совпал с tuple, сохранённым предыдущим + опросом. После явного согласования владельцем unattended deployment отдельное + подтверждение каждого SHA не требуется. Включайте preparation config и задачу + только после отдельного разрешения на опрос; auto-apply config и задачу — только + после отдельного разрешения на unattended production deployment и выполнения + всех backup/restore gate. Отключение любого auto-apply control останавливает + будущие автодеплои; уже начатый cold backup/deploy должен завершиться либо быть + восстановлен по процедуре. +- Ключ `akyldash_release` должен быть отдельным и привязанным к root forced-command + dispatcher с OpenSSH `restrict` (или эквивалентным запретом PTY и forwarding), + проверкой host key и точным сопоставлением status/deploy-команд. Не добавляйте + unrestricted shell или команду в root `authorized_keys`. Существующий ключ и + путь rollback остаются отдельным ручным действием владельца. PR не создаёт, + не копирует и не устанавливает ключи. +- Решите, допустим ли unattended production CD. Сейчас он не включён: + `deploy-handoff.yaml` остаётся только status-проверкой и сообщает + `NOT DEPLOYED`; обе локальные задачи и оба config gate выключены. Windows-хост + не открыт workflow и PR runner. Убедитесь, что root status command установлен + из проверенного bootstrap и ключ forced command ограничен. +- Checkout на хосте не обязан совпадать с текущим `main`: status сравнивает + защищённые root Compose/Caddy файлы и установленную release policy с файлами + точного candidate SHA через pinned Gitea Contents API и проверяет Git blob IDs + и размеры. Receiver повторяет сравнение до остановки сервисов; cutover повторяет + его после backup. Несовпадение требует отдельного проверенного owner bootstrap + update; код release или root helper автоматически не выполняется и не обновляется. + Текущий `main` и CI/release provenance всё равно перепроверяются перед apply. + Endpoint закрывается при неполной странице workflow-run API (более десяти + кандидатов или несовпадение count). Перед включением проверьте поведение этого + API на установленной версии Gitea. +- Подтвердите имена registry packages и минимальные права записи/чтения для + `admin/akyldash/backend` и `admin/akyldash/opensearch`; сохраните digest не + короче rollback window. Последняя read-only проверка Gitea: main CI run #706 + завершился успешно, image release run #708 завершился ошибкой из-за отсутствия + repository secrets `REGISTRY_USERNAME` и `REGISTRY_PASSWORD`, status-only + handoff run #709 был пропущен. Добавьте эти secrets через настройки Gitea; + не помещайте значения в Git или логи. +- Проверьте, что срок хранения Gitea artifacts покрывает rollback window. + Workflow запрашивает хранение небольшого release descriptor и checksum на 90 дней. +- Подготовьте датированный очищенный root audit: SHA установленного checkout, + Compose services и image IDs, состояние health, пути и режимы volumes, + владельца/режим защищённых файлов, сводку listeners и состояние recovery journal. +- Подтвердите root-controlled SSH путь для фиксированных deploy/rollback-команд, + используя существующую owner SSH-конфигурацию и проверенный host key. Репозиторный + `codex` не должен получать общий sudo, членство в Docker group или Docker socket. + PR не устанавливает SSH key или root alias. +- Если потребуется, установите узко ограниченный read-only Gitea API token в + `/etc/akyldash/gitea-api-token`, владелец root, mode `0600`. Запишите только + наличие и scope токена, не его значение. +- Проверьте origin скачивания Gitea artifacts. При redirect добавляйте только + точный HTTPS origin в `/etc/akyldash/gitea-download-origins`, root-owned, + mode `0600`. Исправленный helper не должен отправлять этому origin token. +- Добавьте одобренные владельцем RU и KY search canary queries в + `/etc/akyldash/release-canaries.json`, root-owned, mode `0600`. Убедитесь, что + они возвращают ожидаемые непустые результаты; не передавайте тексты корпуса. +- Проверьте TLS mode Cloudflare, продление origin certificate и текущую доступность + публичных `/review` и search. -## Backup and recovery gates +## Backup и восстановление -- The complete archive must remain on the owner-controlled Windows destination - `D:\Dev\akyldash\.backups`; never stage a full archive on the VPS. -- Synthetic Windows protocol checks and a disposable private-NTFS owner-ACL - fixture passed. Before relying on the flow, run its checks against the actual - D: path and local `.git/info/exclude`, then verify an approved backup is - published only after hash and manifest verification. -- Confirm D: encryption at rest. Archives contain production secrets and - private keys; the protocol encrypts transport but does not encrypt files at - rest. -- Restore a verified archive on an isolated separate target and check data, - SQLite integrity, OpenSearch, and required secrets. Do not use production as - a restore test. -- Confirm current data/index counts, corpus generation, and migration - compatibility. Image rollback does not restore data or undo schema changes. -- Set the archive retention period and keep the previous verified archive - throughout the rollback window. +- Полный архив хранится только на Windows-носителе владельца + `D:\Dev\akyldash\.backups`; не размещайте полный архив на VPS. +- Synthetic Windows protocol проверки и временная private-NTFS owner-ACL fixture + прошли. До использования проверьте реальный путь D: и локальное правило + `.git/info/exclude`; затем подтвердите, что одобренный backup публикуется только + после проверки hash и manifest. +- Подтвердите шифрование D: при хранении. Архив содержит production secrets и + private keys; протокол шифрует передачу, но не хранение файлов. +- Восстановите проверенный архив на отдельной изолированной цели и проверьте данные, + SQLite integrity, OpenSearch и необходимые secrets. Не проверяйте restore на production. +- Подтвердите текущие counts данных и индекса, corpus generation и совместимость + миграций. Откат образа не восстанавливает данные и не отменяет изменения схемы. +- Задайте срок хранения архивов и сохраняйте предыдущий проверенный архив весь + rollback window. -The installer does not create credentials, SSH configuration, canary values, -registry access, or new sudo rules. The PR has not been installed or run -against production. Windows validation passed 12 synthetic client checks, 8 -protocol checks, and a disposable real-NTFS private owner-ACL fixture. The -actual D: path, SSH, full backup, and separate-target restore remain -unverified. Keep deployment disabled until the owner records evidence for -each gate above. +Installer не создаёт credentials, SSH configuration, canary values, доступ к +registry или новые sudo rules. PR не установлен и не запускался на production. +Windows validation прошла 12 synthetic client checks, 8 protocol checks и временную +private owner-ACL fixture на NTFS. Installer и launcher на Windows не запускались; +реальный путь D:, SSH, полный backup и restore на отдельную цель не проверены. +Не включайте deployment до фиксации владельцем результатов всех проверок выше. diff --git a/infra/deploy/install_windows_release_client.ps1 b/infra/deploy/install_windows_release_client.ps1 index f14f408..0f441dc 100644 --- a/infra/deploy/install_windows_release_client.ps1 +++ b/infra/deploy/install_windows_release_client.ps1 @@ -1,7 +1,12 @@ param( [Parameter(Mandatory = $true)] [ValidatePattern('^[0-9a-f]{40}$')] - [string]$ExpectedCommit + [string]$ExpectedCommit, + [Parameter(Mandatory = $true)] + [string]$BundlePath, + [Parameter(Mandatory = $true)] + [ValidatePattern('^[0-9a-f]{64}$')] + [string]$ExpectedBundleSha256 ) $ErrorActionPreference = 'Stop' @@ -14,15 +19,22 @@ $app = Join-Path $appRoot "client-$ExpectedCommit" $programData = 'C:\ProgramData\Akyldash' $trigger = Join-Path $programData 'release-trigger.json' $autoApply = Join-Path $programData 'release-auto-apply.json' -$taskTemplate = Join-Path $PSScriptRoot 'windows-release-trigger.example.xml' -$repo = (& $git -C $PSScriptRoot rev-parse --show-toplevel).Trim() -if ($LASTEXITCODE -ne 0) { throw 'Cannot locate the reviewed repository checkout.' } -$branch = (& $git -C $repo branch --show-current).Trim() -$head = (& $git -C $repo rev-parse HEAD).Trim() -$dirty = & $git -C $repo status --porcelain -if ($LASTEXITCODE -ne 0 -or $branch -ne 'main' -or $head -ne $ExpectedCommit -or $dirty) { - throw 'Install source must be the clean main checkout at ExpectedCommit.' -} +$mutationRights = [System.Security.AccessControl.FileSystemRights]( + [int][System.Security.AccessControl.FileSystemRights]::WriteData -bor + [int][System.Security.AccessControl.FileSystemRights]::AppendData -bor + [int][System.Security.AccessControl.FileSystemRights]::WriteExtendedAttributes -bor + [int][System.Security.AccessControl.FileSystemRights]::WriteAttributes -bor + [int][System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor + [int][System.Security.AccessControl.FileSystemRights]::Delete -bor + [int][System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor + [int][System.Security.AccessControl.FileSystemRights]::TakeOwnership +) +$pathReplacementRights = [System.Security.AccessControl.FileSystemRights]( + [int][System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor + [int][System.Security.AccessControl.FileSystemRights]::Delete -bor + [int][System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor + [int][System.Security.AccessControl.FileSystemRights]::TakeOwnership +) $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = [Security.Principal.WindowsPrincipal]::new($identity) @@ -39,7 +51,12 @@ function Assert-ProtectedPath([string]$Path, [bool]$AllowOwnerWrite = $false) { if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "Refusing reparse path: $Path" } $acl = Get-Acl -LiteralPath $Path $ownerSid = ([Security.Principal.NTAccount]$acl.Owner).Translate([Security.Principal.SecurityIdentifier]).Value - $approvedOwners = @('S-1-5-18', 'S-1-5-32-544', $identity.User.Value) + $trustedInstaller = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464' + if ($AllowOwnerWrite) { + $approvedOwners = @('S-1-5-18', 'S-1-5-32-544', $identity.User.Value) + } else { + $approvedOwners = @('S-1-5-18', 'S-1-5-32-544', $trustedInstaller) + } if ($ownerSid -notin $approvedOwners) { throw "Protected path has an unapproved owner: $Path" } if ($AllowOwnerWrite) { $allowed = @('S-1-5-18', 'S-1-5-32-544', $identity.User.Value) @@ -59,50 +76,62 @@ function Assert-ProtectedPath([string]$Path, [bool]$AllowOwnerWrite = $false) { } else { $writableUntrusted = @($acl.Access | Where-Object { $_.AccessControlType -eq 'Allow' -and - ($_.FileSystemRights.ToString() -match 'Write|Modify|FullControl') -and - $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -notin @('S-1-5-18', 'S-1-5-32-544') + (([int]$_.FileSystemRights -band [int]$mutationRights) -ne 0) -and + $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -notin @('S-1-5-18', 'S-1-5-32-544', $trustedInstaller) }) if ($writableUntrusted.Count -gt 0) { throw "Protected path grants write access outside SYSTEM/Administrators: $Path" } } } -function Assert-TrustedExecutable([string]$Path) { +function Set-TrustedCodeOwner([string]$Path) { + $acl = Get-Acl -LiteralPath $Path + $administratorSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') + $acl.SetOwner($administratorSid) + Set-Acl -LiteralPath $Path -AclObject $acl +} +function Assert-TrustedPath([string]$Path, [bool]$ParentsOnly = $false) { $item = Get-Item -LiteralPath $Path -Force - if ($item -isnot [IO.FileInfo] -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { - throw "Refusing missing or reparse executable: $Path" + if (($item -isnot [IO.FileInfo] -and $item -isnot [IO.DirectoryInfo]) -or + ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { + throw "Refusing missing, non-filesystem, or reparse protected path: $Path" } $trustedInstaller = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464' - $current = $item + $current = if ($ParentsOnly) { $item.Parent } else { $item } + $isLeaf = -not $ParentsOnly while ($null -ne $current) { if (($current.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { - throw "Executable path contains a reparse point: $($current.FullName)" + throw "Protected path contains a reparse point: $($current.FullName)" } $acl = Get-Acl -LiteralPath $current.FullName $ownerSid = ([Security.Principal.NTAccount]$acl.Owner).Translate([Security.Principal.SecurityIdentifier]).Value if ($ownerSid -notin @('S-1-5-18', 'S-1-5-32-544', $trustedInstaller)) { - throw "Executable path has an untrusted owner: $($current.FullName)" + throw "Protected path has an untrusted owner: $($current.FullName)" } + $checkedRights = if ($isLeaf) { $mutationRights } else { $pathReplacementRights } foreach ($rule in $acl.Access) { $sid = $rule.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value if (($rule.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -ne 0) { continue } if ($rule.AccessControlType -eq 'Allow' -and - ($rule.FileSystemRights.ToString() -match 'Write|Modify|FullControl') -and + (([int]$rule.FileSystemRights -band [int]$checkedRights) -ne 0) -and $sid -notin @('S-1-5-18', 'S-1-5-32-544', $trustedInstaller)) { - throw "Executable path grants write access outside SYSTEM/Administrators/TrustedInstaller: $($current.FullName)" + throw "Protected path grants replacement/write access outside trusted system owners: $($current.FullName)" } } $current = $current.Parent + $isLeaf = $false } } -foreach ($tool in @($git, $ssh, $powershell)) { Assert-TrustedExecutable $tool } +foreach ($tool in @($python, $git, $ssh, $powershell)) { Assert-TrustedPath $tool } Assert-ProtectedPath (Split-Path -Parent $python) Assert-ProtectedPath $python if (-not (Test-Path -LiteralPath $appRoot -PathType Container)) { throw 'Protected receiver directory is missing; provision it through the reviewed owner procedure first.' } +Assert-TrustedPath $appRoot Assert-ProtectedPath $appRoot if (Test-Path -LiteralPath $app) { throw 'Versioned receiver destination already exists; inspect it manually instead of overwriting.' } if (-not (Test-Path -LiteralPath $programData -PathType Container)) { throw 'Protected ProgramData directory is missing; provision it through the reviewed owner procedure first.' } Assert-ProtectedPath $programData -AllowOwnerWrite $true +Assert-TrustedPath $programData -ParentsOnly $true if (Test-Path -LiteralPath $trigger) { Assert-ProtectedPath $trigger -AllowOwnerWrite $true } if (Test-Path -LiteralPath $trigger) { $triggerItem = Get-Item -LiteralPath $trigger @@ -127,20 +156,193 @@ if (Test-Path -LiteralPath $autoApply) { } } -$paths = @( - @{ Source = (Join-Path $repo 'infra\backup\receive_external.py'); Name = 'receive_external.py' }, - @{ Source = (Join-Path $repo 'infra\backup\archive.py'); Name = 'archive.py' }, - @{ Source = (Join-Path $repo 'infra\backup\external_session.py'); Name = 'external_session.py' }, - @{ Source = (Join-Path $repo 'infra\deploy\windows_release_launcher.py'); Name = 'windows_release_launcher.py' } -) -foreach ($entry in $paths) { - if (-not (Test-Path -LiteralPath $entry.Source -PathType Leaf)) { throw "Bootstrap source is missing: $($entry.Name)" } +function Read-BoundedZipEntry($Entry, [long]$Maximum) { + if ($Entry.Length -gt $Maximum) { throw "Receiver bundle entry exceeds its size limit: $($Entry.FullName)" } + $inputStream = $Entry.Open() + $buffer = [IO.MemoryStream]::new() + try { + $chunk = New-Object byte[] 8192 + while (($count = $inputStream.Read($chunk, 0, $chunk.Length)) -gt 0) { + if ($buffer.Length + $count -gt $Maximum) { throw "Receiver bundle entry exceeds its size limit: $($Entry.FullName)" } + $buffer.Write($chunk, 0, $count) + } + if ($buffer.Length -ne $Entry.Length) { throw "Receiver bundle entry length is invalid: $($Entry.FullName)" } + return ,$buffer.ToArray() + } finally { + $inputStream.Dispose() + $buffer.Dispose() + } } -$null = New-Item -ItemType Directory -Path $app +function Get-LowerHex([byte[]]$Bytes, [bool]$UseSha1 = $false) { + $algorithm = if ($UseSha1) { [Security.Cryptography.SHA1]::Create() } else { [Security.Cryptography.SHA256]::Create() } + try { return [BitConverter]::ToString($algorithm.ComputeHash($Bytes)).Replace('-', '').ToLowerInvariant() } + finally { $algorithm.Dispose() } +} +function Get-GitObjectHex([string]$Kind, [byte[]]$Bytes) { + $header = [Text.Encoding]::ASCII.GetBytes("$Kind $($Bytes.Length)`0") + $payload = New-Object byte[] ($header.Length + $Bytes.Length) + [Array]::Copy($header, 0, $payload, 0, $header.Length) + [Array]::Copy($Bytes, 0, $payload, $header.Length, $Bytes.Length) + return Get-LowerHex -Bytes $payload -UseSha1 $true +} +function Get-GitTreeEntries([byte[]]$Bytes) { + $entries = @{} + $offset = 0 + $utf8Strict = [Text.UTF8Encoding]::new($false, $true) + while ($offset -lt $Bytes.Length) { + $space = [Array]::IndexOf($Bytes, [byte]32, $offset) + if ($space -lt $offset) { throw 'Git tree object has a malformed mode field.' } + $nul = [Array]::IndexOf($Bytes, [byte]0, $space + 1) + if ($nul -lt $space -or $nul + 21 -gt $Bytes.Length) { throw 'Git tree object has a malformed entry.' } + $mode = [Text.Encoding]::ASCII.GetString($Bytes, $offset, $space - $offset) + $name = $utf8Strict.GetString($Bytes, $space + 1, $nul - $space - 1) + if (-not $name -or $name -in @('.', '..') -or $entries.ContainsKey($name)) { throw 'Git tree object has an invalid or duplicate name.' } + $objectBytes = New-Object byte[] 20 + [Array]::Copy($Bytes, $nul + 1, $objectBytes, 0, 20) + $entries[$name] = [PSCustomObject]@{ + mode = $mode + sha1 = [BitConverter]::ToString($objectBytes).Replace('-', '').ToLowerInvariant() + } + $offset = $nul + 21 + } + return ,$entries +} + +# The package is opened once with write/delete sharing denied. Its bytes are +# hashed and held in memory before any installation write; no checkout or Git +# command participates in this elevated stage. +$bundleItem = Get-Item -LiteralPath $BundlePath -Force +if ($bundleItem -isnot [IO.FileInfo] -or ($bundleItem.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { + throw 'Receiver bundle must be a regular non-reparse file.' +} +$bundleStream = [IO.File]::Open([IO.Path]::GetFullPath($BundlePath), [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read) +$zip = $null +$verifiedFiles = @{} +try { + if ($bundleStream.Length -le 0 -or $bundleStream.Length -gt 524288) { throw 'Receiver bundle has an invalid size.' } + $bundleHasher = [Security.Cryptography.SHA256]::Create() + try { $bundleHash = [BitConverter]::ToString($bundleHasher.ComputeHash($bundleStream)).Replace('-', '').ToLowerInvariant() } + finally { $bundleHasher.Dispose() } + if ($bundleHash -ne $ExpectedBundleSha256) { throw 'Receiver bundle SHA-256 does not match ExpectedBundleSha256.' } + $bundleStream.Position = 0 + Add-Type -AssemblyName System.IO.Compression + $zip = [System.IO.Compression.ZipArchive]::new($bundleStream, [IO.Compression.ZipArchiveMode]::Read, $true) + $expectedEntries = @('manifest.json', 'objects/commit.bin', 'objects/root-tree.bin', + 'objects/infra-tree.bin', 'objects/backup-tree.bin', 'objects/deploy-tree.bin', + 'files/archive.py', 'files/external_session.py', + 'files/receive_external.py', 'files/windows-release-trigger.example.xml', + 'files/windows_release_launcher.py') + $entryNames = @($zip.Entries | ForEach-Object { $_.FullName }) + if ($entryNames.Count -ne $expectedEntries.Count -or + (@($entryNames | Select-Object -Unique).Count -ne $expectedEntries.Count)) { + throw 'Receiver bundle contains duplicate or unexpected entries.' + } + foreach ($expectedEntry in $expectedEntries) { + if ($entryNames -cnotcontains $expectedEntry) { throw "Receiver bundle is missing an exact required entry: $expectedEntry" } + } + foreach ($zipEntry in $zip.Entries) { + $entryMode = (([long]$zipEntry.ExternalAttributes -shr 16) -band 0xFFFF) + if ($entryMode -ne 0x81A0) { throw "Receiver bundle entry has an unsafe file mode: $($zipEntry.FullName)" } + } + $manifestBytes = Read-BoundedZipEntry -Entry $zip.GetEntry('manifest.json') -Maximum 16384 + $utf8Strict = [Text.UTF8Encoding]::new($false, $true) + $manifest = $utf8Strict.GetString($manifestBytes) | ConvertFrom-Json + $manifestFields = @($manifest.PSObject.Properties.Name | Sort-Object) -join ',' + if ($manifestFields -ne 'commit,files,schema_version,trees' -or + ($manifest.schema_version -isnot [int] -and $manifest.schema_version -isnot [long]) -or + $manifest.schema_version -ne 1 -or $manifest.commit -isnot [string] -or + $manifest.commit -cne $ExpectedCommit -or $manifest.files -isnot [Array] -or + @($manifest.files).Count -ne 5 -or $manifest.trees -isnot [Array] -or @($manifest.trees).Count -ne 4) { + throw 'Receiver bundle manifest does not match the expected commit and schema.' + } + $commitBytes = Read-BoundedZipEntry -Entry $zip.GetEntry('objects/commit.bin') -Maximum 16384 + if ((Get-GitObjectHex -Kind 'commit' -Bytes $commitBytes) -cne $ExpectedCommit) { + throw 'Receiver bundle Git commit object does not match ExpectedCommit.' + } + $commitText = [Text.Encoding]::ASCII.GetString($commitBytes) + $headerEnd = $commitText.IndexOf("`n`n", [StringComparison]::Ordinal) + if ($headerEnd -lt 1) { throw 'Receiver bundle commit header is malformed.' } + $treeHeaders = [regex]::Matches($commitText.Substring(0, $headerEnd), '(?m)^tree ([0-9a-f]{40})$') + if ($treeHeaders.Count -ne 1) { throw 'Receiver bundle commit has no unique root tree reference.' } + + $treeEntries = @{} + $treeObjectNames = @{ + '' = 'objects/root-tree.bin' + infra = 'objects/infra-tree.bin' + 'infra/backup' = 'objects/backup-tree.bin' + 'infra/deploy' = 'objects/deploy-tree.bin' + } + $seenTrees = @{} + foreach ($tree in $manifest.trees) { + $treeFields = @($tree.PSObject.Properties.Name | Sort-Object) -join ',' + if ($treeFields -ne 'path,sha1' -or $tree.path -isnot [string] -or + $tree.path -cnotin @('', 'infra', 'infra/backup', 'infra/deploy') -or + $seenTrees.ContainsKey($tree.path) -or $tree.sha1 -cnotmatch '^[0-9a-f]{40}$') { + throw 'Receiver bundle tree manifest is invalid.' + } + $treeData = Read-BoundedZipEntry -Entry $zip.GetEntry($treeObjectNames[$tree.path]) -Maximum 262144 + if ((Get-GitObjectHex -Kind 'tree' -Bytes $treeData) -cne $tree.sha1) { + throw "Receiver bundle tree object identity does not match its manifest: $($tree.path)" + } + $treeEntries[$tree.path] = Get-GitTreeEntries -Bytes $treeData + $seenTrees[$tree.path] = $tree.sha1 + } + if ($seenTrees.Count -ne 4 -or $treeHeaders[0].Groups[1].Value -cne $seenTrees['']) { + throw 'Receiver bundle commit does not bind the declared root tree.' + } + $rootInfra = $treeEntries['']['infra'] + $infraBackup = $treeEntries['infra']['backup'] + $infraDeploy = $treeEntries['infra']['deploy'] + if ($rootInfra.mode -notin @('40000', '040000') -or $rootInfra.sha1 -cne $seenTrees['infra'] -or + $infraBackup.mode -notin @('40000', '040000') -or $infraBackup.sha1 -cne $seenTrees['infra/backup'] -or + $infraDeploy.mode -notin @('40000', '040000') -or $infraDeploy.sha1 -cne $seenTrees['infra/deploy']) { + throw 'Receiver bundle directory tree chain does not match the commit.' + } + $allowedFiles = @('archive.py', 'external_session.py', 'receive_external.py', + 'windows-release-trigger.example.xml', 'windows_release_launcher.py') + $seenFiles = @{} + foreach ($file in $manifest.files) { + $fileFields = @($file.PSObject.Properties.Name | Sort-Object) -join ',' + if ($fileFields -ne 'git_blob_sha1,path,sha256,size' -or $file.path -isnot [string] -or + $file.path -cnotin $allowedFiles -or $seenFiles.ContainsKey($file.path) -or + $file.git_blob_sha1 -isnot [string] -or $file.git_blob_sha1 -cnotmatch '^[0-9a-f]{40}$' -or + $file.sha256 -isnot [string] -or $file.sha256 -cnotmatch '^[0-9a-f]{64}$' -or + ($file.size -isnot [int] -and $file.size -isnot [long]) -or $file.size -lt 0 -or $file.size -gt 262144) { + throw 'Receiver bundle manifest contains an invalid file record.' + } + $entry = $zip.GetEntry("files/$($file.path)") + $data = Read-BoundedZipEntry -Entry $entry -Maximum 262144 + if ($data.Length -ne [long]$file.size -or + (Get-LowerHex -Bytes $data) -cne $file.sha256) { + throw "Receiver bundle file digest or size does not match its manifest: $($file.path)" + } + if ((Get-GitObjectHex -Kind 'blob' -Bytes $data) -cne $file.git_blob_sha1) { + throw "Receiver bundle Git blob identity does not match its manifest: $($file.path)" + } + $treePath = if ($file.path -in @('archive.py', 'external_session.py', 'receive_external.py')) { 'infra/backup' } else { 'infra/deploy' } + $treeFile = $treeEntries[$treePath][$file.path] + if ($null -eq $treeFile -or $treeFile.mode -ne '100644' -or $treeFile.sha1 -cne $file.git_blob_sha1) { + throw "Receiver bundle commit tree does not contain the exact source file: $($file.path)" + } + $seenFiles[$file.path] = $true + $verifiedFiles[$file.path] = $data + } + if ($seenFiles.Count -ne $allowedFiles.Count) { throw 'Receiver bundle manifest omitted a required file.' } +} finally { + if ($null -ne $zip) { $zip.Dispose() } + $bundleStream.Dispose() +} + +$appSecurity = Get-Acl -LiteralPath $appRoot +$appSecurity.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')) +$null = [IO.Directory]::CreateDirectory($app, $appSecurity) +Set-TrustedCodeOwner $app Assert-ProtectedPath $app -foreach ($entry in $paths) { - Copy-Item -LiteralPath $entry.Source -Destination (Join-Path $app $entry.Name) - Assert-ProtectedPath (Join-Path $app $entry.Name) +foreach ($name in @('receive_external.py', 'archive.py', 'external_session.py', 'windows_release_launcher.py')) { + $destination = Join-Path $app $name + [IO.File]::WriteAllBytes($destination, $verifiedFiles[$name]) + Set-TrustedCodeOwner $destination + Assert-ProtectedPath $destination } if (-not (Test-Path -LiteralPath $trigger)) { $config = '{"schema_version":1,"enabled":false,"repository":"D:\\Dev\\akyldash","ssh_alias":"akyldash_release"}' @@ -152,7 +354,7 @@ if (-not (Test-Path -LiteralPath $autoApply)) { Assert-ProtectedPath $trigger -AllowOwnerWrite $true Assert-ProtectedPath $autoApply -AllowOwnerWrite $true -$template = [xml](Get-Content -LiteralPath $taskTemplate -Raw) +$template = [xml][Text.Encoding]::UTF8.GetString($verifiedFiles['windows-release-trigger.example.xml']) $ns = [System.Xml.XmlNamespaceManager]::new($template.NameTable) $ns.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task') $sid = $identity.User.Value @@ -164,7 +366,7 @@ $template.SelectSingleNode('/t:Task/t:Actions/t:Exec/t:WorkingDirectory', $ns).I $template.SelectSingleNode('/t:Task/t:Triggers/t:CalendarTrigger/t:StartBoundary', $ns).InnerText = (Get-Date).AddDays(1).ToString('yyyy-MM-ddTHH:mm:ss') $templatePath = Join-Path $programData 'Akyldash-ReleaseTrigger-disabled.xml' $template.Save($templatePath) -$applyTemplate = [xml](Get-Content -LiteralPath $taskTemplate -Raw) +$applyTemplate = [xml][Text.Encoding]::UTF8.GetString($verifiedFiles['windows-release-trigger.example.xml']) $applyNs = [System.Xml.XmlNamespaceManager]::new($applyTemplate.NameTable) $applyNs.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task') $applyTemplate.SelectSingleNode('/t:Task/t:RegistrationInfo/t:URI', $applyNs).InnerText = '\Akyldash\ReleaseAutoApply' @@ -174,5 +376,5 @@ $applyTemplate.SelectSingleNode('/t:Task/t:Actions/t:Exec/t:Arguments', $applyNs $applyTemplate.SelectSingleNode('/t:Task/t:Actions/t:Exec/t:WorkingDirectory', $applyNs).InnerText = $app $applyTemplate.SelectSingleNode('/t:Task/t:Triggers/t:CalendarTrigger/t:StartBoundary', $applyNs).InnerText = (Get-Date).AddDays(1).ToString('yyyy-MM-ddTHH:mm:ss') $applyTemplate.Save((Join-Path $programData 'Akyldash-ReleaseAutoApply-disabled.xml')) -Write-Output "Prepared disabled receiver files and task template for reviewed main commit $ExpectedCommit." +Write-Output "Prepared disabled receiver files from verified source commit $ExpectedCommit." Write-Output 'No task was registered or enabled; both configuration gates remain disabled.' diff --git a/infra/deploy/prepare_windows_release_bundle.py b/infra/deploy/prepare_windows_release_bundle.py new file mode 100644 index 0000000..d177ec5 --- /dev/null +++ b/infra/deploy/prepare_windows_release_bundle.py @@ -0,0 +1,309 @@ +"""Build a small immutable Windows receiver bundle from one Git commit.""" + +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import re +import subprocess +import zipfile +from pathlib import Path + +FILES = { + "archive.py": "infra/backup/archive.py", + "external_session.py": "infra/backup/external_session.py", + "receive_external.py": "infra/backup/receive_external.py", + "windows-release-trigger.example.xml": "infra/deploy/windows-release-trigger.example.xml", + "windows_release_launcher.py": "infra/deploy/windows_release_launcher.py", +} +MAX_BUNDLE_BYTES = 512 * 1024 +MAX_FILE_BYTES = 262144 +TREE_OBJECTS = { + "": "objects/root-tree.bin", + "infra": "objects/infra-tree.bin", + "infra/backup": "objects/backup-tree.bin", + "infra/deploy": "objects/deploy-tree.bin", +} + + +def _git(repository: Path, *arguments: str) -> bytes: + result = subprocess.run( + ["git", "-C", str(repository), *arguments], + check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + ) + return result.stdout + + +def _blob_sha(data: bytes) -> str: + return _git_object_sha("blob", data) + + +def _git_object_sha(kind: str, data: bytes) -> str: + return hashlib.sha1(kind.encode("ascii") + b" " + str(len(data)).encode("ascii") + b"\0" + data).hexdigest() + + +def _tree_entry(repository: Path, tree: str, name: str) -> tuple[str, str, str]: + records = _git(repository, "ls-tree", "-z", tree, "--", name).split(b"\0") + matches = [] + for record in records: + if not record: + continue + header, raw_path = record.split(b"\t", 1) + mode, kind, object_id = header.decode("ascii").split(" ") + if raw_path.decode("utf-8") == name: + matches.append((mode, kind, object_id)) + if len(matches) != 1: + raise ValueError(f"Git tree is missing or duplicates required path: {name}") + return matches[0] + + +def _parse_git_tree(data: bytes) -> dict[str, tuple[str, str]]: + entries: dict[str, tuple[str, str]] = {} + offset = 0 + while offset < len(data): + space = data.find(b" ", offset) + nul = data.find(b"\0", space + 1) if space >= 0 else -1 + if space < offset or nul < 0 or nul + 21 > len(data): + raise ValueError("Git tree object is malformed") + mode = data[offset:space].decode("ascii") + name = data[space + 1:nul].decode("utf-8") + object_id = data[nul + 1:nul + 21].hex() + if not name or name in {".", ".."} or name in entries: + raise ValueError("Git tree object has an invalid or duplicate name") + entries[name] = (mode, object_id) + offset = nul + 21 + return entries + + +def _strict_json_object(pairs): + value = {} + for key, item in pairs: + if key in value: + raise ValueError("receiver bundle manifest has duplicate keys") + value[key] = item + return value + + +def verify_bundle(payload: bytes, expected_commit: str, expected_sha256: str) -> dict[str, bytes]: + """Verify a generated or transferred bundle before an installer consumes it.""" + if len(payload) <= 0 or len(payload) > MAX_BUNDLE_BYTES: + raise ValueError("receiver bundle has an invalid size") + if hashlib.sha256(payload).hexdigest() != expected_sha256: + raise ValueError("receiver bundle SHA-256 does not match") + if not re.fullmatch(r"[0-9a-f]{40}", expected_commit): + raise ValueError("expected commit must be a full lowercase Git SHA-1") + expected_entries = { + "manifest.json", "objects/commit.bin", *TREE_OBJECTS.values(), + *(f"files/{name}" for name in FILES), + } + try: + archive = zipfile.ZipFile(io.BytesIO(payload)) + except (zipfile.BadZipFile, OSError) as error: + raise ValueError("receiver bundle is not a valid ZIP") from error + with archive: + infos = archive.infolist() + names = [item.filename for item in infos] + if len(names) != len(expected_entries) or len(set(names)) != len(expected_entries) or set(names) != expected_entries: + raise ValueError("receiver bundle has duplicate, missing, or unexpected entries") + for item in infos: + mode = (item.external_attr >> 16) & 0xFFFF + if mode != 0o100600 or item.compress_type != zipfile.ZIP_STORED: + raise ValueError("receiver bundle entry has an unsafe mode or compression method") + maximum = 16384 if item.filename == "manifest.json" else MAX_FILE_BYTES + if item.file_size > maximum: + raise ValueError("receiver bundle entry exceeds its size limit") + contents = {item.filename: archive.read(item) for item in infos} + + try: + manifest = json.loads(contents["manifest.json"].decode("ascii"), object_pairs_hook=_strict_json_object) + except (UnicodeError, json.JSONDecodeError) as error: + raise ValueError("receiver bundle manifest is invalid") from error + if (not isinstance(manifest, dict) or set(manifest) != {"schema_version", "commit", "files", "trees"} + or type(manifest["schema_version"]) is not int or manifest["schema_version"] != 1 + or manifest["commit"] != expected_commit): + raise ValueError("receiver bundle manifest does not match the expected commit and schema") + + commit_object = contents["objects/commit.bin"] + if _git_object_sha("commit", commit_object) != expected_commit: + raise ValueError("receiver bundle commit object does not match expected SHA") + commit_header = commit_object.split(b"\n\n", 1)[0] + commit_trees = re.findall(rb"(?m)^tree ([0-9a-f]{40})$", commit_header) + if len(commit_trees) != 1: + raise ValueError("receiver bundle commit has no unique root tree") + + if not isinstance(manifest["trees"], list) or len(manifest["trees"]) != len(TREE_OBJECTS): + raise ValueError("receiver bundle tree manifest is invalid") + tree_hashes: dict[str, str] = {} + tree_entries: dict[str, dict[str, tuple[str, str]]] = {} + for record in manifest["trees"]: + if (not isinstance(record, dict) or set(record) != {"path", "sha1"} + or not isinstance(record["path"], str) or record["path"] not in TREE_OBJECTS + or record["path"] in tree_hashes + or not isinstance(record["sha1"], str) or not re.fullmatch(r"[0-9a-f]{40}", record["sha1"])): + raise ValueError("receiver bundle tree record is invalid") + path = record["path"] + data = contents[TREE_OBJECTS[path]] + if _git_object_sha("tree", data) != record["sha1"]: + raise ValueError(f"receiver bundle tree hash does not match: {path}") + tree_hashes[path] = record["sha1"] + tree_entries[path] = _parse_git_tree(data) + if set(tree_hashes) != set(TREE_OBJECTS) or tree_hashes[""].encode("ascii") != commit_trees[0]: + raise ValueError("receiver bundle commit does not bind the declared root tree") + for parent, name, child in (("", "infra", "infra"), + ("infra", "backup", "infra/backup"), + ("infra", "deploy", "infra/deploy")): + mode, child_sha = tree_entries[parent].get(name, ("", "")) + if mode not in {"40000", "040000"} or child_sha != tree_hashes[child]: + raise ValueError(f"receiver bundle directory tree chain is invalid at {parent or '/'}/{name}") + + if not isinstance(manifest["files"], list) or len(manifest["files"]) != len(FILES): + raise ValueError("receiver bundle file manifest is invalid") + verified: dict[str, bytes] = {} + for record in manifest["files"]: + if (not isinstance(record, dict) or set(record) != {"path", "git_blob_sha1", "sha256", "size"} + or not isinstance(record["path"], str) or record["path"] not in FILES or record["path"] in verified + or type(record["size"]) is not int or record["size"] < 0 or record["size"] > MAX_FILE_BYTES + or not isinstance(record["git_blob_sha1"], str) + or not re.fullmatch(r"[0-9a-f]{40}", record["git_blob_sha1"]) + or not isinstance(record["sha256"], str) + or not re.fullmatch(r"[0-9a-f]{64}", record["sha256"])): + raise ValueError("receiver bundle file record is invalid") + name = record["path"] + data = contents[f"files/{name}"] + tree_path = "infra/backup" if FILES[name].startswith("infra/backup/") else "infra/deploy" + mode, blob_sha = tree_entries[tree_path].get(name, ("", "")) + if (mode != "100644" or blob_sha != record["git_blob_sha1"] + or _git_object_sha("blob", data) != blob_sha + or hashlib.sha256(data).hexdigest() != record["sha256"] + or len(data) != record["size"]): + raise ValueError(f"receiver bundle file does not match its commit tree: {name}") + verified[name] = data + if set(verified) != set(FILES): + raise ValueError("receiver bundle omits a required source file") + return verified + + +def read_commit_files(repository: Path, commit: str) -> tuple[ + dict[str, bytes], list[dict[str, object]], dict[str, bytes], list[dict[str, str]]]: + if not re.fullmatch(r"[0-9a-f]{40}", commit): + raise ValueError("expected commit must be a full lowercase Git SHA-1") + if repository.is_symlink(): + raise ValueError("repository must be a real directory") + repository = repository.resolve(strict=True) + if not repository.is_dir(): + raise ValueError("repository must be a real directory") + if _git(repository, "cat-file", "-t", commit).strip() != b"commit": + raise ValueError("expected object is not a commit") + main_commit = _git(repository, "rev-parse", "refs/heads/main").strip().decode("ascii") + if main_commit != commit: + raise ValueError("expected commit must equal the local main branch tip") + commit_object = _git(repository, "cat-file", "commit", commit) + if _git_object_sha("commit", commit_object) != commit: + raise ValueError("commit object bytes do not match the expected SHA") + commit_header = commit_object.split(b"\n\n", 1)[0] + commit_trees = [value.decode("ascii") for value in + re.findall(rb"(?m)^tree ([0-9a-f]{40})$", commit_header)] + if len(commit_trees) != 1: + raise ValueError("commit object has no unique root tree") + tree_ids = {"": commit_trees[0]} + tree_ids["infra"] = _tree_entry(repository, tree_ids[""], "infra")[2] + tree_ids["infra/backup"] = _tree_entry(repository, tree_ids["infra"], "backup")[2] + tree_ids["infra/deploy"] = _tree_entry(repository, tree_ids["infra"], "deploy")[2] + tree_objects: dict[str, bytes] = {"objects/commit.bin": commit_object} + manifest_trees: list[dict[str, str]] = [] + for tree_path, tree_sha in sorted(tree_ids.items()): + data = _git(repository, "cat-file", "tree", tree_sha) + if _git_object_sha("tree", data) != tree_sha: + raise ValueError(f"Git tree bytes do not match their object ID: {tree_path or '/'}") + tree_objects[TREE_OBJECTS[tree_path]] = data + manifest_trees.append({"path": tree_path, "sha1": tree_sha}) + records = _git(repository, "ls-tree", "-z", commit, "--", *FILES.values()).split(b"\0") + tree_entries: dict[str, tuple[str, str, str]] = {} + for record in records: + if not record: + continue + header, raw_path = record.split(b"\t", 1) + mode, kind, object_id = header.decode("ascii").split(" ") + tree_entries[raw_path.decode("utf-8")] = (mode, kind, object_id) + if set(tree_entries) != set(FILES.values()): + raise ValueError("commit does not contain the exact receiver allowlist") + + contents: dict[str, bytes] = {} + manifest_files: list[dict[str, object]] = [] + for name, source_path in sorted(FILES.items()): + mode, kind, object_id = tree_entries[source_path] + if mode != "100644" or kind != "blob": + raise ValueError(f"receiver source is not a regular Git blob: {source_path}") + data = _git(repository, "cat-file", "blob", object_id) + if _blob_sha(data) != object_id: + raise ValueError(f"Git blob bytes do not match the commit object: {source_path}") + contents[name] = data + manifest_files.append({ + "path": name, + "git_blob_sha1": object_id, + "sha256": hashlib.sha256(data).hexdigest(), + "size": len(data), + }) + for name, source_path in FILES.items(): + parent_path = "infra/backup" if source_path.startswith("infra/backup/") else "infra/deploy" + _mode, _kind, expected_blob = tree_entries[source_path] + mode, kind, tree_blob = _tree_entry(repository, tree_ids[parent_path], name) + if mode != "100644" or kind != "blob" or tree_blob != expected_blob: + raise ValueError(f"Git tree path does not bind the expected regular source blob: {source_path}") + return contents, manifest_files, tree_objects, manifest_trees + + +def create_bundle(repository: Path, commit: str) -> bytes: + contents, manifest_files, tree_objects, manifest_trees = read_commit_files(repository, commit) + manifest = json.dumps({ + "schema_version": 1, + "commit": commit, + "files": manifest_files, + "trees": manifest_trees, + }, sort_keys=True, separators=(",", ":")).encode("ascii") + b"\n" + output = io.BytesIO() + with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as bundle: + members = [("manifest.json", manifest)] + members.extend((f"files/{key}", value) for key, value in sorted(contents.items())) + members.extend(sorted(tree_objects.items())) + for name, data in members: + entry = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + entry.compress_type = zipfile.ZIP_STORED + entry.external_attr = 0o100600 << 16 + bundle.writestr(entry, data) + result = output.getvalue() + if len(result) > MAX_BUNDLE_BYTES: + raise ValueError("receiver bundle exceeds its size limit") + verify_bundle(result, commit, hashlib.sha256(result).hexdigest()) + return result + + +def write_bundle(repository: Path, commit: str, output_path: Path) -> str: + if output_path.exists() or output_path.is_symlink(): + raise ValueError("refusing to overwrite an existing release bundle") + if not output_path.parent.is_dir() or output_path.parent.is_symlink(): + raise ValueError("release bundle output directory must already exist and be a real directory") + payload = create_bundle(repository, commit) + with output_path.open("xb") as stream: + stream.write(payload) + stream.flush() + return hashlib.sha256(payload).hexdigest() + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repository", type=Path, required=True) + parser.add_argument("--commit", required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + digest = write_bundle(args.repository, args.commit, args.output) + print(f"Prepared receiver bundle for {args.commit}") + print(f"Bundle SHA-256: {digest}") + print(f"Bundle path: {args.output.resolve()}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/infra/deploy/test_windows_release_launcher.py b/infra/deploy/test_windows_release_launcher.py index bb5d970..3343697 100644 --- a/infra/deploy/test_windows_release_launcher.py +++ b/infra/deploy/test_windows_release_launcher.py @@ -1,17 +1,257 @@ import os +import re +import shlex import subprocess import sys import tempfile import unittest import xml.etree.ElementTree as ET +import zipfile +import io +import hashlib +import json from pathlib import Path +import prepare_windows_release_bundle as release_bundle from windows_release_launcher import WINDOWS_PATH, WINDOWS_TOOLS, configure_windows_tool_environment ROOT = Path(__file__).resolve().parents[2] class WindowsReleaseBootstrapTests(unittest.TestCase): + def _installer_mutation_mask(self): + script = (ROOT / "infra/deploy/install_windows_release_client.ps1").read_text(encoding="utf-8") + match = re.search(r"\$mutationRights\s*=\s*\[System\.Security\.AccessControl\.FileSystemRights\]\((.*?)\n\)", script, re.S) + self.assertIsNotNone(match, "installer must declare one explicit FileSystemRights mutation mask") + names = set(re.findall(r"FileSystemRights\]::([A-Za-z]+)", match.group(1))) + values = { + "WriteData": 0x0002, + "AppendData": 0x0004, + "WriteExtendedAttributes": 0x0010, + "WriteAttributes": 0x0100, + "DeleteSubdirectoriesAndFiles": 0x0040, + "Delete": 0x10000, + "ChangePermissions": 0x40000, + "TakeOwnership": 0x80000, + } + self.assertEqual(names, set(values), "mutation mask must name each mutating filesystem right explicitly") + mask = 0 + for name in names: + mask |= values[name] + return script, mask, values + + def test_installer_acl_guard_rejects_each_mutation_right(self): + script, mask, rights = self._installer_mutation_mask() + trusted = {"S-1-5-18", "S-1-5-32-544", "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"} + + def safe_acl(owner, entries): + if owner not in trusted: + return False + for sid, access_type, granted, inherit_only in entries: + if inherit_only: + continue + if access_type == "Allow" and granted & mask and sid not in trusted: + return False + return True + + for name, right in rights.items(): + with self.subTest(right=name): + self.assertNotEqual(mask & right, 0) + self.assertFalse(safe_acl("S-1-5-18", [("S-1-5-11", "Allow", right, False)])) + self.assertTrue(safe_acl( + "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464", + [("S-1-5-32-544", "Allow", mask, False), ("S-1-5-11", "Allow", 0x0001, False)], + )) + self.assertTrue(safe_acl("S-1-5-18", [("S-1-5-11", "Allow", mask, True)])) + self.assertIn("([int]$_.FileSystemRights -band [int]$mutationRights)", script) + self.assertIn("([int]$rule.FileSystemRights -band [int]$checkedRights)", script) + self.assertIn("PropagationFlags]::InheritOnly", script) + owner_branch = re.search( + r"if \(\$AllowOwnerWrite\) \{\s*\$approvedOwners = @\((.*?)\)\s*\} else \{\s*\$approvedOwners = @\((.*?)\)\s*\}", + script, re.S, + ) + self.assertIsNotNone(owner_branch) + self.assertIn("$identity.User.Value", owner_branch.group(1)) + self.assertNotIn("$identity.User.Value", owner_branch.group(2)) + self.assertIn("$trustedInstaller", owner_branch.group(2)) + + def test_parent_path_guard_allows_create_sibling_but_rejects_replacement_rights(self): + script = (ROOT / "infra/deploy/install_windows_release_client.ps1").read_text(encoding="utf-8") + match = re.search(r"\$pathReplacementRights\s*=\s*\[System\.Security\.AccessControl\.FileSystemRights\]\((.*?)\n\)", script, re.S) + self.assertIsNotNone(match) + names = set(re.findall(r"FileSystemRights\]::([A-Za-z]+)", match.group(1))) + values = {"DeleteSubdirectoriesAndFiles": 0x40, "Delete": 0x10000, + "ChangePermissions": 0x40000, "TakeOwnership": 0x80000} + self.assertEqual(names, set(values)) + mask = sum(values.values()) + self.assertEqual(mask & 0x0004, 0) # AppendData/CreateDirectories on C:\ creates a sibling. + for right in values.values(): + self.assertNotEqual(mask & right, 0) + + def test_installer_source_is_hash_bound_locked_and_never_runs_git(self): + script = (ROOT / "infra/deploy/install_windows_release_client.ps1").read_text(encoding="utf-8") + self.assertIn("[IO.FileShare]::Read", script) + self.assertIn("[System.IO.Compression.ZipArchive]::new($bundleStream", script) + self.assertIn("$entryMode -ne 0x81A0", script) + self.assertIn("$bundleHash -ne $ExpectedBundleSha256", script) + self.assertIn("manifest.commit -cne $ExpectedCommit", script) + self.assertIn("Get-GitObjectHex -Kind 'blob' -Bytes $data", script) + self.assertIn("Get-GitObjectHex -Kind 'commit' -Bytes $commitBytes", script) + self.assertIn("Get-GitObjectHex -Kind 'tree' -Bytes $treeData", script) + self.assertIn("Receiver bundle commit tree does not contain the exact source file", script) + self.assertIn("objects/commit.bin", script) + self.assertIn("objects/root-tree.bin", script) + self.assertIn("$treeHeaders[0].Groups[1].Value -cne $seenTrees['']", script) + self.assertIn("$verifiedFiles[$file.path] = $data", script) + self.assertNotIn("(& $git", script) + self.assertNotIn("Start-Process", script) + self.assertNotIn("Copy-Item", script) + self.assertLess(script.index("$bundleHash -ne $ExpectedBundleSha256"), + script.index("[IO.File]::WriteAllBytes($destination, $verifiedFiles[$name])")) + self.assertLess(script.index("foreach ($tool in @($python, $git, $ssh, $powershell)) { Assert-TrustedPath $tool }"), + script.index("$bundleStream = [IO.File]::Open")) + self.assertIn("$approvedOwners = @('S-1-5-18', 'S-1-5-32-544', $trustedInstaller)", script) + self.assertIn("$approvedOwners = @('S-1-5-18', 'S-1-5-32-544', $identity.User.Value)", script) + self.assertIn("Assert-TrustedPath $appRoot", script) + self.assertIn("Assert-TrustedPath $programData -ParentsOnly $true", script) + self.assertIn("Set-TrustedCodeOwner $app", script) + self.assertIn("Set-TrustedCodeOwner $destination", script) + for name in release_bundle.FILES: + self.assertIn(f"files/{name}", script) + + def test_release_bundle_uses_exact_commit_objects_not_dirty_worktree_or_git_hooks(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + repository = root / "repo" + repository.mkdir() + self._git(repository, "init", "-b", "main") + self._git(repository, "config", "user.name", "Fixture") + self._git(repository, "config", "user.email", "fixture@example.invalid") + for name, relative in release_bundle.FILES.items(): + path = repository / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(f"committed:{name}\n".encode()) + self._git(repository, "add", "--", *release_bundle.FILES.values()) + self._git(repository, "commit", "-m", "fixture") + commit = self._git(repository, "rev-parse", "HEAD").decode().strip() + self._git(repository, "switch", "-c", "not-main") + self._git(repository, "commit", "--allow-empty", "-m", "alternate") + alternate = self._git(repository, "rev-parse", "HEAD").decode().strip() + self._git(repository, "switch", "main") + with self.assertRaisesRegex(ValueError, "local main branch tip"): + release_bundle.create_bundle(repository, alternate) + + executable_path = repository / release_bundle.FILES["archive.py"] + self._git(repository, "switch", "-c", "executable-mode") + executable_path.chmod(0o755) + self._git(repository, "add", "--", release_bundle.FILES["archive.py"]) + self._git(repository, "commit", "-m", "executable source") + executable_commit = self._git(repository, "rev-parse", "HEAD").decode().strip() + self._git(repository, "update-ref", "refs/heads/main", executable_commit) + with self.assertRaisesRegex(ValueError, "not a regular Git blob"): + release_bundle.create_bundle(repository, executable_commit) + self._git(repository, "update-ref", "refs/heads/main", commit) + self._git(repository, "switch", "main") + + symlink_path = repository / release_bundle.FILES["archive.py"] + self._git(repository, "switch", "-c", "symlink-source") + symlink_path.unlink() + symlink_path.symlink_to("missing-target") + self._git(repository, "add", "--", release_bundle.FILES["archive.py"]) + self._git(repository, "commit", "-m", "symlink source") + symlink_commit = self._git(repository, "rev-parse", "HEAD").decode().strip() + self._git(repository, "update-ref", "refs/heads/main", symlink_commit) + with self.assertRaisesRegex(ValueError, "not a regular Git blob"): + release_bundle.create_bundle(repository, symlink_commit) + self._git(repository, "update-ref", "refs/heads/main", commit) + self._git(repository, "switch", "main") + + edited = repository / release_bundle.FILES["receive_external.py"] + edited.write_bytes(b"uncommitted attacker-controlled edit\n") + hook_marker = root / "fsmonitor-ran" + hook = root / "fsmonitor.sh" + hook.write_text(f"#!/bin/sh\nprintf ran > {shlex.quote(str(hook_marker))}\n", encoding="utf-8") + hook.chmod(0o700) + self._git(repository, "config", "core.fsmonitor", str(hook)) + + payload = release_bundle.create_bundle(repository, commit) + expected_sha256 = hashlib.sha256(payload).hexdigest() + self.assertEqual(set(release_bundle.verify_bundle(payload, commit, expected_sha256)), + set(release_bundle.FILES)) + self.assertFalse(hook_marker.exists(), "bundle creation must not invoke config-driven fsmonitor hooks") + with zipfile.ZipFile(io.BytesIO(payload)) as bundle: + manifest = json.loads(bundle.read("manifest.json")) + self.assertEqual(manifest["commit"], commit) + self.assertEqual(set(member.filename for member in bundle.infolist()), + {"manifest.json", *(f"files/{name}" for name in release_bundle.FILES), + *release_bundle.TREE_OBJECTS.values(), "objects/commit.bin"}) + self.assertEqual(release_bundle._git_object_sha("commit", bundle.read("objects/commit.bin")), commit) + for tree in manifest["trees"]: + object_name = release_bundle.TREE_OBJECTS[tree["path"]] + self.assertEqual(release_bundle._git_object_sha("tree", bundle.read(object_name)), tree["sha1"]) + for name in release_bundle.FILES: + self.assertEqual(bundle.read(f"files/{name}"), f"committed:{name}\n".encode()) + for member in ("objects/commit.bin", "objects/infra-tree.bin", "files/receive_external.py"): + with self.subTest(member=member): + corrupted = self._rewrite_bundle(payload, member, lambda content: content[:-1] + bytes([content[-1] ^ 1])) + with self.assertRaises(ValueError): + release_bundle.verify_bundle(corrupted, commit, hashlib.sha256(corrupted).hexdigest()) + + traversal = self._rewrite_bundle(payload, "../escape", lambda _unused: b"outside") + with self.assertRaisesRegex(ValueError, "unexpected entries"): + release_bundle.verify_bundle(traversal, commit, hashlib.sha256(traversal).hexdigest()) + duplicate = self._rewrite_bundle(payload, "manifest.json", lambda content: content, duplicate=True) + with self.assertRaisesRegex(ValueError, "duplicate"): + release_bundle.verify_bundle(duplicate, commit, hashlib.sha256(duplicate).hexdigest()) + symlink_entry = self._rewrite_bundle(payload, "files/archive.py", lambda content: content, + external_attr=0o120777 << 16) + with self.assertRaisesRegex(ValueError, "unsafe mode"): + release_bundle.verify_bundle(symlink_entry, commit, hashlib.sha256(symlink_entry).hexdigest()) + altered_mode = self._rewrite_bundle(payload, "files/archive.py", lambda content: content, + external_attr=0o100755 << 16) + with self.assertRaisesRegex(ValueError, "unsafe mode"): + release_bundle.verify_bundle(altered_mode, commit, hashlib.sha256(altered_mode).hexdigest()) + with self.assertRaisesRegex(ValueError, "invalid size"): + release_bundle.verify_bundle(b"x" * (release_bundle.MAX_BUNDLE_BYTES + 1), commit, "0" * 64) + + @staticmethod + def _git(repository, *arguments): + return subprocess.run(["git", "-C", str(repository), *arguments], check=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout + + @staticmethod + def _rewrite_bundle(payload, target, transform, *, duplicate=False, external_attr=None): + output = io.BytesIO() + with zipfile.ZipFile(io.BytesIO(payload)) as original, zipfile.ZipFile(output, "w") as altered: + for item in original.infolist(): + content = original.read(item) + if item.filename == target: + content = transform(content) + info = zipfile.ZipInfo(item.filename, item.date_time) + info.compress_type = zipfile.ZIP_STORED + info.external_attr = external_attr if item.filename == target and external_attr is not None else item.external_attr + altered.writestr(info, content) + if duplicate and item.filename == target: + altered.writestr(info, content) + if target not in {item.filename for item in original.infolist()}: + info = zipfile.ZipInfo(target) + info.compress_type = zipfile.ZIP_STORED + info.external_attr = 0o100600 << 16 + altered.writestr(info, transform(b"")) + return output.getvalue() + + def test_installer_has_no_child_processes_and_checks_tools_before_bundle_read(self): + script = (ROOT / "infra/deploy/install_windows_release_client.ps1").read_text(encoding="utf-8") + trusted_tools = script.index("foreach ($tool in @($python, $git, $ssh, $powershell)) { Assert-TrustedPath $tool }") + bundle_open = script.index("$bundleStream = [IO.File]::Open") + self.assertLess(trusted_tools, bundle_open) + self.assertNotIn("(& $git", script) + self.assertNotIn("Start-Process", script) + self.assertNotIn("Process]::Start", script) + self.assertIn("while ($null -ne $current)", script) + self.assertIn("$current = $current.Parent", script) + self.assertIn("$ownerSid -notin @('S-1-5-18', 'S-1-5-32-544', $trustedInstaller)", script) + def test_windows_tool_environment_discards_path_and_git_overrides(self): environment = { "PATH": r"C:\Users\attacker\bin", @@ -107,7 +347,7 @@ class WindowsReleaseBootstrapTests(unittest.TestCase): self.assertIn("client-$ExpectedCommit", script) self.assertIn("--auto-apply-prepared", script) self.assertIn("Akyldash-ReleaseAutoApply-disabled.xml", script) - self.assertIn("Assert-TrustedExecutable $tool", script) + self.assertIn("Assert-TrustedPath $tool", script) self.assertIn(r"$git = 'C:\Program Files\Git\cmd\git.exe'", script) self.assertIn(r"$ssh = 'C:\Windows\System32\OpenSSH\ssh.exe'", script) self.assertIn(r"$powershell = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'", script)