| 1 | using System.Runtime.InteropServices; |
| 2 | using System.Security.Cryptography; |
| 3 | using System.Security.Cryptography.X509Certificates; |
| 4 | |
| 5 | namespace Cage.Windows; |
| 6 | |
| 7 | internal static class Authenticode |
| 8 | { |
| 9 | public static string Publisher(string path) |
| 10 | { |
| 11 | UpdatePolicy.PlainPath(path); |
| 12 | var file = new TrustFile { Size = (uint)Marshal.SizeOf<TrustFile>(), Path = path }; |
| 13 | var memory = Marshal.AllocHGlobal(Marshal.SizeOf<TrustFile>()); |
| 14 | try |
| 15 | { |
| 16 | Marshal.StructureToPtr(file, memory, false); |
| 17 | var data = new TrustData { |
| 18 | Size = (uint)Marshal.SizeOf<TrustData>(), UiChoice = 2, UnionChoice = 1, |
| 19 | File = memory, StateAction = 1, |
| 20 | |
| 21 | |
| 22 | ProviderFlags = 0x1000, |
| 23 | }; |
| 24 | var action = new Guid("00AAC56B-CD44-11D0-8CC2-00C04FC295EE"); |
| 25 | var result = WinVerifyTrust(new IntPtr(-1), ref action, ref data); |
| 26 | data.StateAction = 2; _ = WinVerifyTrust(new IntPtr(-1), ref action, ref data); |
| 27 | if (result != 0) throw new IOException("Windows 无法验证安装包签名;原应用已保留。请确认系统证书信任状态。"); |
| 28 | #pragma warning disable SYSLIB0057 |
| 29 | using var signed = X509Certificate.CreateFromSignedFile(path); |
| 30 | using var certificate = new X509Certificate2(signed); |
| 31 | #pragma warning restore SYSLIB0057 |
| 32 | return Convert.ToHexString(SHA256.HashData(certificate.PublicKey.ExportSubjectPublicKeyInfo())); |
| 33 | } |
| 34 | finally { Marshal.DestroyStructure<TrustFile>(memory); Marshal.FreeHGlobal(memory); } |
| 35 | } |
| 36 | |
| 37 | public static void SamePublisher(string path, string expected) |
| 38 | { |
| 39 | if (!string.Equals(Publisher(path), expected, StringComparison.Ordinal)) |
| 40 | throw new IOException("更新包的发布者签名与当前 Cage 不一致"); |
| 41 | } |
| 42 | |
| 43 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] |
| 44 | private struct TrustFile { public uint Size; [MarshalAs(UnmanagedType.LPWStr)] public string Path; public IntPtr Handle; public IntPtr KnownSubject; } |
| 45 | [StructLayout(LayoutKind.Sequential)] |
| 46 | private struct TrustData { |
| 47 | public uint Size; public IntPtr PolicyCallback, SipClient; |
| 48 | public uint UiChoice, RevocationChecks, UnionChoice; public IntPtr File; |
| 49 | public uint StateAction; public IntPtr StateData, UrlReference; |
| 50 | public uint ProviderFlags, UiContext; public IntPtr SignatureSettings; |
| 51 | } |
| 52 | [DllImport("wintrust.dll", ExactSpelling = true, PreserveSig = true)] |
| 53 | private static extern int WinVerifyTrust(IntPtr window, ref Guid action, ref TrustData data); |
| 54 | } |