Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Verify staged signatures before replacing release artifacts

Danielf2eb0618befd
diff --git a/docs/RELEASE-VERIFICATION.zh-CN.md b/docs/RELEASE-VERIFICATION.zh-CN.md
index d527492a6e..bcd04a536e 100644
--- a/docs/RELEASE-VERIFICATION.zh-CN.md
+++ b/docs/RELEASE-VERIFICATION.zh-CN.md
@@ -365,6 +365,8 @@ python -X utf8 scripts/verify-release.py check D:/releases/siyuan --version 3.8.
自动执行时可由启动程序通过进程环境变量 `SIYUAN_SIGNING_PIN` 提供 PIN,无需把密码写进命令或脚本。仍需保持签名设备连接;脚本不改变 PIN 或触摸策略,需要触摸的密钥不能完全无人值守。若驱动不支持自动认证,可添加 `--signing-ui` 沿用系统弹窗。
+自动签名对每个文件使用同目录临时副本:签名期间禁止原文件写入,副本签名后独立检查签名、证书和时间戳,并确认原文件哈希未变化,才原子替换原文件。失败时保留原文件并删除临时副本,不以重签或忽略 `HashMismatch` 代替验证。安装包收集前仍执行最终验签。
+
默认按现有证书主题选择有效代码签名证书;多张证书时用 `--certificate-sha1` 指定 40 位公开指纹,它不是密码。SignTool 的 `/p` 是证书文件密码选项,不能当成通用 YubiKey PIN 参数。参见 [Yubico 驱动说明](https://www.yubico.com/support/download/smart-card-drivers-tools/) 和 [SignTool 文档](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool)。
## 可选的完整摘要基准
diff --git a/scripts/release-sign-windows.ps1 b/scripts/release-sign-windows.ps1
index 12f9719441..b38198df41 100644
--- a/scripts/release-sign-windows.ps1
+++ b/scripts/release-sign-windows.ps1
@@ -60,6 +60,38 @@ public static class SiYuanReleaseKey {
}
'@
+function Set-VerifiedFileSignature($file, $certificate) {
+ Import-Module (Join-Path $PSHOME 'Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1')
+ $file = [IO.Path]::GetFullPath($file)
+ $temporary = Join-Path ([IO.Path]::GetDirectoryName($file)) ('.siyuan-sign-' + [guid]::NewGuid().ToString('N') + [IO.Path]::GetExtension($file))
+ $inputFile = $null
+ try {
+ # Deny concurrent writes until the verified replacement is installed.
+ $inputFile = [IO.File]::Open($file, [IO.FileMode]::Open, [IO.FileAccess]::Read,
+ ([IO.FileShare]::Read -bor [IO.FileShare]::Delete))
+ $originalHash = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash
+ $copy = [IO.File]::Create($temporary)
+ try { $inputFile.CopyTo($copy) } finally { $copy.Dispose() }
+ if ((Get-FileHash -LiteralPath $temporary -Algorithm SHA256).Hash -ne $originalHash) {
+ throw 'Signing input changed during copy'
+ }
+ $script:stage = 'signing'
+ $null = Set-AuthenticodeSignature -LiteralPath $temporary -Certificate $certificate -HashAlgorithm SHA256 -TimestampServer 'http://timestamp.digicert.com'
+ $script:stage = 'verification'
+ $signature = Get-AuthenticodeSignature -LiteralPath $temporary
+ [Console]::Error.WriteLine('SIGNING_STATUS:' + [int]$signature.Status + ':' + [int]($null -ne $signature.TimeStamperCertificate))
+ if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Thumbprint -ne $certificate.Thumbprint -or
+ $null -eq $signature.TimeStamperCertificate) { throw 'Signature or timestamp verification failed' }
+ if ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ne $originalHash) {
+ throw 'Signing input changed before replacement'
+ }
+ [IO.File]::Replace($temporary, $file, [System.Management.Automation.Language.NullString]::Value)
+ } finally {
+ if ($null -ne $inputFile) { $inputFile.Dispose() }
+ if ([IO.File]::Exists($temporary)) { [IO.File]::Delete($temporary) }
+ }
+}
+
$payload = $null
$certificate = $null
$stage = "request"
@@ -85,14 +117,7 @@ try {
[SiYuanReleaseKey]::Authenticate($certificate.Handle, $payload.pin, $oid -eq '1.2.840.113549.1.1.1')
$payload.pin = $null
foreach ($file in $payload.files) {
- $stage = "signing"
- $signature = Set-AuthenticodeSignature -LiteralPath $file -Certificate $certificate -HashAlgorithm SHA256 -TimestampServer "http://timestamp.digicert.com"
- $stage = 'verification'
- [Console]::Error.WriteLine('SIGNING_STATUS:' + [int]$signature.Status + ':' + [int]($null -ne $signature.TimeStamperCertificate))
- if ($signature.Status -ne "Valid" -or $signature.SignerCertificate.Thumbprint -ne $certificate.Thumbprint -or
- $null -eq $signature.TimeStamperCertificate) {
- throw "Signature or timestamp verification failed"
- }
+ Set-VerifiedFileSignature $file $certificate
Write-Output ("Signed and verified: " + $file)
}
} catch {
diff --git a/scripts/test_build_release.py b/scripts/test_build_release.py
index 0f6e3dee5a..c614bf8122 100644
--- a/scripts/test_build_release.py
+++ b/scripts/test_build_release.py
@@ -188,7 +188,7 @@ class BuildTests(unittest.TestCase):
@unittest.skipUnless(sys.platform == "win32", "Windows certificate provider")
def test_signing_certificate_provider_loads_without_module_path(self):
source = Path(__file__).with_name("release-sign-windows.ps1").read_text(encoding="utf-8")
- load = next(line.strip() for line in source.splitlines() if "Import-Module" in line)
+ load = next(line.strip() for line in source.splitlines() if "Import-Module" in line and "Microsoft.PowerShell.Security" in line)
env = dict(build.os.environ)
env.pop("PSModulePath", None)
result = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
@@ -197,6 +197,13 @@ class BuildTests(unittest.TestCase):
env=env, capture_output=True, timeout=30)
self.assertEqual(result.returncode, 0, result.stderr)
+ @unittest.skipUnless(sys.platform == "win32", "Windows file replacement semantics")
+ def test_staged_signing_preserves_original_on_failure(self):
+ result = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
+ "-File", str(Path(__file__).with_name("test_release_sign_windows.ps1"))],
+ capture_output=True, timeout=30)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+
@unittest.skipUnless(sys.platform == "win32", "需要 Windows 批处理")
def test_batch_restores_missing_windows_environment_marker(self):
batch = self.write(self.root / "environment.bat",
diff --git a/scripts/test_release_sign_windows.ps1 b/scripts/test_release_sign_windows.ps1
new file mode 100644
index 0000000000..da5b065ac0
--- /dev/null
+++ b/scripts/test_release_sign_windows.ps1
@@ -0,0 +1,44 @@
+$ErrorActionPreference = 'Stop'
+$tokens = $null
+$errors = $null
+$ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $PSScriptRoot 'release-sign-windows.ps1'), [ref]$tokens, [ref]$errors)
+if ($errors.Count) { throw 'Signing script has parse errors' }
+$definition = $ast.Find({ param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Set-VerifiedFileSignature' }, $true)
+Invoke-Expression $definition.Extent.Text
+$root = Join-Path ([IO.Path]::GetTempPath()) ('siyuan-sign-test-' + [guid]::NewGuid().ToString('N'))
+$null = [IO.Directory]::CreateDirectory($root)
+$original = Join-Path $root 'original.exe'
+$certificate = [pscustomobject]@{ Thumbprint = 'A' * 40 }
+function Set-AuthenticodeSignature($LiteralPath, $Certificate, $HashAlgorithm, $TimestampServer) {
+ if ($LiteralPath -eq $original) { throw 'Must sign a copy' }
+ if ($HashAlgorithm -ne 'SHA256') { throw 'Unexpected digest' }
+ if ($mode -eq 'throw') { throw 'Simulated signing error' }
+ try {
+ $writer = [IO.File]::Open($original, [IO.FileMode]::Open, [IO.FileAccess]::Write, [IO.FileShare]::ReadWrite)
+ $writer.Dispose()
+ throw 'Original was writable during signing'
+ } catch [IO.IOException] { }
+ [IO.File]::WriteAllText($LiteralPath, 'signed-copy')
+}
+function Get-AuthenticodeSignature($LiteralPath) {
+ [pscustomobject]@{
+ Status = $(if ($mode -eq 'hash') { [System.Management.Automation.SignatureStatus]::HashMismatch } else { [System.Management.Automation.SignatureStatus]::Valid })
+ SignerCertificate = [pscustomobject]@{ Thumbprint = $(if ($mode -eq 'signer') { 'B' * 40 } else { $certificate.Thumbprint }) }
+ TimeStamperCertificate = $(if ($mode -eq 'timestamp') { $null } else { [pscustomobject]@{} })
+ }
+}
+try {
+ foreach ($mode in @('success', 'hash', 'timestamp', 'signer', 'throw')) {
+ [IO.File]::WriteAllText($original, 'original-content')
+ $failed = $false
+ try { Set-VerifiedFileSignature $original $certificate } catch { $failed = $true; if ($mode -eq 'success') { throw } }
+ if ($failed -ne ($mode -ne 'success')) { throw "Unexpected outcome: $mode" }
+ $expected = if ($mode -eq 'success') { 'signed-copy' } else { 'original-content' }
+ if ([IO.File]::ReadAllText($original) -ne $expected) { throw "Original damaged: $mode" }
+ if (@(Get-ChildItem -LiteralPath $root -Force).Count -ne 1) { throw 'Temporary copy was not cleaned' }
+ }
+ Write-Output 'Staged signing tests passed'
+} finally {
+ [IO.File]::Delete($original)
+ [IO.Directory]::Delete($root)
+}