From aea1cf60aee75f9d44566a28dce24eb32f0f0f67 Mon Sep 17 00:00:00 2001 From: sloray Date: Sat, 31 Oct 2026 13:18:20 +0800 Subject: [PATCH] =?UTF-8?q?fix(build):=20=E9=BB=98=E8=AE=A4=E5=A4=8D?= =?UTF-8?q?=E7=94=A8=E8=87=AA=E7=AD=BE=E5=90=8D=E8=AF=81=E4=B9=A6=E7=AD=BE?= =?UTF-8?q?=E7=BD=B2=20Windows=20=E5=8F=91=E5=B8=83=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - fix(signing): 独立校验文件摘要、CMS 签名与 RFC 3161 时间戳,不修改系统信任库 - build(windows): 发布脚本和 CI 复用本机签名身份,交付公钥证书与真实信任状态 --- .github/workflows/build-client.yml | 12 +- README.md | 4 +- client/package.json | 3 +- client/scripts/build-windows-release.ps1 | 56 ++++++-- client/scripts/initialize-windows-signing.ps1 | 36 +++++ client/scripts/test-windows-signing.ps1 | 38 ++++- client/scripts/verify-windows-signature.ps1 | 23 +++ client/scripts/windows-signature.cs | 135 ++++++++++++++++++ client/src-tauri/tauri.conf.json | 2 +- client/src/lib/version.ts | 6 +- docs/client/client.md | 18 ++- docs/releases/changelog.json | 8 +- docs/releases/changelog.md | 13 ++ version.json | 8 +- 14 files changed, 323 insertions(+), 39 deletions(-) create mode 100644 client/scripts/initialize-windows-signing.ps1 create mode 100644 client/scripts/verify-windows-signature.ps1 create mode 100644 client/scripts/windows-signature.cs diff --git a/.github/workflows/build-client.yml b/.github/workflows/build-client.yml index fc4c663..5764d3d 100644 --- a/.github/workflows/build-client.yml +++ b/.github/workflows/build-client.yml @@ -103,9 +103,9 @@ # vt/ 和 armor/ 各自固定 ESP 工具链;client/ 固定 stable。 # vt/protocol/ 的主机测试必须显式 +stable,并清空继承自 vt/ 的 build-std。 # -# ── 没做的事 ──────────────────────────────────────────────────────────────── -# Windows 可用 runner 用户证书库中的签名身份;未配置时仅生成标注 unsigned 的测试包, -# v* 标签构建要求签名证书。有效签名仍可能遇到 SmartScreen 信誉提示。 +# ── 签名与发布 ────────────────────────────────────────────────────────────── +# Windows 发布默认创建或复用 runner 用户的自签名证书,可另设 CA 证书指纹。 +# PR 仅生成未签名预览包。自签名不建立 SmartScreen 发布者信誉。 # macOS 仍不签名、不公证,可能被 Gatekeeper 拦截。要做的话给 macOS 那几个 job 加 # APPLE_CERTIFICATE / APPLE_SIGNING_IDENTITY / APPLE_ID / APPLE_PASSWORD / # APPLE_TEAM_ID(tauri 认这些环境变量,构建步骤不用改)。也没有自动发 Release: @@ -512,15 +512,12 @@ jobs: shell: pwsh env: RMIC_WINDOWS_CERT_THUMBPRINT: ${{ vars.WINDOWS_CODE_SIGNING_THUMBPRINT }} - RMIC_RELEASE_REF: ${{ github.ref }} RMIC_EVENT_NAME: ${{ github.event_name }} run: | if ($env:RMIC_EVENT_NAME -eq 'pull_request') { ./scripts/build-windows-release.ps1 -CertificateThumbprint '' -AllowUnsigned - } elseif ($env:RMIC_WINDOWS_CERT_THUMBPRINT -or $env:RMIC_RELEASE_REF -like 'refs/tags/v*') { - ./scripts/build-windows-release.ps1 } else { - ./scripts/build-windows-release.ps1 -AllowUnsigned + ./scripts/build-windows-release.ps1 } - name: 检查安装包与主程序完整性标签 @@ -543,6 +540,7 @@ jobs: target/releases/**/RMIC-2026*setup.exe target/releases/**/*.exe.sha256 target/releases/**/windows-signature-verification.json + target/releases/**/RMIC-2026-codesign.cer # ─────────────────────────────────────────────────────────────────────────── # macOS 通用包:.app + .dmg diff --git a/README.md b/README.md index fa5c6c0..08b6bfc 100644 --- a/README.md +++ b/README.md @@ -119,10 +119,10 @@ pnpm app --target x86_64-pc-windows-msvc -- --locked --config 'unstable.build-st 生成 NSIS 安装包: ```powershell -pnpm tauri build --target x86_64-pc-windows-msvc --bundles nsis --ci -- --locked --config 'unstable.build-std=[]' +pnpm bundle:windows ``` -安装包位于 `client/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/`。显示名为 **RMIC::2026**,Windows 可执行文件和安装包使用 **RMIC-2026**。 +交付包位于 `target/releases/v<版本>+<构建号>/`,默认创建或复用本机自签名代码证书,附带公钥证书和签名校验报告;自签名不保证免除 SmartScreen 提示,配置见[Windows 构建说明](docs/client/client.md#windows-x64-构建)。显示名为 **RMIC::2026**,Windows 可执行文件和安装包使用 **RMIC-2026**。 diff --git a/client/package.json b/client/package.json index b0abcdd..4831e19 100644 --- a/client/package.json +++ b/client/package.json @@ -1,7 +1,7 @@ { "name": "rmic-2026", "private": true, - "version": "0.4.0", + "version": "0.4.1", "type": "module", "description": "RMIC::2026 —— ESP32 图传与装甲板系统的桌面端:用户端(装甲条 + 瞄准器)与裁判端(双路 + 装甲板 + 录制)", "scripts": { @@ -9,6 +9,7 @@ "build": "tsc --noEmit && vite build", "preview": "vite preview", "tauri": "tauri", + "bundle:windows": "pwsh -NoProfile -File scripts/build-windows-release.ps1", "app": "tauri dev", "check": "tsc --noEmit", "version:write": "node ../scripts/version.mjs --write", diff --git a/client/scripts/build-windows-release.ps1 b/client/scripts/build-windows-release.ps1 index b80a693..7ceb687 100644 --- a/client/scripts/build-windows-release.ps1 +++ b/client/scripts/build-windows-release.ps1 @@ -1,3 +1,4 @@ +#requires -Version 7.4 # Build with Tauri's native Authenticode signing support. No private keys or # personal signing identities are stored in the shared Tauri configuration. [CmdletBinding()] @@ -6,6 +7,7 @@ param( [string]$TimestampUrl = 'http://timestamp.digicert.com', [switch]$AllowUnsigned, [switch]$PreflightOnly, + [string]$SigningConfigPath = $env:RMIC_WINDOWS_SIGNING_CONFIG, [string]$OutputDirectory ) @@ -13,8 +15,17 @@ $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest $clientRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) $repoRoot = Split-Path -Parent $clientRoot +if (-not $SigningConfigPath) { $SigningConfigPath = Join-Path $env:LOCALAPPDATA 'RMIC-2026/signing/windows.json' } +if (-not $CertificateThumbprint -and -not $AllowUnsigned) { + if ($PreflightOnly -and -not (Test-Path -LiteralPath $SigningConfigPath)) { + throw 'A code-signing certificate is required. Initialize the local signing identity before a read-only preflight.' + } + $identity = & (Join-Path $PSScriptRoot 'initialize-windows-signing.ps1') -ConfigPath $SigningConfigPath + $CertificateThumbprint = $identity.certificateThumbprint +} $thumbprint = ($CertificateThumbprint -replace '\s', '').ToUpperInvariant() $signed = $thumbprint.Length -gt 0 +$selfSigned = $false if ($signed) { if ($thumbprint -notmatch '^[0-9A-F]{40}$') { throw 'Invalid code-signing certificate thumbprint.' } $certificate = Get-Item -LiteralPath "Cert:\CurrentUser\My\$thumbprint" -ErrorAction SilentlyContinue @@ -23,7 +34,7 @@ if ($signed) { if (-not $certificate.HasPrivateKey -or $certificate.NotBefore -gt $now -or $certificate.NotAfter -le $now) { throw 'The signing certificate needs an accessible private key and must be currently valid.' } - if ($certificate.Subject -eq $certificate.Issuer) { throw 'A self-signed certificate cannot be used as a public release identity.' } + $selfSigned = [Convert]::ToBase64String($certificate.SubjectName.RawData) -eq [Convert]::ToBase64String($certificate.IssuerName.RawData) $usageOids = @($certificate.Extensions | Where-Object { $_ -is [Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension] } | ForEach-Object { $_.EnhancedKeyUsages } | ForEach-Object { $_.Value }) @@ -39,7 +50,8 @@ if (-not [Uri]::TryCreate($TimestampUrl, [UriKind]::Absolute, [ref]$timestamp) - throw 'Timestamp URL must be an HTTP(S) server without credentials.' } if ($PreflightOnly) { - [pscustomobject]@{ signing = $signed; unsignedExplicitlyAllowed = [bool]$AllowUnsigned; digestAlgorithm = 'sha256'; tsp = $true } + [pscustomobject]@{ signing = $signed; selfSigned = $selfSigned; certificateThumbprint = $thumbprint; + unsignedExplicitlyAllowed = [bool]$AllowUnsigned; digestAlgorithm = $(if ($signed) { 'sha256' } else { $null }); tsp = $signed } return } @@ -75,24 +87,52 @@ try { $release = Join-Path $metadata.target_directory 'x86_64-pc-windows-msvc/release' $main = Join-Path $release 'cam-desktop.exe' $installer = Join-Path $release "bundle/nsis/RMIC-2026_$($version.version)_x64-setup.exe" + if ($signed) { + # Tauri signs the bundled copy, then can restore the original standalone + # executable. Sign that final output too, using the same identity. + $signTool = Get-Command signtool.exe -ErrorAction SilentlyContinue + $signToolPath = if ($signTool) { $signTool.Source } else { $null } + if (-not $signToolPath) { + $sdkRoot = (Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows Kits\Installed Roots' -Name KitsRoot10).KitsRoot10 + $sdkVersions = Get-ChildItem -LiteralPath (Join-Path $sdkRoot 'bin') -Directory | + Where-Object Name -Match '^\d+\.\d+\.\d+\.\d+$' | Sort-Object { [version]$_.Name } -Descending + foreach ($sdk in $sdkVersions) { + $candidate = Join-Path $sdk.FullName 'x64/signtool.exe' + if (Test-Path -LiteralPath $candidate) { $signToolPath = $candidate; break } + } + } + if (-not $signToolPath) { throw 'Windows SDK signtool.exe is required to sign the final standalone executable.' } + & $signToolPath sign /sha1 $thumbprint /s My /fd SHA256 /tr $TimestampUrl /td SHA256 /d RMIC-2026 $main + if ($LASTEXITCODE -ne 0) { throw 'Signing the final standalone executable failed.' } + } $signatures = @() foreach ($file in @($main, $installer)) { $signature = Get-AuthenticodeSignature -LiteralPath $file - if ($signed -and ($signature.Status -ne 'Valid' -or -not $signature.TimeStamperCertificate -or - $signature.SignerCertificate.Thumbprint -ne $thumbprint)) { - throw "The signature, signer or timestamp could not be verified: $file" + if ($signed) { + $signatures += & (Join-Path $PSScriptRoot 'verify-windows-signature.ps1') -Path $file -CertificateThumbprint $thumbprint -SelfSigned:$selfSigned + } else { + if ($signature.Status -ne 'NotSigned') { throw "Unexpected signature on explicitly unsigned output: $file" } + $signatures += @{ file = [IO.Path]::GetFileName($file); status = [string]$signature.Status; timestamped = $false } } - if (-not $signed -and $signature.Status -ne 'NotSigned') { throw "Unexpected signature on explicitly unsigned output: $file" } - $signatures += @{ file = [IO.Path]::GetFileName($file); status = [string]$signature.Status; timestamped = $null -ne $signature.TimeStamperCertificate } } - $suffix = if ($signed) { '' } else { '-unsigned' } + $suffix = if ($selfSigned) { '-self-signed' } elseif ($signed) { '' } else { '-unsigned' } $delivery = Join-Path $OutputDirectory "RMIC-2026_${label}_windows-x64${suffix}-setup.exe" Copy-Item -LiteralPath $installer -Destination $delivery & icacls.exe $delivery /setintegritylevel M | Out-Null if ($LASTEXITCODE -ne 0) { throw 'Cannot set installer Medium integrity label.' } $hash = (Get-FileHash -LiteralPath $delivery -Algorithm SHA256).Hash.ToLowerInvariant() [IO.File]::WriteAllText("$delivery.sha256", "$hash $([IO.Path]::GetFileName($delivery))`n", $utf8) + $publicCertificate = $null + if ($signed) { + $certPath = Join-Path $OutputDirectory 'RMIC-2026-codesign.cer' + [IO.File]::WriteAllBytes($certPath, $certificate.Export([Security.Cryptography.X509Certificates.X509ContentType]::Cert)) + $publicCertificate = @{ file = 'RMIC-2026-codesign.cer'; subject = $certificate.Subject; + expiresUtc = $certificate.NotAfter.ToUniversalTime().ToString('o'); + sha256 = (Get-FileHash -LiteralPath $certPath -Algorithm SHA256).Hash.ToLowerInvariant() } + } $report = @{ version = $label; installer = $delivery; sha256 = $hash; signed = $signed; + selfSigned = $selfSigned; certificateThumbprint = $thumbprint; + publicCertificate = $publicCertificate; signatures = $signatures; smartScreenReputationVerified = $false } [IO.File]::WriteAllText((Join-Path $OutputDirectory 'windows-signature-verification.json'), ($report | ConvertTo-Json -Depth 6), $utf8) $report | ConvertTo-Json -Depth 6 diff --git a/client/scripts/initialize-windows-signing.ps1 b/client/scripts/initialize-windows-signing.ps1 new file mode 100644 index 0000000..a346cb5 --- /dev/null +++ b/client/scripts/initialize-windows-signing.ps1 @@ -0,0 +1,36 @@ +#requires -Version 7.4 +# Keep the non-exportable private key in CurrentUser/My. Never install a root. +[CmdletBinding()] +param([string]$ConfigPath = $env:RMIC_WINDOWS_SIGNING_CONFIG) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +if (-not $ConfigPath) { $ConfigPath = Join-Path $env:LOCALAPPDATA 'RMIC-2026/signing/windows.json' } +if (Test-Path -LiteralPath $ConfigPath) { + $saved = Get-Content -LiteralPath $ConfigPath -Raw | ConvertFrom-Json + if ($saved.schema -ne 1 -or $saved.certificateThumbprint -notmatch '^[0-9A-F]{40}$') { + throw 'Invalid saved Windows signing identity. Restore the local signing configuration.' + } + $cert = Get-Item -LiteralPath "Cert:\CurrentUser\My\$($saved.certificateThumbprint)" -ErrorAction SilentlyContinue + if (-not $cert -or -not $cert.HasPrivateKey -or $cert.NotAfter -le (Get-Date)) { + throw 'Saved signing certificate/key is missing or expired. Restore the original identity or explicitly provision a replacement; it will not be silently rotated.' + } + $saved + return +} +$existing = @(Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Where-Object FriendlyName -eq 'RMIC-2026 self-signed code signing') +if ($existing.Count -gt 1) { throw 'Multiple RMIC signing identities exist. Select one explicitly with RMIC_WINDOWS_CERT_THUMBPRINT.' } +if ($existing.Count -eq 1) { + $cert = $existing[0] + if (-not $cert.HasPrivateKey -or $cert.NotAfter -le (Get-Date)) { throw 'Existing RMIC signing identity is unusable; provision a replacement explicitly.' } +} else { + $cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject 'CN=RMIC-2026 Self-signed Code Signing' ` + -FriendlyName 'RMIC-2026 self-signed code signing' -KeyAlgorithm RSA -KeyLength 3072 ` + -HashAlgorithm SHA256 -KeyUsage DigitalSignature -KeyExportPolicy NonExportable ` + -Provider 'Microsoft Software Key Storage Provider' -CertStoreLocation 'Cert:\CurrentUser\My' ` + -NotBefore (Get-Date).AddMinutes(-5) -NotAfter (Get-Date).AddYears(3) +} +$saved = [ordered]@{ schema = 1; certificateThumbprint = $cert.Thumbprint; kind = 'self-signed'; + subject = $cert.Subject; expiresUtc = $cert.NotAfter.ToUniversalTime().ToString('o') } +New-Item -ItemType Directory -Force -Path (Split-Path -Parent ([IO.Path]::GetFullPath($ConfigPath))) | Out-Null +[IO.File]::WriteAllText([IO.Path]::GetFullPath($ConfigPath), ($saved | ConvertTo-Json), [Text.UTF8Encoding]::new($false)) +[pscustomobject]$saved diff --git a/client/scripts/test-windows-signing.ps1 b/client/scripts/test-windows-signing.ps1 index 68e6ee8..3c2bb1d 100644 --- a/client/scripts/test-windows-signing.ps1 +++ b/client/scripts/test-windows-signing.ps1 @@ -1,5 +1,5 @@ [CmdletBinding()] -param() +param([string]$SignedFixture, [string]$CertificateThumbprint, [string]$UntimestampedFixture) $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest $build = Join-Path $PSScriptRoot 'build-windows-release.ps1' @@ -11,13 +11,45 @@ function Must-Reject([scriptblock]$Action, [string]$Expected) { } if (-not $rejected) { throw 'Signing preflight accepted an invalid configuration.' } } -Must-Reject { & $build -CertificateThumbprint '' -PreflightOnly } 'certificate is required' +Must-Reject { & $build -CertificateThumbprint '' -SigningConfigPath (Join-Path $PSScriptRoot '../target/no-signing-identity.json') -PreflightOnly } 'certificate is required' Must-Reject { & $build -CertificateThumbprint 'not-a-certificate' -AllowUnsigned -PreflightOnly } 'Invalid.*thumbprint' Must-Reject { & $build -CertificateThumbprint ('0' * 40) -AllowUnsigned -PreflightOnly } 'not found' Must-Reject { & $build -CertificateThumbprint '' -AllowUnsigned -TimestampUrl 'file:///tmp/timestamp' -PreflightOnly } 'Timestamp URL' Must-Reject { & $build -CertificateThumbprint '' -AllowUnsigned -TimestampUrl 'https://user:secret@example.invalid' -PreflightOnly } 'Timestamp URL' $result = & $build -CertificateThumbprint '' -AllowUnsigned -PreflightOnly -if ($result.signing -or -not $result.unsignedExplicitlyAllowed -or $result.digestAlgorithm -ne 'sha256' -or -not $result.tsp) { +if ($result.signing -or -not $result.unsignedExplicitlyAllowed -or $result.digestAlgorithm -or $result.tsp) { throw 'Explicit unsigned preflight returned inconsistent signing metadata.' } Write-Host 'Windows signing preflight: 6 checks passed; no certificates or system settings were changed.' +if ($SignedFixture) { + if (-not $CertificateThumbprint) { throw 'Integration checks need a pinned fixture certificate thumbprint.' } + $verify = Join-Path $PSScriptRoot 'verify-windows-signature.ps1' + $verified = & $verify -Path $SignedFixture -CertificateThumbprint $CertificateThumbprint -SelfSigned + if (-not $verified.integrityVerified -or -not $verified.timestampVerified -or -not $verified.selfSigned) { throw 'Signed fixture was not verified.' } + Must-Reject { & $verify -Path $SignedFixture -CertificateThumbprint ('0' * 40) -SelfSigned } 'Unexpected signing certificate' + Must-Reject { & $verify -Path $SignedFixture -CertificateThumbprint $CertificateThumbprint } 'certificate chain is invalid' + $tempDir = Join-Path $PSScriptRoot "../target/signing-tests/tamper-$([guid]::NewGuid().ToString('N'))" + New-Item -ItemType Directory -Path $tempDir | Out-Null + $tampered = Join-Path $tempDir 'tampered.exe' + try { + $bytes = [IO.File]::ReadAllBytes([IO.Path]::GetFullPath($SignedFixture)) + $pe = [BitConverter]::ToInt32($bytes, 0x3c) + $section = $pe + 24 + [BitConverter]::ToUInt16($bytes, $pe + 20) + $codeOffset = [BitConverter]::ToInt32($bytes, $section + 20) + $bytes[$codeOffset + 32] = $bytes[$codeOffset + 32] -bxor 1 + [IO.File]::WriteAllBytes([IO.Path]::GetFullPath($tampered), $bytes) + Must-Reject { & $verify -Path $tampered -CertificateThumbprint $CertificateThumbprint -SelfSigned } 'PE file digest mismatch' + } finally { + Remove-Item -LiteralPath $tampered -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $tempDir + } + if (Test-Path -LiteralPath "Cert:\CurrentUser\Root\$CertificateThumbprint") { throw 'Project signing identity was imported into Root.' } + if (Test-Path -LiteralPath "Cert:\CurrentUser\TrustedPublisher\$CertificateThumbprint") { throw 'Project identity was imported into TrustedPublisher.' } + $identity = & (Join-Path $PSScriptRoot 'initialize-windows-signing.ps1') + if ($identity.certificateThumbprint -ne $CertificateThumbprint) { throw 'Default signing identity changed between builds.' } + Write-Host 'Self-signed integration: valid signature/timestamp, wrong identity, CA trust requirement, PE tampering, trust-store isolation and identity reuse passed.' + if ($UntimestampedFixture) { + Must-Reject { & $verify -Path $UntimestampedFixture -CertificateThumbprint $CertificateThumbprint -SelfSigned } 'Expected one RFC 3161 timestamp' + Write-Host 'Missing RFC 3161 timestamp was rejected.' + } +} diff --git a/client/scripts/verify-windows-signature.ps1 b/client/scripts/verify-windows-signature.ps1 new file mode 100644 index 0000000..c258a0a --- /dev/null +++ b/client/scripts/verify-windows-signature.ps1 @@ -0,0 +1,23 @@ +#requires -Version 7.4 +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$Path, + [Parameter(Mandatory)][string]$CertificateThumbprint, + [switch]$SelfSigned +) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$signature = Get-AuthenticodeSignature -LiteralPath $Path +if ($signature.Status -eq 'NotSigned') { throw "The file has no embedded signature: $Path" } +if (-not ('RmicWindowsSignature' -as [type])) { + $references = @((Get-ChildItem -LiteralPath (Join-Path $PSHOME 'ref') -Filter '*.dll').FullName) + + @([System.Security.Cryptography.Pkcs.SignedCms].Assembly.Location) + Add-Type -Path (Join-Path $PSScriptRoot 'windows-signature.cs') -ReferencedAssemblies $references +} +$timestamp = [RmicWindowsSignature]::Verify([IO.Path]::GetFullPath($Path), $CertificateThumbprint, [bool]$SelfSigned) +if (-not $SelfSigned -and $signature.Status -ne 'Valid') { throw "Windows does not trust the CA-signed output: $Path" } +[pscustomobject]@{ file = [IO.Path]::GetFileName($Path); status = [string]$signature.Status; + verificationStatus = $(if ($SelfSigned) { 'valid-pinned-self-signed' } else { 'valid-trusted-signature' }); + windowsTrustMessage = $signature.StatusMessage; + integrityVerified = $true; timestamped = $true; timestampVerified = $true; timestampUtc = $timestamp.ToString('o'); + certificateThumbprint = $CertificateThumbprint; selfSigned = [bool]$SelfSigned; windowsTrusted = $signature.Status -eq 'Valid' } diff --git a/client/scripts/windows-signature.cs b/client/scripts/windows-signature.cs new file mode 100644 index 0000000..4e040c5 --- /dev/null +++ b/client/scripts/windows-signature.cs @@ -0,0 +1,135 @@ +// Verify the signed PE digest with Windows SIP, CMS with .NET, and the RFC 3161 +// binding with .NET. A pinned self-signed root is scoped to this X509Chain only. +// No certificate is imported into an operating-system trust store. +using System; +using System.ComponentModel; +using System.Formats.Asn1; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Security.Cryptography.Pkcs; +using System.Security.Cryptography.X509Certificates; + +public static class RmicWindowsSignature { + const string Sha256 = "2.16.840.1.101.3.4.2.1"; + [StructLayout(LayoutKind.Sequential)] struct Blob { public uint Size; public IntPtr Data; } + [StructLayout(LayoutKind.Sequential)] struct Algorithm { + [MarshalAs(UnmanagedType.LPStr)] public string Oid; + public Blob Parameters; + } + [StructLayout(LayoutKind.Sequential)] struct Attribute { + public IntPtr Oid; + public Blob Value; + } + [StructLayout(LayoutKind.Sequential)] struct IndirectData { + public Attribute Data; + public Algorithm Algorithm; + public Blob Digest; + } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct Subject { + public uint Size; + public IntPtr Type, File; + [MarshalAs(UnmanagedType.LPWStr)] public string FileName; + public IntPtr DisplayName; + public uint Reserved1, Version; + public IntPtr Provider; + public Algorithm Algorithm; + public uint Flags, Encoding, Reserved2, CapiSettings, SecuritySettings, Index, UnionChoice; + public IntPtr AdditionalInfo, ClientData; + } + [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] + static extern bool CryptSIPRetrieveSubjectGuid(string file, IntPtr handle, out Guid type); + [DllImport("crypt32.dll", SetLastError = true, ExactSpelling = true)] + static extern bool CryptSIPGetSignedDataMsg(ref Subject subject, out uint encoding, uint index, ref uint size, [Out] byte[] data); + [DllImport("crypt32.dll", SetLastError = true, ExactSpelling = true)] + static extern bool CryptSIPCreateIndirectData(ref Subject subject, ref uint size, IntPtr data); + + static void Require(bool condition, string message) { + if (!condition) throw new CryptographicException(message); + } + static void Native(bool success) { + if (!success) throw new Win32Exception(Marshal.GetLastWin32Error()); + } + public static DateTimeOffset Verify(string file, string thumbprint, bool selfSigned) { + Native(CryptSIPRetrieveSubjectGuid(file, IntPtr.Zero, out Guid type)); + IntPtr guid = Marshal.AllocHGlobal(Marshal.SizeOf()); + IntPtr indirect = IntPtr.Zero; + try { + Marshal.StructureToPtr(type, guid, false); + var subject = new Subject { Size = (uint)Marshal.SizeOf(), Type = guid, + File = new IntPtr(-1), FileName = Path.GetFullPath(file), Encoding = 0x10001, + Algorithm = new Algorithm { Oid = Sha256 } }; + uint size = 0; + Native(CryptSIPGetSignedDataMsg(ref subject, out uint encoding, 0, ref size, null)); + Require(size > 0 && size <= 16 * 1024 * 1024, "Invalid embedded signature size."); + var encoded = new byte[size]; + Native(CryptSIPGetSignedDataMsg(ref subject, out encoding, 0, ref size, encoded)); + var cms = new SignedCms(); + cms.Decode(encoded); + Require(cms.ContentInfo.ContentType.Value == "1.3.6.1.4.1.311.2.1.4" && cms.SignerInfos.Count == 1, + "Expected one embedded Authenticode signer."); + var signer = cms.SignerInfos[0]; + Require(signer.Certificate != null && signer.Certificate.Thumbprint.Equals(thumbprint, StringComparison.OrdinalIgnoreCase), + "Unexpected signing certificate thumbprint."); + Require(signer.DigestAlgorithm.Value == Sha256, "Expected SHA-256 CMS signature."); + cms.CheckSignature(true); + var reader = new AsnReader(cms.ContentInfo.Content, AsnEncodingRules.BER); + var content = reader.ReadSequence(); + content.ReadEncodedValue(); // SpcAttributeTypeAndOptionalValue + var digestInfo = content.ReadSequence(); + var algorithm = digestInfo.ReadSequence(); + Require(algorithm.ReadObjectIdentifier() == Sha256, "Expected SHA-256 PE digest."); + if (algorithm.HasData) algorithm.ReadNull(); + algorithm.ThrowIfNotEmpty(); + byte[] digest = digestInfo.ReadOctetString(); + digestInfo.ThrowIfNotEmpty(); content.ThrowIfNotEmpty(); reader.ThrowIfNotEmpty(); + + uint indirectSize = 0; + Native(CryptSIPCreateIndirectData(ref subject, ref indirectSize, IntPtr.Zero)); + Require(indirectSize > 0 && indirectSize <= 1024 * 1024, "Invalid SIP result size."); + indirect = Marshal.AllocHGlobal((int)indirectSize); + Native(CryptSIPCreateIndirectData(ref subject, ref indirectSize, indirect)); + var actual = Marshal.PtrToStructure(indirect); + Require(actual.Algorithm.Oid == Sha256 && actual.Digest.Size == 32 && digest.Length == 32, + "Invalid SIP digest algorithm or length."); + byte[] actualDigest = new byte[32]; + Marshal.Copy(actual.Digest.Data, actualDigest, 0, actualDigest.Length); + Require(CryptographicOperations.FixedTimeEquals(actualDigest, digest), "PE file digest mismatch."); + + var timestampAttributes = signer.UnsignedAttributes.Cast() + .Where(a => a.Oid.Value == "1.3.6.1.4.1.311.3.3.1").ToArray(); + Require(timestampAttributes.Length == 1 && timestampAttributes[0].Values.Count == 1, + "Expected one RFC 3161 timestamp."); + var timestampData = timestampAttributes[0].Values[0].RawData; + Require(Rfc3161TimestampToken.TryDecode(timestampData, out var token, out int consumed) && consumed == timestampData.Length, + "Invalid RFC 3161 timestamp."); + Require(token.VerifySignatureForSignerInfo(signer, out var tsa, cms.Certificates), + "Timestamp signature or binding is invalid."); + using (var tsaChain = new X509Chain()) { + tsaChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + tsaChain.ChainPolicy.VerificationTime = token.TokenInfo.Timestamp.UtcDateTime; + tsaChain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.8")); + tsaChain.ChainPolicy.ExtraStore.AddRange(token.AsSignedCms().Certificates); + Require(tsaChain.Build(tsa), "Timestamp authority certificate chain is invalid."); + } + using (var chain = new X509Chain()) { + chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + chain.ChainPolicy.VerificationTime = token.TokenInfo.Timestamp.UtcDateTime; + chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3")); + chain.ChainPolicy.ExtraStore.AddRange(cms.Certificates); + if (selfSigned) { + Require(signer.Certificate.SubjectName.RawData.SequenceEqual(signer.Certificate.IssuerName.RawData), + "Expected a self-signed certificate."); + chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + chain.ChainPolicy.CustomTrustStore.Add(signer.Certificate); + } + Require(chain.Build(signer.Certificate), "Signing certificate chain is invalid for the selected identity."); + } + return token.TokenInfo.Timestamp; + } finally { + if (indirect != IntPtr.Zero) Marshal.FreeHGlobal(indirect); + Marshal.FreeHGlobal(guid); + } + } +} diff --git a/client/src-tauri/tauri.conf.json b/client/src-tauri/tauri.conf.json index 1ca1d6f..2da2f07 100644 --- a/client/src-tauri/tauri.conf.json +++ b/client/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "RMIC-2026", - "version": "0.4.0", + "version": "0.4.1", "identifier": "com.simbarobotics.rmic2026", "build": { "beforeDevCommand": "pnpm dev", diff --git a/client/src/lib/version.ts b/client/src/lib/version.ts index c6a1ca2..9f457fe 100644 --- a/client/src/lib/version.ts +++ b/client/src/lib/version.ts @@ -6,12 +6,12 @@ */ export const BUILD = { - version: "0.4.0", + version: "0.4.1", major: 0, minor: 4, - patch: 0, + patch: 1, /** git 提交数,单调递增。 */ - build: 44, + build: 45, /** 线路协议版本。与固件自报的那个数直接比对。 */ protocol: 1, /** 生成时的提交日期(`YYYY-MM-DD`)。 */ diff --git a/docs/client/client.md b/docs/client/client.md index 60680ad..29c5a31 100644 --- a/docs/client/client.md +++ b/docs/client/client.md @@ -177,10 +177,10 @@ cd client/src-tauri && cargo test # 40,其中几条真的会起 ffmpeg ```powershell pnpm install --frozen-lockfile -pnpm tauri build --target x86_64-pc-windows-msvc --bundles nsis --ci -- --locked --config 'unstable.build-std=[]' +pnpm bundle:windows ``` -`--target` 覆盖本目录原来的 macOS target,`--bundles nsis` 选择 Windows 安装包;末尾的 Cargo 参数清空从根固件项目继承的 `build-std`。 +该命令调用 `scripts/build-windows-release.ps1`,显式选择 Windows x64、NSIS 安装包与 stable 工具链,并清空从固件项目继承的 `build-std`。 - 程序:`src-tauri/target/x86_64-pc-windows-msvc/release/cam-desktop.exe`。当前 Cargo 和 Tauri 构建都使用这个二进制文件名;安装器的显示名和文件名使用 `RMIC-2026`。 - 安装包:同一 release 目录下的 `bundle/nsis/*-setup.exe`。 @@ -207,17 +207,23 @@ icacls .\src-tauri\target\x86_64-pc-windows-msvc\release\bundle\nsis\*-setup.exe SmartScreen 的发布者与文件信誉和上述完整性标签是两套机制。未签名的软件、使用自签证书的软件以及信誉尚未建立的新签名包都可能出现提示;有效代码签名也不保证新包立即免提示,见[微软的 SmartScreen 开发者说明](https://learn.microsoft.com/en-us/windows/apps/package-and-deploy/smartscreen-reputation)。 -正式 Windows 构建使用 `scripts/build-windows-release.ps1`,通过 Tauri 原生签名配置,对主程序及 NSIS 安装包使用 SHA-256 和 RFC 3161 时间戳,并检查签名状态、发布者指纹和时间戳。将公开信任 CA 签发的代码签名证书及可访问的私钥配置到构建用户的 `CurrentUser/My`,再在进程环境指定 `RMIC_WINDOWS_CERT_THUMBPRINT`;个人证书身份不会写进共享 Tauri 配置。没有证书时默认停止,需要明确传入 `-AllowUnsigned` 才生成文件名带 `unsigned` 的测试包,并在校验报告中标明 `signed=false`。这不解决 SmartScreen 信誉问题,也不改变系统防护设置。 +Windows 发布通过 Tauri 原生签名配置,对主程序及 NSIS 安装包使用 SHA-256 和 RFC 3161 时间戳。发布脚本要求 PowerShell 7.4+,首次运行默认在 `CurrentUser/My` 创建项目专用的 RSA 3072 自签名代码证书,有效期 3 年,私钥不可导出。公开指纹保存在 `%LOCALAPPDATA%/RMIC-2026/signing/windows.json`;后续构建复用同一证书,不会每版重新创建。配置丢失时可找回同名的唯一证书;证书过期、私钥丢失或存在多个候选时停止,需明确选择或补建身份。私钥仍需依靠原构建账户和机器保留;换机不能只复制公钥继续签名。 + +自签名交付文件名带 `self-signed`,附带 `RMIC-2026-codesign.cer` 公钥证书及 `windows-signature-verification.json`。校验器分别验证 CMS 签名、Windows SIP 文件摘要、固定证书指纹,以及 RFC 3161 时间戳的签名、绑定和时间戳机构证书链。自签名链仅在本次校验对象中按指纹验证,不会把证书导入系统 Root 或 TrustedPublisher。报告中的 `integrityVerified=true` 与 `windowsTrusted=false` 可以同时成立;系统可能显示 `UnknownError`,原因仍是根证书未受信任。完整文件 SHA-256 另见同目录校验文件。 + +如改用 CA 证书,将证书及可访问的私钥配置到构建用户的 `CurrentUser/My`,再指定 `RMIC_WINDOWS_CERT_THUMBPRINT`。个人证书身份不会写入共享 Tauri 配置。只有显式传入 `-AllowUnsigned` 且没有指定证书指纹时,才生成带 `unsigned` 的未签名包;它不读取本地默认身份。`-SigningConfigPath` 或 `RMIC_WINDOWS_SIGNING_CONFIG` 可指定本机配置位置。这些方式不改变系统防护设置,也不代表已建立 SmartScreen 信誉。 ```powershell -# 在 client/ 执行。已有证书时,将其指纹放入进程环境后运行。 -.\scripts\build-windows-release.ps1 +# 在 client/ 执行。默认创建或复用本机自签名身份。 +pnpm bundle:windows +# 只读预检(首次创建前会提示没有身份)。 +pwsh -NoProfile -File scripts/build-windows-release.ps1 -PreflightOnly # 仅用于明确接受未签名限制的开发测试。 .\scripts\build-windows-release.ps1 -AllowUnsigned .\scripts\test-windows-signing.ps1 ``` -交付文件与签名报告输出到根目录 `target/releases/v<版本>+<构建号>/`。CI 的 `WINDOWS_CODE_SIGNING_THUMBPRINT` 仓库变量引用 runner 用户证书库中的身份;`v*` 标签构建缺少证书时失败,其他构建可输出明确标注的未签名测试包。PR 构建只生成未签名测试包。签名 runner 应仅接受可信源码;私钥或证书密码不写入仓库、构建参数或报告。 +交付文件与签名报告输出到根目录 `target/releases/v<版本>+<构建号>/`。CI 发布同样默认复用 runner 账户的自签名身份;需要持久保存该账户的证书库和本机配置,临时 runner 无法自动继承前一次身份。`WINDOWS_CODE_SIGNING_THUMBPRINT` 仓库变量可覆盖默认选择。PR 构建只生成未签名预览包。签名 runner 应仅接受可信源码;私钥或证书密码不写入仓库、构建参数或报告。 NSIS 安装流程使用简体中文,包括欢迎、安装位置、安装完成、覆盖安装、卸载与 WebView2 错误提示。`src-tauri/installer/hooks.nsh` 定义页面提示和安装日志,`SimpChinese.nsh` 定义 Tauri 安装器的补充翻译;`tauri.windows.conf.json` 引用这些脚本和主题图片。沿用 Tauri 默认安装模板和当前用户安装方式;首次启动的模式选择与裁判系统绑定仍在客户端内完成。 diff --git a/docs/releases/changelog.json b/docs/releases/changelog.json index 09623f9..a9eda8e 100644 --- a/docs/releases/changelog.json +++ b/docs/releases/changelog.json @@ -1,12 +1,12 @@ { - "version": "0.4.0", + "version": "0.4.1", "major": 0, "minor": 4, - "patch": 0, - "build": 44, + "patch": 1, + "build": 45, "protocol": 1, "date": "2026-10-31", - "baseline": "v0.4.0", + "baseline": "v0.4.1", "commits": 0, "groups": {} } diff --git a/docs/releases/changelog.md b/docs/releases/changelog.md index 61fdb73..5a49e63 100644 --- a/docs/releases/changelog.md +++ b/docs/releases/changelog.md @@ -4,6 +4,19 @@ > 提交采用 Conventional Commits,规则见[版本维护](../development/versioning.md)。 > 自动版本机制建立前的说明见[早期人工记录](changelog-legacy.md)。 +## v0.4.1 — 2026-10-31 + +1 个提交 + +### 修复 + +- **build** · 默认复用自签名证书签署 Windows 发布包 +- **signing** · 独立校验文件摘要、CMS 签名与 RFC 3161 时间戳,不修改系统信任库 + +### 构建 + +- **windows** · 发布脚本和 CI 复用本机签名身份,交付公钥证书与真实信任状态 + ## v0.4.0 — 2026-10-31 2 个提交 diff --git a/version.json b/version.json index 1e8c83b..2b201ef 100644 --- a/version.json +++ b/version.json @@ -1,11 +1,11 @@ { - "version": "0.4.0", + "version": "0.4.1", "major": 0, "minor": 4, - "patch": 0, - "build": 44, + "patch": 1, + "build": 45, "protocol": 1, "date": "2026-10-31", - "baseline": "v0.4.0", + "baseline": "v0.4.1", "note": "由 scripts/version.mjs 从 git 历史算出,请勿手改。" }