// 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); } } }