fix(build): 默认复用自签名证书签署 Windows 发布包
- fix(signing): 独立校验文件摘要、CMS 签名与 RFC 3161 时间戳,不修改系统信任库 - build(windows): 发布脚本和 CI 复用本机签名身份,交付公钥证书与真实信任状态
This commit is contained in:
14 files changed
+323
-39
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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.'
|
||||
}
|
||||
}
|
||||
@@ -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' }
|
||||
@@ -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<Guid>());
|
||||
IntPtr indirect = IntPtr.Zero;
|
||||
try {
|
||||
Marshal.StructureToPtr(type, guid, false);
|
||||
var subject = new Subject { Size = (uint)Marshal.SizeOf<Subject>(), 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<IndirectData>(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<CryptographicAttributeObject>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user