fix(windows): bundle and audit app-local MSVC runtime

Deploy the official x64 redistributable DLLs into the shared MSI/ZIP payload and reject missing, debug, incompatible or shadowed CRT imports. Smoke both deployed products with isolated profiles and record loaded Qt/CRT paths.

Validate with 14 PE fixtures, PowerShell parsing, actionlint and shellcheck. Native clean-Windows acceptance remains pending.

cx
This commit is contained in:
vicrodh committed 2026-09-06 04:54:40 -06:00
1 parent 6794e15257
commit 9fd9978be2
7 files changed
+501 -58

No files matched your search

+60 -58
View File
@@ -288,7 +288,7 @@ jobs:
# (the committed .qsb carry HLSL 50 *source*; d3d11 compiles it at runtime). # (the committed .qsb carry HLSL 50 *source*; d3d11 compiles it at runtime).
# Exit code is checked (pipefail); the grep is a separate, informational pass. # Exit code is checked (pipefail); the grep is a separate, informational pass.
"$QT_ROOT_DIR/bin/windeployqt.exe" --release --qmldir crates/qbz-qt/qml \ "$QT_ROOT_DIR/bin/windeployqt.exe" --release --qmldir crates/qbz-qt/qml \
--no-translations --no-opengl-sw "$DIST/qbz.exe" 2>&1 | tee windeploy.log --no-translations --no-opengl-sw --no-compiler-runtime "$DIST/qbz.exe" 2>&1 | tee windeploy.log
grep -iE 'error|warning' windeploy.log || true grep -iE 'error|warning' windeploy.log || true
# Nothing uses Qt SQL, Qt TLS (rustls) or network-information. # Nothing uses Qt SQL, Qt TLS (rustls) or network-information.
rm -rf "$DIST/sqldrivers" "$DIST/tls" "$DIST/networkinformation" rm -rf "$DIST/sqldrivers" "$DIST/tls" "$DIST/networkinformation"
@@ -321,43 +321,14 @@ jobs:
# Hard fail, not a warning — plan A task 14 adds licenses/. # Hard fail, not a warning — plan A task 14 adds licenses/.
if [ ! -d licenses ]; then echo "::error::licenses/ (Qt LGPL notice) is missing; refusing to package Qt without it"; exit 1; fi if [ ! -d licenses ]; then echo "::error::licenses/ (Qt LGPL notice) is missing; refusing to package Qt without it"; exit 1; fi
cp -r licenses "$DIST/licenses" cp -r licenses "$DIST/licenses"
# offscreen platform plugin: smoke only; removed before packaging.
cp "$QT_ROOT_DIR/plugins/platforms/qoffscreen.dll" "$DIST/platforms/"
du -sh "$DIST" du -sh "$DIST"
# THE gate: the deployed directory boots without the Qt install. Pass = # Both products harvest this exact app-local runtime. Audit every EXE,
# >= 10 log lines, zero QML/loader complaints, core initialized (login # DLL and plugin (normal + delay imports) before making either artifact.
# screen reached; `home published` needs a session CI does not have). - name: Deploy official MSVC CRT app-local and audit imports
# This is the step that catches the qrc-backslash bug (W1) as `Cannot open`.
# pwsh, not Git-Bash: MSYS `kill $!` cannot reliably stop a native
# Windows process (Sol R15), and a survivor locks the deploy dir.
- name: Offscreen smoke (the directory that ships)
shell: pwsh shell: pwsh
run: | run: ./scripts/packaging/deploy_windows_crt.ps1 -Dist dist/qbz
$ErrorActionPreference = "Stop"
$dist = "dist\qbz"
$qtRoot = $env:QT_ROOT_DIR
$qtHidden = "$qtRoot.hidden"
# Move-Item accepts a full destination path. Rename-Item's NewName
# parameter does not, so using it here can leave the Qt install live
# and turn this deployed-tree gate into a false positive.
Move-Item -LiteralPath $qtRoot -Destination $qtHidden
foreach ($v in "QT_PLUGIN_PATH","QML_IMPORT_PATH","QML2_IMPORT_PATH","QT_ROOT_DIR") { Remove-Item "Env:$v" -ErrorAction SilentlyContinue }
$env:QT_QPA_PLATFORM = "offscreen"; $env:RUST_LOG = "info"
$p = Start-Process -FilePath "$dist\qbz.exe" -RedirectStandardOutput smoke.out -RedirectStandardError smoke.err -PassThru -NoNewWindow
Start-Sleep -Seconds 45
if (-not $p.HasExited) { Stop-Process -Id $p.Id -Force; Start-Sleep 1 }
Move-Item -LiteralPath $qtHidden -Destination $qtRoot
Get-Content smoke.out, smoke.err | Set-Content smoke.log
$lines = (Get-Content smoke.log | Measure-Object -Line).Lines
Write-Host "smoke log: $lines lines"
if ($lines -lt 10) { Get-Content smoke.log; Write-Host "::error::the app did not start"; exit 1 }
$pat = 'is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed|could not be found|0xc0000135|STATUS_DLL_NOT_FOUND|This application failed to start'
$errs = Get-Content smoke.log | Where-Object { $_ -notmatch 'propertyCache' } | Select-String -Pattern $pat
if ($errs) { $errs | Select-Object -First 20; Write-Host "::error::$($errs.Count) QML/loader complaint(s) in the smoke log"; exit 1 }
if (-not (Select-String -Path smoke.log -Pattern 'QbzCore initialized' -Quiet)) { Get-Content smoke.log -Tail 20; Write-Host "::error::never reached QbzCore init"; exit 1 }
Remove-Item "$dist\platforms\qoffscreen.dll"
Write-Host "smoke OK (0 QML complaints, core initialized)"
# D4 = unsigned, so this is a no-op until a cert exists (HAVE_CERT is # D4 = unsigned, so this is a no-op until a cert exists (HAVE_CERT is
# resolved at workflow level — see the env block at the top). PLACEHOLDER # resolved at workflow level — see the env block at the top). PLACEHOLDER
# for an OV cert in a PFX: cloud-issued keys (Azure Trusted Signing, # for an OV cert in a PFX: cloud-issued keys (Azure Trusted Signing,
@@ -402,37 +373,43 @@ jobs:
-o "dist/QBZ_${VERSION}_x64.msi" -o "dist/QBZ_${VERSION}_x64.msi"
ls -la dist ls -la dist
# The MSI is exercised, not just built: install per-user (no UAC), assert # Product smoke uses qwindows from the installed payload with an isolated
# the layout + registry, launch the INSTALLED exe offscreen, uninstall, # profile/PATH. A VS runner still does not certify a clean Windows image.
# assert nothing is left. `wix msi validate` is deliberately NOT run: - name: Install / upgrade / launch / uninstall the MSI (runner smoke)
# per-user harvested components fail ICE38 by WiX design (issue #8633).
- name: Install / launch / uninstall the MSI (runner smoke)
shell: pwsh shell: pwsh
env: env:
VERSION: ${{ steps.release.outputs.version }} VERSION: ${{ steps.release.outputs.version }}
run: | run: |
$ErrorActionPreference = 'Stop'
$msi = (Resolve-Path "dist\QBZ_$($env:VERSION)_x64.msi").Path $msi = (Resolve-Path "dist\QBZ_$($env:VERSION)_x64.msi").Path
$p = Start-Process msiexec -ArgumentList "/i `"$msi`" /qn /l*v install.log" -Wait -PassThru
if ($p.ExitCode -ne 0) { Get-Content install.log -Tail 60; Write-Host "::error::msiexec /i exit $($p.ExitCode)"; exit 1 }
$root = "$env:LOCALAPPDATA\Programs\QBZ" $root = "$env:LOCALAPPDATA\Programs\QBZ"
foreach ($f in "qbz.exe","platforms\qwindows.dll","qml\QtQuick\Controls\Basic","imageformats\qsvg.dll","LICENSE.txt") { $installed = $false
if (-not (Test-Path "$root\$f")) { Write-Host "::error::installed layout is missing $f"; exit 1 } try {
foreach ($stage in @('install','upgrade')) {
$p = Start-Process msiexec -ArgumentList "/i `"$msi`" /qn /l*v $stage.log" -Wait -PassThru
if ($p.ExitCode -ne 0) { Get-Content "$stage.log" -Tail 60; throw "msiexec $stage exit $($p.ExitCode)" }
$installed = $true
}
foreach ($f in @('qbz.exe','platforms\qwindows.dll','qml\QtQuick\Controls\Basic','imageformats\qsvg.dll','LICENSE.txt')) {
if (-not (Test-Path "$root\$f")) { throw "Installed layout is missing $f" }
}
if (-not (Test-Path 'HKCU:\Software\Classes\qbz')) { throw 'qbz protocol key missing' }
if (-not (Test-Path "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\QBZ.lnk")) { throw 'Start-menu shortcut missing' }
$sourceHash = (Get-FileHash 'dist/qbz/licenses/msvc-runtime.json').Hash
if ((Get-FileHash "$root/licenses/msvc-runtime.json").Hash -ne $sourceHash) { throw 'MSI CRT inventory differs from shared payload' }
python scripts/packaging/windows_crt.py $root --report windows-msi-imports.json
if ($LASTEXITCODE -ne 0) { throw 'Installed MSI CRT audit failed' }
./scripts/packaging/smoke_windows_deploy.ps1 -Directory $root -LogPrefix inst
} }
foreach ($protocol in "qbz") { finally {
if (-not (Test-Path "HKCU:\Software\Classes\$protocol")) { Write-Host "::error::$protocol protocol key missing"; exit 1 } if ($installed) {
$u = Start-Process msiexec -ArgumentList "/x `"$msi`" /qn /l*v uninstall.log" -Wait -PassThru
if ($u.ExitCode -ne 0) { Get-Content uninstall.log -Tail 60; throw "msiexec uninstall exit $($u.ExitCode)" }
}
} }
if (-not (Test-Path "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\QBZ.lnk")) { Write-Host "::error::Start-menu shortcut missing"; exit 1 } if (Test-Path "$root\qbz.exe") { throw 'Uninstall left qbz.exe' }
$env:QT_QPA_PLATFORM = "offscreen"; $env:RUST_LOG = "info" if (Test-Path 'HKCU:\Software\Classes\qbz') { throw 'Uninstall left the qbz protocol key' }
$app = Start-Process "$root\qbz.exe" -RedirectStandardOutput inst.out -RedirectStandardError inst.err -PassThru -NoNewWindow Write-Host 'MSI install/upgrade/GUI launch/uninstall OK'
Start-Sleep 25; if (-not $app.HasExited) { Stop-Process -Id $app.Id -Force; Start-Sleep 1 }
if (-not (Select-String -Path inst.out,inst.err -Pattern 'QbzCore initialized' -Quiet)) { Get-Content inst.out,inst.err -Tail 30; Write-Host "::error::installed app never reached QbzCore init"; exit 1 }
$u = Start-Process msiexec -ArgumentList "/x `"$msi`" /qn /l*v uninstall.log" -Wait -PassThru
if ($u.ExitCode -ne 0) { Get-Content uninstall.log -Tail 60; Write-Host "::error::msiexec /x exit $($u.ExitCode)"; exit 1 }
if (Test-Path "$root\qbz.exe") { Write-Host "::error::uninstall left $root\qbz.exe"; exit 1 }
foreach ($protocol in "qbz") {
if (Test-Path "HKCU:\Software\Classes\$protocol") { Write-Host "::error::uninstall left the $protocol protocol key"; exit 1 }
}
Write-Host "MSI install/launch/uninstall OK"
- name: Sign MSI - name: Sign MSI
if: ${{ env.HAVE_CERT == 'true' }} if: ${{ env.HAVE_CERT == 'true' }}
@@ -452,6 +429,31 @@ jobs:
run: | run: |
Compress-Archive -Path dist\qbz\* -DestinationPath "dist\qbz_$($env:VERSION)_windows_x64.zip" Compress-Archive -Path dist\qbz\* -DestinationPath "dist\qbz_$($env:VERSION)_windows_x64.zip"
Copy-Item "crates\target\$env:TARGET\release\qbz.pdb" "dist\qbz_$($env:VERSION)_windows_x64.pdb" Copy-Item "crates\target\$env:TARGET\release\qbz.pdb" "dist\qbz_$($env:VERSION)_windows_x64.pdb"
$unpacked = Join-Path $env:RUNNER_TEMP ('qbz-portable-' + [guid]::NewGuid())
try {
Expand-Archive -LiteralPath "dist\qbz_$($env:VERSION)_windows_x64.zip" -DestinationPath $unpacked
if ((Get-FileHash "$unpacked/licenses/msvc-runtime.json").Hash -ne (Get-FileHash 'dist/qbz/licenses/msvc-runtime.json').Hash) { throw 'ZIP CRT inventory differs from shared payload' }
python scripts/packaging/windows_crt.py $unpacked --report windows-zip-imports.json
if ($LASTEXITCODE -ne 0) { throw 'Portable ZIP CRT audit failed' }
./scripts/packaging/smoke_windows_deploy.ps1 -Directory $unpacked -LogPrefix portable
}
finally { if (Test-Path $unpacked) { Remove-Item -LiteralPath $unpacked -Recurse -Force } }
- name: Upload deployment evidence
if: always()
uses: actions/upload-artifact@v7
with:
name: qbz-windows-deployment-checks
retention-days: 14
if-no-files-found: ignore
path: |
windows-*-imports.json
inst.*
portable.*
install.log
upgrade.log
uninstall.log
dist/qbz/licenses/msvc-runtime.json
- name: Upload artifacts - name: Upload artifacts
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v7
+4
View File
@@ -39,6 +39,8 @@ on:
- "scripts/qt-*.py" - "scripts/qt-*.py"
- "scripts/qt-*.sh" - "scripts/qt-*.sh"
- "scripts/test_qt_build_gates.py" - "scripts/test_qt_build_gates.py"
- "scripts/packaging/windows_crt.py"
- "scripts/packaging/test_windows_crt.py"
- "scripts/qml-audits/**" - "scripts/qml-audits/**"
- ".github/workflows/test-crates.yml" - ".github/workflows/test-crates.yml"
push: push:
@@ -50,6 +52,8 @@ on:
- "scripts/qt-*.py" - "scripts/qt-*.py"
- "scripts/qt-*.sh" - "scripts/qt-*.sh"
- "scripts/test_qt_build_gates.py" - "scripts/test_qt_build_gates.py"
- "scripts/packaging/windows_crt.py"
- "scripts/packaging/test_windows_crt.py"
- "scripts/qml-audits/**" - "scripts/qml-audits/**"
- ".github/workflows/test-crates.yml" - ".github/workflows/test-crates.yml"
workflow_dispatch: workflow_dispatch:
+3
View File
@@ -48,6 +48,9 @@ say() { printf '[cargo-test] %s\n' "$*"; }
say "gate: native Qt SDK cache and crash-aware smoke regressions" say "gate: native Qt SDK cache and crash-aware smoke regressions"
python3 scripts/test_qt_build_gates.py python3 scripts/test_qt_build_gates.py
say "gate: Windows app-local CRT import regressions"
python3 scripts/packaging/test_windows_crt.py
say "gate: all eight gettext catalogs" say "gate: all eight gettext catalogs"
for locale in en es de fr pt ru ja nl; do for locale in en es de fr pt ru ja nl; do
msgfmt --check --output-file=/dev/null "crates/qbz-i18n/translations/$locale/LC_MESSAGES/qbz-ui.po" msgfmt --check --output-file=/dev/null "crates/qbz-i18n/translations/$locale/LC_MESSAGES/qbz-ui.po"
+54
View File
@@ -0,0 +1,54 @@
# Common app-local payload for the per-user MSI and portable ZIP. No installer,
# elevation, System32 copies, debug runtime or UCRT/API-set bundling.
param([Parameter(Mandatory=$true)][string]$Dist)
$ErrorActionPreference = 'Stop'
$distRoot = (Resolve-Path -LiteralPath $Dist).Path
if (-not $env:VCToolsRedistDir -or -not $env:VCToolsVersion) {
throw 'Run from the configured MSVC build environment (VCToolsRedistDir/VCToolsVersion required)'
}
$redist = (Resolve-Path -LiteralPath $env:VCToolsRedistDir).Path
$roots = @(Get-ChildItem -LiteralPath (Join-Path $redist 'x64') -Directory |
Where-Object { $_.Name -match '^Microsoft\.VC\d+\.CRT$' })
if ($roots.Count -ne 1) { throw "Expected one official x64 CRT directory in $redist; found $($roots.Count)" }
$source = $roots[0]
$files = @(Get-ChildItem -LiteralPath $source.FullName -Filter '*.dll' -File)
if ($files.Count -eq 0) { throw 'Official CRT directory contains no DLLs' }
$entries = @()
foreach ($file in $files) {
if ($file.Name -notmatch '^(msvc[pr]|vcruntime|vccorlib|concrt)\d.*\.dll$' -or $file.Name -match 'd\.dll$') {
throw "Unexpected DLL in release CRT directory: $($file.Name)"
}
$info = $file.VersionInfo
$fileVersion = "$($info.FileMajorPart).$($info.FileMinorPart).$($info.FileBuildPart).$($info.FilePrivatePart)"
if ([version]$fileVersion -lt [version]$env:VCToolsVersion) { throw "CRT $fileVersion predates toolset $env:VCToolsVersion" }
Copy-Item -LiteralPath $file.FullName -Destination $distRoot -Force
$entries += [ordered]@{ name=$file.Name; source=$file.FullName; file_version=$fileVersion;
sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant();
copyright=$info.LegalCopyright }
}
$licenses = Join-Path $distRoot 'licenses'
New-Item -ItemType Directory -Path $licenses -Force | Out-Null
[ordered]@{ architecture='x64'; toolset_version=$env:VCToolsVersion;
source=$source.FullName; files=$entries } | ConvertTo-Json -Depth 5 |
Set-Content -LiteralPath (Join-Path $licenses 'msvc-runtime.json') -Encoding utf8
@'
Microsoft Visual C++ Runtime (x64, application-local deployment)
These runtime DLLs come from the official Visual Studio redistributable
folder. Original version and copyright resources are retained in each DLL;
msvc-runtime.json records their origin, versions, hashes and copyright.
QBZ updates these copies when updating its MSVC runtime dependency.
Microsoft redistribution terms and list:
https://learn.microsoft.com/en-us/visualstudio/releases/2022/redistribution
Deployment documentation:
https://learn.microsoft.com/en-us/cpp/windows/determining-which-dlls-to-redistribute
'@ | Set-Content -LiteralPath (Join-Path $licenses 'MSVC-RUNTIME-NOTICE.txt') -Encoding utf8
# Retain any notices accompanying the selected official CRT directory.
foreach ($folder in @($source.FullName, $redist)) {
foreach ($notice in @(Get-ChildItem -LiteralPath $folder -File | Where-Object { $_.Name -match '(?i)(license|notice|redist).*\.txt$' })) {
Copy-Item -LiteralPath $notice.FullName -Destination (Join-Path $licenses "MSVC-$($notice.Name)") -Force
}
}
python scripts/packaging/windows_crt.py $distRoot --report windows-crt-imports.json
if ($LASTEXITCODE -ne 0) { throw 'MSVC app-local import audit failed' }
@@ -0,0 +1,70 @@
# Smoke the actual deployed product. qoffscreen.dll is neither injected nor
# resolved from the SDK. A development machine still does not prove clean OS.
param(
[Parameter(Mandatory=$true)][string]$Directory,
[Parameter(Mandatory=$true)][string]$LogPrefix,
[int]$Seconds = 75
)
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path -LiteralPath $Directory).Path
$prefix = [IO.Path]::GetFullPath($LogPrefix)
$manifest = Get-Content -LiteralPath (Join-Path $root 'licenses/msvc-runtime.json') -Raw | ConvertFrom-Json
# QML/platform/image plugins do not all have a Qt6-prefixed filename.
$qtModules = @(Get-ChildItem -LiteralPath $root -Recurse -Filter '*.dll' -File |
Where-Object { $_.DirectoryName -ne $root -or $_.Name -match '^Qt6' } | ForEach-Object { $_.Name })
$profile = Join-Path ([IO.Path]::GetTempPath()) ('qbz-deploy-' + [guid]::NewGuid())
New-Item -ItemType Directory -Path $profile | Out-Null
$names = @('PATH','APPDATA','LOCALAPPDATA','QT_PLUGIN_PATH','QML_IMPORT_PATH','QML2_IMPORT_PATH',
'QT_ROOT_DIR','QTDIR','QT_QPA_PLATFORM_PLUGIN_PATH','QT_QPA_PLATFORM','QSG_RHI_BACKEND',
'QT_QUICK_BACKEND','QBZ_RENDERER','RUST_LOG')
$saved = @{}
foreach ($name in $names) { $saved[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') }
$app = $null
try {
foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null, 'Process') }
$env:PATH = "$env:SystemRoot\System32;$env:SystemRoot"
$env:APPDATA = Join-Path $profile 'roaming'
$env:LOCALAPPDATA = Join-Path $profile 'local'
New-Item -ItemType Directory -Path $env:APPDATA,$env:LOCALAPPDATA | Out-Null
$env:QT_QPA_PLATFORM = 'windows'
$env:RUST_LOG = 'info'
$app = Start-Process -FilePath (Join-Path $root 'qbz.exe') -WorkingDirectory $root `
-RedirectStandardOutput "$prefix.out" -RedirectStandardError "$prefix.err" -PassThru
$clock = [Diagnostics.Stopwatch]::StartNew()
while ($clock.Elapsed.TotalSeconds -lt $Seconds) {
if ($app.HasExited) { throw "Product exited before smoke deadline: $($app.ExitCode)" }
Start-Sleep -Milliseconds 250
$app.Refresh()
}
if ($app.MainWindowHandle -eq 0) { throw 'Product did not create a visible native window' }
$modules = @($app.Modules | ForEach-Object { [ordered]@{ name=$_.ModuleName; path=$_.FileName } })
$modules | ConvertTo-Json | Set-Content -LiteralPath "$prefix.modules.json"
foreach ($entry in $modules) {
$isCrt = @($manifest.files | Where-Object { $_.name -ieq $entry.name }).Count -gt 0
if ($isCrt -or $entry.name -in $qtModules) {
if (-not $entry.path.StartsWith($root + '\', [StringComparison]::OrdinalIgnoreCase)) {
throw "Product resolved $($entry.name) outside deployment: $($entry.path)"
}
}
}
foreach ($required in @('qwindows.dll','Qt6Core.dll','vcruntime140.dll')) {
if (-not ($modules | Where-Object { $_.name -ieq $required })) { throw "Expected loaded module missing: $required" }
}
}
finally {
if ($null -ne $app -and -not $app.HasExited) {
Stop-Process -Id $app.Id -Force
$app.WaitForExit(5000) | Out-Null
}
foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $saved[$name], 'Process') }
Remove-Item -LiteralPath $profile -Recurse -Force
if ((Test-Path "$prefix.out") -and (Test-Path "$prefix.err")) {
Get-Content "$prefix.out","$prefix.err" | Set-Content "$prefix.log"
}
}
$lines = @(Get-Content -LiteralPath "$prefix.log")
$pattern = 'is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed|could not be found|0xc0000135|STATUS_DLL_NOT_FOUND|This application failed to start'
$errors = @($lines | Where-Object { $_ -notmatch 'propertyCache' -and $_ -match $pattern })
if ($errors.Count -gt 0) { $errors | Select-Object -First 20 | Write-Host; throw 'QML/loader complaints in deployed smoke' }
if (-not ($lines -match 'QbzCore initialized')) { throw 'Product never reached core initialization' }
Write-Host "Deployed GUI smoke OK: $root, survived ${Seconds}s, app-local Qt/CRT modules"
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""PE fixtures reproduce missing/transitive/architecture CRT packaging failures."""
import hashlib
import json
from pathlib import Path
import struct
import tempfile
import unittest
import sys
sys.dont_write_bytecode = True
from windows_crt import audit, pe_imports
def pe(path, imports=(), delayed=(), machine=0x8664):
# One PE32+ .rdata section. Imports are real descriptor/name layouts;
# fixtures are parser inputs, deliberately not runnable executables.
data = bytearray(4096)
data[:2] = b'MZ'
struct.pack_into('<I', data, 60, 128)
data[128:132] = b'PE\0\0'
struct.pack_into('<HH', data, 132, machine, 1)
struct.pack_into('<H', data, 148, 240)
optional = 152
struct.pack_into('<HBB', data, optional, 0x20b, 14, 44)
struct.pack_into('<Q', data, optional + 24, 0x140000000)
struct.pack_into('<I', data, optional + 60, 512)
struct.pack_into('<I', data, optional + 108, 16)
section = optional + 240
struct.pack_into('<IIII', data, section + 8, 3584, 4096, 3584, 512)
names = 2048
for index, at, stride, values in ((1, 512, 20, imports), (13, 1024, 32, delayed)):
if not values:
continue
struct.pack_into('<II', data, optional + 112 + index * 8, at - 512 + 4096, (len(values) + 1) * stride)
for i, value in enumerate(values):
rva = names - 512 + 4096
if index == 1:
struct.pack_into('<IIIII', data, at + i * stride, 0, 0, 0, rva, 0)
else:
struct.pack_into('<IIIIIIII', data, at + i * stride, 1, rva, 0, 0, 0, 0, 0, 0)
encoded = value.encode() + b'\0'
data[names:names + len(encoded)] = encoded
names += len(encoded)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
class Deployment(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='qbz-crt-test-')
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
pe(self.root / 'qbz.exe', ['MSVCP140.dll', 'KERNEL32.dll'])
pe(self.root / 'msvcp140.dll', ['VCRUNTIME140.dll', 'ucrtbase.dll'])
pe(self.root / 'vcruntime140.dll')
pe(self.root / 'vcruntime140_1.dll', ['vcruntime140.dll'])
pe(self.root / 'platforms/qwindows.dll', delayed=['VCRUNTIME140_1.dll'])
self.manifest = {
'architecture': 'x64', 'toolset_version': '14.44.35207',
'files': [{'name': name, 'file_version': '14.44.35211.0',
'sha256': hashlib.sha256((self.root / name).read_bytes()).hexdigest()}
for name in ('msvcp140.dll', 'vcruntime140.dll', 'vcruntime140_1.dll')],
}
self.write_manifest()
def write_manifest(self):
path = self.root / 'licenses/msvc-runtime.json'
path.parent.mkdir(exist_ok=True)
path.write_text(json.dumps(self.manifest))
def test_complete_payload_including_delay_loaded_plugin_passes(self):
result = audit(self.root)
self.assertEqual(result['binaries'], 5)
self.assertIn({'binary': 'platforms/qwindows.dll', 'imports': 'vcruntime140_1.dll'}, result['imports'])
def test_redistributable_installer_is_not_a_dll(self):
(self.root / 'vcruntime140.dll').unlink()
(self.root / 'vc_redist.x64.exe').write_bytes(b'installer does not satisfy imports')
with self.assertRaisesRegex(ValueError, 'app-local CRT missing'):
audit(self.root)
def test_uninventoried_transitive_crt_fails(self):
pe(self.root / 'platforms/qwindows.dll', ['concrt140.dll'])
with self.assertRaisesRegex(ValueError, 'unbundled/debug CRT concrt140.dll'):
audit(self.root)
def test_missing_delay_import_fails(self):
self.manifest['files'].pop()
self.write_manifest()
(self.root / 'vcruntime140_1.dll').unlink()
with self.assertRaisesRegex(ValueError, 'vcruntime140_1.dll'):
audit(self.root)
def test_debug_import_fails(self):
pe(self.root / 'platforms/qwindows.dll', ['MSVCP140D.dll'])
with self.assertRaisesRegex(ValueError, 'unbundled/debug CRT'):
audit(self.root)
def test_wrong_architecture_in_a_plugin_fails(self):
pe(self.root / 'platforms/qwindows.dll', machine=0x14c)
with self.assertRaisesRegex(ValueError, 'expected AMD64'):
audit(self.root)
def test_debug_system_crt_import_is_rejected(self):
pe(self.root / 'platforms/qwindows.dll', ['ucrtbased.dll'])
with self.assertRaisesRegex(ValueError, 'debug system CRT'):
audit(self.root)
def test_unused_debug_crt_cannot_hide_in_payload(self):
pe(self.root / 'msvcp140d.dll')
with self.assertRaisesRegex(ValueError, 'uninventoried/debug CRT'):
audit(self.root)
def test_modified_crt_fails_source_hash(self):
with (self.root / 'vcruntime140.dll').open('ab') as stream:
stream.write(b'changed')
with self.assertRaisesRegex(ValueError, 'differs from official source'):
audit(self.root)
def test_outdated_crt_fails_toolset_check(self):
self.manifest['files'][0]['file_version'] = '14.43.1.0'
self.write_manifest()
with self.assertRaisesRegex(ValueError, 'older than build toolset'):
audit(self.root)
def test_newer_qt_linker_requires_a_newer_crt(self):
path = self.root / 'platforms/qwindows.dll'
data = bytearray(path.read_bytes())
data[155] = 45
path.write_bytes(data)
with self.assertRaisesRegex(ValueError, 'older than linker'):
audit(self.root)
def test_nested_crt_cannot_shadow_the_audited_copy(self):
pe(self.root / 'platforms/msvcp140.dll')
with self.assertRaisesRegex(ValueError, 'shadows app-local'):
audit(self.root)
def test_truncated_pe_fails_closed(self):
path = self.root / 'qbz.exe'
path.write_bytes(b'MZ')
with self.assertRaisesRegex(ValueError, 'truncated PE'):
pe_imports(path)
def test_system_ucrt_is_not_required_app_local(self):
pe(self.root / 'qbz.exe', ['msvcp140.dll', 'api-ms-win-crt-runtime-l1-1-0.dll', 'msvcrt.dll'])
self.assertEqual(audit(self.root)['crt_files'], 3)
if __name__ == '__main__':
unittest.main()
+158
View File
@@ -0,0 +1,158 @@
#!/usr/bin/env python3
"""Audit MSVC imports (including delay imports) in the exact MSI/ZIP payload.
No loader search paths or System32 fallback: every non-system MSVC dependency
must resolve beside qbz.exe and match the official-redist inventory.
"""
import argparse
import hashlib
import json
from pathlib import Path
import re
import struct
CRT = re.compile(r"(?:msvc[pr]|vcruntime|vccorlib|concrt|vcomp|vcamp|mfc|mfcm)\d.*\.dll$", re.I)
DEBUG_CRT = re.compile(r"(?:d|d_[0-9]+)\.dll$", re.I)
SYSTEM_DEBUG_CRT = {'ucrtbased.dll', 'msvcrtd.dll'}
def pe_imports(path):
data = Path(path).read_bytes()
def unpack(fmt, offset):
try:
return struct.unpack_from(fmt, data, offset)
except struct.error as error:
raise ValueError(f"{path}: truncated PE") from error
if data[:2] != b'MZ':
raise ValueError(f"{path}: missing MZ header")
pe, = unpack('<I', 60)
if data[pe:pe + 4] != b'PE\0\0':
raise ValueError(f"{path}: missing PE signature")
machine, count = unpack('<HH', pe + 4)
optional_size, = unpack('<H', pe + 20)
optional = pe + 24
magic, = unpack('<H', optional)
if machine != 0x8664 or magic != 0x20b:
raise ValueError(f"{path}: expected AMD64 PE32+, got machine {machine:#x}, magic {magic:#x}")
if optional_size < 112:
raise ValueError(f"{path}: invalid optional header")
linker = unpack('BB', optional + 2)
image_base, = unpack('<Q', optional + 24)
header_size, = unpack('<I', optional + 60)
directories, = unpack('<I', optional + 108)
sections = []
for index in range(count):
section = optional + optional_size + 40 * index
_, rva, raw_size, raw = unpack('<IIII', section + 8)
sections.append((rva, raw_size, raw))
def offset(rva):
if 0 <= rva < min(header_size, len(data)):
return rva
for base, size, raw in sections:
if base <= rva < base + size and raw + rva - base < len(data):
return raw + rva - base
raise ValueError(f"{path}: unmapped RVA {rva:#x}")
def name(rva):
start = offset(rva)
end = data.find(b'\0', start, min(len(data), start + 1024))
if end < 0:
raise ValueError(f"{path}: unterminated import name")
value = data[start:end].decode('ascii').lower()
if not value or '/' in value or '\\' in value:
raise ValueError(f"{path}: invalid import name {value!r}")
return value
imports = set()
for index, stride in ((1, 20), (13, 32)):
if directories <= index:
continue
if optional_size < 112 + (index + 1) * 8:
raise ValueError(f"{path}: truncated data directories")
rva, size = unpack('<II', optional + 112 + index * 8)
if not rva and not size:
continue
if not rva or size < stride or size > len(data):
raise ValueError(f"{path}: invalid import directory")
for relative in range(0, size - stride + 1, stride):
fields = unpack('<' + 'I' * (stride // 4), offset(rva + relative))
if not any(fields):
break
dll_rva = fields[3] if index == 1 else fields[1]
if index == 13 and not fields[0] & 1:
dll_rva -= image_base
imports.add(name(dll_rva))
else:
raise ValueError(f"{path}: unterminated import directory")
return imports, linker
def version(value):
parts = tuple(int(p) for p in str(value).split('.'))
return parts + (0,) * (4 - len(parts))
def audit(root):
root = Path(root)
manifest = json.loads((root / 'licenses/msvc-runtime.json').read_text(encoding='utf-8-sig'))
if manifest['architecture'] != 'x64' or not manifest['files']:
raise ValueError('missing x64 official CRT inventory')
inventory = {}
for entry in manifest['files']:
name = entry['name'].lower()
if not CRT.fullmatch(name) or DEBUG_CRT.search(name):
raise ValueError(f'non-release CRT in inventory: {name}')
if name in inventory:
raise ValueError(f'duplicate CRT entry: {name}')
inventory[name] = entry
local = {p.name.lower(): p for p in root.iterdir() if p.is_file()}
for name, entry in inventory.items():
if name not in local:
raise ValueError(f'app-local CRT missing: {name}')
if hashlib.sha256(local[name].read_bytes()).hexdigest() != entry['sha256'].lower():
raise ValueError(f'CRT differs from official source: {name}')
if version(entry['file_version']) < version(manifest['toolset_version']):
raise ValueError(f'CRT older than build toolset: {name}')
edges = []
binaries = sorted(p for p in root.rglob('*') if p.suffix.lower() in ('.exe', '.dll'))
if not (root / 'qbz.exe').is_file():
raise ValueError('qbz.exe missing')
for binary in binaries:
imports, linker = pe_imports(binary)
if binary.name.lower() in SYSTEM_DEBUG_CRT:
raise ValueError(f'debug system CRT in payload: {binary}')
if CRT.fullmatch(binary.name) and binary.parent != root:
raise ValueError(f'CRT shadows app-local copy: {binary}')
if CRT.fullmatch(binary.name) and binary.name.lower() not in inventory:
raise ValueError(f'uninventoried/debug CRT in payload: {binary}')
for name in sorted(imports):
if name in SYSTEM_DEBUG_CRT:
raise ValueError(f'{binary.relative_to(root)} imports debug system CRT {name}')
if not CRT.fullmatch(name):
continue
if DEBUG_CRT.search(name) or name not in inventory:
raise ValueError(f'{binary.relative_to(root)} imports unbundled/debug CRT {name}')
if version(inventory[name]['file_version'])[:2] < linker:
raise ValueError(f'{binary.name}: {name} older than linker {linker}')
edges.append({'binary': str(binary.relative_to(root)), 'imports': name})
if not edges:
raise ValueError('no MSVC imports found; wrong or incomplete payload')
return {'binaries': len(binaries), 'crt_files': len(inventory), 'imports': edges}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('directory', type=Path)
parser.add_argument('--report', type=Path)
args = parser.parse_args()
report = audit(args.directory)
if args.report:
args.report.write_text(json.dumps(report, indent=2) + '\n')
print(f"CRT audit OK: {report['binaries']} AMD64 binaries, {report['crt_files']} official app-local DLLs, {len(report['imports'])} MSVC import edges")
if __name__ == '__main__':
main()