From 15aa28846a6bd29272f16d6e85514a0d812f0bdb Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Mon, 23 Nov 2026 20:16:15 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=9C=BA=E5=99=A8=E7=A0=81?= =?UTF-8?q?=E6=94=B9=E7=94=A8=E7=A3=81=E7=9B=98=E5=BA=8F=E5=88=97=E5=8F=B7?= =?UTF-8?q?=E5=90=8E=E6=97=A7=E6=8E=88=E6=9D=83=E8=AE=B0=E5=BD=95=E8=A7=A3?= =?UTF-8?q?=E4=B8=8D=E5=BC=80=E5=AF=BC=E8=87=B4=E6=BF=80=E6=B4=BB=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=EF=BC=9A=E6=96=B0=E5=A2=9E=E5=8E=86=E5=8F=B2=E4=B8=BB?= =?UTF-8?q?=E6=9D=BF=E6=9C=BA=E5=99=A8=E7=A0=81=E6=83=B0=E6=80=A7=E8=BF=81?= =?UTF-8?q?=E7=A7=BB=EF=BC=8C=E6=97=A7=E8=AE=B0=E5=BD=95=E5=B0=B1=E5=9C=B0?= =?UTF-8?q?=E9=87=8D=E5=B0=81=E5=B9=B6=E4=BF=9D=E7=95=99=E8=AF=95=E7=94=A8?= =?UTF-8?q?=E8=B5=B7=E7=82=B9=E5=92=8C=E5=B7=B2=E5=85=91=E6=8D=A2=E7=A0=81?= =?UTF-8?q?=EF=BC=8C=E8=A1=A5=E5=85=85=E8=BF=81=E7=A7=BB=E4=B8=8E=E6=8B=92?= =?UTF-8?q?=E7=BB=9D=E7=94=A8=E4=BE=8B=E5=8F=8A=E7=8E=B0=E5=9C=BA=E6=8E=92?= =?UTF-8?q?=E9=9A=9C=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Licensing/LegacyHardwareIdentity.cs | 90 +++++++++++++++++++ .../Licensing/LicenseService.cs | 25 +++++- .../Licensing/ProtectedLicenseStore.cs | 89 ++++++++++++++---- tests/D3Startup.Smoke/LicenseTests.cs | 78 ++++++++++++++++ tests/D3Startup.Smoke/Program.cs | 3 + 5 files changed, 268 insertions(+), 17 deletions(-) create mode 100644 src/SopHelper.CrossPlatform.Engine/Licensing/LegacyHardwareIdentity.cs diff --git a/src/SopHelper.CrossPlatform.Engine/Licensing/LegacyHardwareIdentity.cs b/src/SopHelper.CrossPlatform.Engine/Licensing/LegacyHardwareIdentity.cs new file mode 100644 index 0000000..9305b90 --- /dev/null +++ b/src/SopHelper.CrossPlatform.Engine/Licensing/LegacyHardwareIdentity.cs @@ -0,0 +1,90 @@ +using System.Diagnostics; +using System.Text.Json; + +namespace SopHelper.Engine.Licensing; + +/// +/// 历史硬件绑定方案的机器码重算器。c018869 之前授权绑定主板固件序列号(厂商+型号+序列号), +/// 之后改用物理磁盘固件序列号;升级后本机旧授权记录是用主板机器码派生的熵加密的, +/// 存储层与授权状态机需要据此识别并迁移旧记录,否则升级即视为“记录损坏”,已激活的机器无法继续运行。 +/// 本类只服务于旧记录迁移:不参与日常检查、不生成新记录、也不接受用它签发新授权码。 +/// 读取硬件失败时返回空集合且不抛错,避免让正常的授权检查因迁移探测而失败。 +/// +public static class LegacyHardwareIdentity +{ + // CIM 读取要启动 powershell 子进程,结果按进程生命周期缓存,避免每次授权检查重复读取硬件。 + private static readonly Lazy _boardCodes = new(ReadBoardMachineCodes, LazyThreadSafetyMode.ExecutionAndPublication); + + /// + /// 返回本机在历史版本下可能得到过的机器码,供存储层逐个尝试解密旧记录。 + /// 主板序列号读不到、为厂商占位值时返回空数组;调用方必须把“无法迁移”当作拒绝放行处理。 + /// + public static IReadOnlyList BoardMachineCodes() => _boardCodes.Value; + + /// + /// 计算旧版主板绑定机器码:Windows 通过 CIM 读取 Win32_BaseBoard 的序列号、厂商和型号, + /// Linux 读取 /sys/class/dmi/id 下的 board_serial、board_vendor、board_name。 + /// 标识串拼接顺序与过滤规则必须与当时的 MotherboardIdentity 完全一致,否则算不出同一机器码。 + /// + private static string[] ReadBoardMachineCodes() + { + string serial, vendor, model; + try + { + if (OperatingSystem.IsWindows()) + { + var info = new ProcessStartInfo("powershell.exe") + { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; + foreach (var argument in new[] { "-NoProfile", "-NonInteractive", "-Command", + "$ErrorActionPreference='Stop'; Get-CimInstance Win32_BaseBoard | Select-Object -First 1 SerialNumber,Manufacturer,Product | ConvertTo-Json -Compress" }) + info.ArgumentList.Add(argument); + using var process = Process.Start(info); + if (process is null) return []; + // 同步读取:受限宿主下异步 Task 完成顺序会导致输出被截断,与 DiskIdentity 保持同一读取方式。 + var output = process.StandardOutput.ReadToEnd(); + process.StandardError.ReadToEnd(); + if (!process.WaitForExit(15000)) { process.Kill(true); return []; } + if (process.ExitCode != 0) return []; + using var data = JsonDocument.Parse(output); + var root = data.RootElement; + if (root.ValueKind == JsonValueKind.Array) + { + foreach (var item in root.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Object) { root = item; break; } + } + } + serial = Text(root, "SerialNumber"); + vendor = Text(root, "Manufacturer"); + model = Text(root, "Product"); + } + else if (OperatingSystem.IsLinux()) + { + // 主板序列号在多数发行版下仅 root 可读,读不到即视为无旧记录可迁移,不影响正常授权。 + serial = ReadFile("/sys/class/dmi/id/board_serial"); + vendor = ReadFile("/sys/class/dmi/id/board_vendor"); + model = ReadFile("/sys/class/dmi/id/board_name"); + } + else return []; + } + catch { return []; } + + // 复现旧版校验:过短、全零/全 F/全占位字符或已知出厂占位串都不产生机器码,避免为无序列号主板签发共用码。 + var normalized = serial.Trim().ToUpperInvariant(); + if (normalized.Length < 4 || normalized.All(c => c is '0' or 'F' or '-' or ' ') + || new[] { "DEFAULT", "TO BE FILLED", "UNKNOWN", "NONE", "NOT SPECIFIED", "SYSTEM SERIAL", "INVALID", "N/A", "OEM" } + .Any(normalized.Contains)) + return []; + return [LicenseService.MachineCode($"{vendor.Trim()}|{model.Trim()}|{normalized}")]; + } + + /// 读取 CIM JSON 里的字符串属性;属性缺失或非字符串时按空串处理。 + private static string Text(JsonElement obj, string name) + => obj.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() ?? "" : ""; + + /// 读取 DMI 文件,权限不足或文件缺失时返回空串。 + private static string ReadFile(string path) + { + try { return File.Exists(path) ? File.ReadAllText(path) : ""; } catch { return ""; } + } +} diff --git a/src/SopHelper.CrossPlatform.Engine/Licensing/LicenseService.cs b/src/SopHelper.CrossPlatform.Engine/Licensing/LicenseService.cs index 74bcc03..15949b7 100644 --- a/src/SopHelper.CrossPlatform.Engine/Licensing/LicenseService.cs +++ b/src/SopHelper.CrossPlatform.Engine/Licensing/LicenseService.cs @@ -25,14 +25,27 @@ public sealed class LicenseService private readonly ILicenseStore _store; private readonly string _publicKey; private readonly Func _clock; + + /// 历史主板绑定机器码,仅在记录里的机器码与当前机器码不一致时惰性读取,避免每次启动多一次 CIM 硬件读取。 + private readonly Lazy> _legacyMachines; private readonly object _sync = new(); public string Machine { get; } /// 注入时钟及存储便于验证边界;生产环境使用嵌入公钥,禁止通过配置替换信任根。 - public LicenseService(string machine, ILicenseStore store, string publicKey, Func? clock = null) + /// 本机当前硬件机器码(磁盘固件序列号散列)。 + /// 授权记录存储。 + /// 发行方验签公钥 PEM。 + /// 可注入时钟,默认取当前 UTC。 + /// 历史主板绑定机器码集合,仅用于识别机器码算法升级前的旧记录; + /// 生产调用留空由本机硬件推算,测试传入固定值以覆盖迁移分支。 + public LicenseService(string machine, ILicenseStore store, string publicKey, Func? clock = null, + IReadOnlyList? legacyMachines = null) { if (!IsMachineCode(machine)) throw new ArgumentException("硬件机器码无效"); Machine = machine; _store = store; _publicKey = publicKey; _clock = clock ?? (() => DateTimeOffset.UtcNow); + _legacyMachines = legacyMachines is not null + ? new Lazy>(() => legacyMachines) + : new Lazy>(LegacyHardwareIdentity.BoardMachineCodes, LazyThreadSafetyMode.ExecutionAndPublication); } /// 从程序集读取发行方公钥;私钥不参与客户端构建。 @@ -113,7 +126,15 @@ public sealed class LicenseService var bytes = _store.Read(); if (bytes is null) return new(Machine, now, now, now.AddMonths(1), false, []); var state = JsonSerializer.Deserialize(bytes) ?? throw new InvalidDataException("授权记录为空"); - if (state.Machine != Machine) throw new InvalidDataException("硬件已更换或授权记录来自其他电脑,请联系发行方。"); + if (state.Machine != Machine) + { + // 机器码算法升级(主板固件序列号 → 磁盘固件序列号)后,老记录里的 Machine 是历史机器码。 + // 只有该历史机器码能由本机硬件重新算出时才认这条记录,并把字段改写为当前机器码; + // 复制他机记录或因更换硬件得到的历史码都算不出来,继续拒绝,禁止借升级重置试用或续期。 + if (!_legacyMachines.Value.Contains(state.Machine)) + throw new InvalidDataException("硬件已更换或授权记录来自其他电脑,请联系发行方。"); + state = state with { Machine = Machine }; + } if (state.StartedUtc == default || state.LastUtc < state.StartedUtc || state.ExpiresUtc <= state.StartedUtc || state.UsedIds is null) throw new InvalidDataException("授权记录损坏,请恢复备份并联系发行方。"); return state; diff --git a/src/SopHelper.CrossPlatform.Engine/Licensing/ProtectedLicenseStore.cs b/src/SopHelper.CrossPlatform.Engine/Licensing/ProtectedLicenseStore.cs index feced3c..d68c78e 100644 --- a/src/SopHelper.CrossPlatform.Engine/Licensing/ProtectedLicenseStore.cs +++ b/src/SopHelper.CrossPlatform.Engine/Licensing/ProtectedLicenseStore.cs @@ -10,24 +10,47 @@ using System.Runtime.CompilerServices; namespace SopHelper.Engine.Licensing; -/// 授权记录独立于安装目录;Windows 使用当前账号 DPAPI 并镜像到注册表,避免重装或删单个文件重置试用。 +/// 授权记录独立于安装目录;Windows 使用当前账号 DPAPI 并镜像到注册表,避免重装或删单个文件重置试用。 +/// 记录密钥由硬件机器码派生,因此机器码算法升级时由本类识别历史机器码封装的老记录并就地重封,见 。 public sealed class ProtectedLicenseStore : ILicenseStore { private readonly string _registryPath; private readonly string _path; private readonly byte[] _entropy; + /// + /// 历史硬件绑定(主板序列号)派生的机器码集合。机器码算法从主板改为磁盘序列号后, + /// 老记录仍用主板机器码派生的熵加密;保留这份集合才能把升级前已激活的记录读出来并迁移, + /// 不能因为解不开就当作首次运行重建试用,也不能接受任意来源的密文。 + /// 读取主板信息要启动 CIM 子进程,因此惰性求值:只有当前密钥解不开记录时才真正读取硬件。 + /// + private readonly Lazy> _legacyMachines; + /// 固定用户数据目录,不受配方工作区和程序位置影响;Linux 使用硬件机器码派生密钥及仅本人可读写权限。 public ProtectedLicenseStore(string machine) : this(machine, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - "Bellwether", "AISOP", "license.dat"), @"Software\Bellwether\AISOP\Licensing") { } + "Bellwether", "AISOP", "license.dat"), @"Software\Bellwether\AISOP\Licensing", null) { } /// 仅供友元测试注入隔离路径,生产构造函数始终固定用户授权目录。 internal ProtectedLicenseStore(string machine, string path, string registryPath) + : this(machine, path, registryPath, null) { } + + /// + /// 供测试注入隔离路径与历史机器码集合;生产调用把 legacyMachines 留空,由真实硬件算出历史主板机器码。 + /// 传空数组表示关闭旧记录迁移,用于验证迁移不可用时依然拒绝放行。 + /// + /// 当前硬件机器码,决定记录加解密密钥。 + /// 授权文件路径。 + /// Windows 注册表镜像项路径。 + /// 历史机器码集合;null 表示读取真实硬件推算。 + internal ProtectedLicenseStore(string machine, string path, string registryPath, IReadOnlyList? legacyMachines) { _path = path; _registryPath = registryPath; - _entropy = SHA256.HashData(Encoding.UTF8.GetBytes("AISOP-state-v1|" + machine)); + _entropy = Entropy(machine); + _legacyMachines = legacyMachines is not null + ? new Lazy>(() => legacyMachines) + : new Lazy>(LegacyHardwareIdentity.BoardMachineCodes, LazyThreadSafetyMode.ExecutionAndPublication); } /// 文件和镜像均存在时必须一致;损坏、硬件不匹配和权限错误均上抛,禁止静默重置。 @@ -46,13 +69,13 @@ public sealed class ProtectedLicenseStore : ILicenseStore file ??= mirror; } if (file is null) return null; - return OperatingSystem.IsWindows() ? Dpapi(file, false) : Decrypt(file); + return Unseal(file); } /// 先原子替换文件,再写入相同密文的注册表镜像;任一步失败都必须向调用方报告。 public void Write(byte[] value) { - var encrypted = OperatingSystem.IsWindows() ? Dpapi(value, true) : Encrypt(value); + var encrypted = OperatingSystem.IsWindows() ? Dpapi(value, _entropy, true) : Encrypt(value, _entropy); var directory = Path.GetDirectoryName(_path)!; Directory.CreateDirectory(directory); if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); @@ -69,36 +92,72 @@ public sealed class ProtectedLicenseStore : ILicenseStore } // Linux 没有 DPAPI;此密钥只阻止随意编辑,无法抵御具有本机调试能力的管理员。 - private byte[] Encrypt(byte[] value) + private static byte[] Encrypt(byte[] value, byte[] entropy) { var result = new byte[28 + value.Length]; RandomNumberGenerator.Fill(result.AsSpan(0, 12)); - using var aes = new AesGcm(_entropy, 16); + using var aes = new AesGcm(entropy, 16); aes.Encrypt(result.AsSpan(0, 12), value, result.AsSpan(28), result.AsSpan(12, 16)); return result; } - private byte[] Decrypt(byte[] value) + private static byte[] Decrypt(byte[] value, byte[] entropy) { if (value.Length < 28) throw new InvalidDataException("授权记录损坏"); var result = new byte[value.Length - 28]; - using var aes = new AesGcm(_entropy, 16); + using var aes = new AesGcm(entropy, 16); aes.Decrypt(value.AsSpan(0, 12), value.AsSpan(28), value.AsSpan(12, 16), result); return result; } + /// 按机器码派生密钥熵;历史机器码用同一算法派生,保证旧记录可被识别和解封。 + private static byte[] Entropy(string machine) => SHA256.HashData(Encoding.UTF8.GetBytes("AISOP-state-v1|" + machine)); + + /// + /// 解封记录密文。先用当前机器码派生的密钥;解不开时才读取历史主板机器码逐个尝试, + /// 命中即按当前机器码重新封装文件与注册表镜像,使机器码算法升级不再让已激活机器“记录损坏”。 + /// 参与尝试的历史机器码只能由本机硬件算出,因此他机复制来的记录依旧解不开,禁止借迁移重置试用。 + /// + /// 文件或注册表镜像里的密文。 + /// 明文授权状态;命中历史密钥时会同步把记录改写为当前机器码封装。 + private byte[] Unseal(byte[] file) + { + Exception? failure = null; + try { return Open(file, _entropy); } + catch (Exception error) when (IsUnsealFailure(error)) { failure = error; } + foreach (var legacy in _legacyMachines.Value) + { + try + { + var plain = Open(file, Entropy(legacy)); + Write(plain); + return plain; + } + catch (Exception error) when (IsUnsealFailure(error)) { /* 该历史机器码与本机无关,继续尝试下一个。 */ } + } + throw failure ?? new InvalidDataException("授权记录与本机硬件不匹配,请联系发行方。"); + } + + /// 按平台解封一次;密钥不符在 Windows 表现为 DPAPI 调用失败,在 Linux 表现为 AES-GCM 校验失败。 + private static byte[] Open(byte[] file, byte[] entropy) + => OperatingSystem.IsWindows() ? Dpapi(file, entropy, false) : Decrypt(file, entropy); + + /// 判定异常是否属于“密钥不匹配或密文损坏”;只有这类异常才允许继续尝试历史密钥。 + private static bool IsUnsealFailure(Exception error) + => error is System.ComponentModel.Win32Exception or CryptographicException; + // 使用系统 DPAPI 避免引入额外运行时包;所有非托管缓冲区由当前调用负责释放。 - private byte[] Dpapi(byte[] value, bool protect) + private static byte[] Dpapi(byte[] value, byte[] entropy, bool protect) { var input = new Blob { Length = value.Length, Data = Marshal.AllocHGlobal(value.Length) }; - var entropy = new Blob { Length = _entropy.Length, Data = Marshal.AllocHGlobal(_entropy.Length) }; + var entropyBlob = new Blob { Length = entropy.Length, Data = Marshal.AllocHGlobal(entropy.Length) }; var output = new Blob(); try { Marshal.Copy(value, 0, input.Data, value.Length); - Marshal.Copy(_entropy, 0, entropy.Data, _entropy.Length); + Marshal.Copy(entropy, 0, entropyBlob.Data, entropy.Length); var success = protect - ? CryptProtectData(ref input, null, ref entropy, IntPtr.Zero, IntPtr.Zero, 1, out output) - : CryptUnprotectData(ref input, IntPtr.Zero, ref entropy, IntPtr.Zero, IntPtr.Zero, 1, out output); + ? CryptProtectData(ref input, null, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, 1, out output) + : CryptUnprotectData(ref input, IntPtr.Zero, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, 1, out output); if (!success) throw new Win32Exception(Marshal.GetLastWin32Error(), "授权记录保护校验失败"); var result = new byte[output.Length]; Marshal.Copy(output.Data, result, 0, result.Length); @@ -106,7 +165,7 @@ public sealed class ProtectedLicenseStore : ILicenseStore } finally { - Marshal.FreeHGlobal(input.Data); Marshal.FreeHGlobal(entropy.Data); + Marshal.FreeHGlobal(input.Data); Marshal.FreeHGlobal(entropyBlob.Data); if (output.Data != IntPtr.Zero) LocalFree(output.Data); } } diff --git a/tests/D3Startup.Smoke/LicenseTests.cs b/tests/D3Startup.Smoke/LicenseTests.cs index b49949e..1d1244a 100644 --- a/tests/D3Startup.Smoke/LicenseTests.cs +++ b/tests/D3Startup.Smoke/LicenseTests.cs @@ -1,4 +1,5 @@ using System.Security.Cryptography; +using System.Text; using System.Text.Json; using SopHelper.Engine.Licensing; using Microsoft.Win32; @@ -44,6 +45,40 @@ internal static class LicenseTests var bytes = Convert.FromBase64String(parts[1]); bytes[5] ^= 1; parts[1] = Convert.ToBase64String(bytes); Reject(() => service.Activate(string.Join('.', parts)), "拒绝被篡改的签名内容"); Check(!Create(LicenseService.MachineCode("replacement")).Check().Allowed, "更换硬件后原记录不可使用"); + + // 机器码算法升级(主板固件序列号 → 磁盘固件序列号)后,老记录必须继续有效,只改写机器码字段。 + var legacyMachine = LicenseService.MachineCode("vendor|model|BSS-00000001"); + var usedId = "0123456789abcdef0123456789abcdef"; + var upgradeStore = new MemoryStore(); + var upgradedService = new LicenseService(machine, upgradeStore, issuer.ExportSubjectPublicKeyInfoPem(), () => now, [legacyMachine]); + upgradeStore.Data = JsonSerializer.SerializeToUtf8Bytes(new + { + Machine = legacyMachine, StartedUtc = now.AddDays(-10), LastUtc = now, ExpiresUtc = now.AddDays(20), + Permanent = false, UsedIds = new List { usedId } + }); + var upgraded = upgradedService.Check(); + Check(upgraded.Allowed && upgraded.ExpiresUtc == now.AddDays(20), "机器码算法升级后老授权记录继续有效"); + var migratedJson = JsonDocument.Parse(Encoding.UTF8.GetString(upgradeStore.Data!)).RootElement; + Check(migratedJson.GetProperty("Machine").GetString() == machine && migratedJson.GetProperty("UsedIds")[0].GetString() == usedId, + "迁移只改写机器码字段,保留试用起点和已兑换授权码"); + Check(new LicenseService(machine, new MemoryStore { Data = upgradeStore.Data }, issuer.ExportSubjectPublicKeyInfoPem(), () => now, []).Check().Allowed, + "迁移完成后不再依赖历史硬件标识"); + var foreignStore = new MemoryStore(); + foreignStore.Data = JsonSerializer.SerializeToUtf8Bytes(new + { + Machine = LicenseService.MachineCode("other-vendor|other-model|BSS-00000001"), StartedUtc = now.AddDays(-10), + LastUtc = now, ExpiresUtc = now.AddDays(20), Permanent = false, UsedIds = new List() + }); + Check(!new LicenseService(machine, foreignStore, issuer.ExportSubjectPublicKeyInfoPem(), () => now, [legacyMachine]).Check().Allowed, + "他机主板机器码记录不能借算法升级迁移"); + var noLegacyStore = new MemoryStore(); + noLegacyStore.Data = JsonSerializer.SerializeToUtf8Bytes(new + { + Machine = legacyMachine, StartedUtc = now.AddDays(-10), LastUtc = now, ExpiresUtc = now.AddDays(20), + Permanent = false, UsedIds = new List() + }); + Check(!new LicenseService(machine, noLegacyStore, issuer.ExportSubjectPublicKeyInfoPem(), () => now, []).Check().Allowed, + "本机没有对应历史硬件时拒绝老记录"); now = renewed.ExpiresUtc!.Value; Check(!service.Check().Allowed, "到期时刻立即失效"); now = now.AddDays(5); @@ -89,6 +124,29 @@ internal static class LicenseTests } } + /// + /// 现场排障:按真实磁盘机器码读取本机正式授权记录,打印机器码、历史主板机器码与授权状态。 + /// 调用 与软件启动时的检查完全一致,会把主板绑定时期的旧记录 + /// 迁移为磁盘绑定记录;不签发也不兑换授权码,因此不会消耗客户的码。 + /// + public static string RealStoreCheck() + { + var machine = DiskIdentity.ReadMachineCode(); + var legacy = LegacyHardwareIdentity.BoardMachineCodes(); + // 与生产 ProtectedLicenseStore 相同的正式记录位置,便于支持人员核对文件和注册表镜像。 + var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Bellwether", "AISOP", "license.dat"); + var service = new LicenseService(machine, new ProtectedLicenseStore(machine), LicenseService.ReadIssuerPublicKey()); + var status = service.Check(); + return string.Join(Environment.NewLine, + [ + "当前磁盘机器码:" + machine, + "历史主板机器码:" + (legacy.Count == 0 ? "本机读不到有效主板序列号,旧记录无法迁移" : string.Join(",", legacy)), + "授权文件:" + path + (File.Exists(path) ? "(存在)" : "(缺失)"), + "注册表镜像:HKCU\\Software\\Bellwether\\AISOP\\Licensing" + (OperatingSystem.IsWindows() ? "" : "(非 Windows 不使用)"), + (status.Allowed ? "允许使用:" : "当前不可用:") + status.Message + ]); + } + /// 在固定测试文件与测试专用注册表项验证真实加密、镜像恢复及篡改拒绝,最终只清理这两个测试资源。 private static void CheckProtectedStore(string machine) { @@ -116,6 +174,26 @@ internal static class LicenseTests using (var key = Registry.CurrentUser.OpenSubKey(registryPath, true)!) key.DeleteValue("State"); Check(target.Read()!.SequenceEqual(clear), "镜像缺失时仍保留文件中的原始授权"); Check(Refused(new ProtectedLicenseStore(LicenseService.MachineCode("different-board"), path, registryPath)), "不同硬件无法解密复制的授权记录"); + + // 机器码算法升级:老记录由历史主板机器码封装,升级后要能读出并按当前机器码重新封装文件和镜像。 + var legacyMachine = LicenseService.MachineCode("legacy-vendor|legacy-model|LEGACY0001"); + File.Delete(path); + Registry.CurrentUser.DeleteSubKey(registryPath, false); + new ProtectedLicenseStore(legacyMachine, path, registryPath, []).Write(clear); + Check(new ProtectedLicenseStore(machine, path, registryPath, [legacyMachine]).Read()!.SequenceEqual(clear), + "主板绑定时期的旧授权记录可迁移到磁盘绑定机器码"); + Check(new ProtectedLicenseStore(machine, path, registryPath, []).Read()!.SequenceEqual(clear), + "迁移后文件与注册表镜像均按当前机器码重新封装"); + File.Delete(path); + Check(new ProtectedLicenseStore(machine, path, registryPath, []).Read()!.SequenceEqual(clear), + "注册表镜像同步迁移,删除文件后仍可用当前机器码读取"); + var foreignMachine = LicenseService.MachineCode("foreign-vendor|foreign-model|FOREIGN0001"); + File.Delete(path); + Registry.CurrentUser.DeleteSubKey(registryPath, false); + new ProtectedLicenseStore(foreignMachine, path, registryPath, []).Write(clear); + // 生产环境的历史密钥集合只能由本机硬件算出,绝不会包含签发记录的那台机器的机器码。 + Check(Refused(new ProtectedLicenseStore(machine, path, registryPath, [legacyMachine])), + "他机记录不能借历史密钥迁移"); target.Write(clear); File.WriteAllBytes(path, [1, 2, 3]); Check(Refused(target), "授权文件与镜像不同则拒绝加载"); diff --git a/tests/D3Startup.Smoke/Program.cs b/tests/D3Startup.Smoke/Program.cs index 43efda6..65ffc32 100644 --- a/tests/D3Startup.Smoke/Program.cs +++ b/tests/D3Startup.Smoke/Program.cs @@ -5,6 +5,9 @@ using SopHelper.Engine.Sop; // 复用已有测试工程验证授权状态机,避免创建额外构建目录或重复测试宿主。 if (args.Contains("--license-only")) { LicenseTests.Run(); return; } +// 现场排障:读取本机正式授权记录并打印状态,触发历史主板绑定记录的迁移;不签发、不兑换授权码。 +if (args.Contains("--license-check-real")) { Console.WriteLine(LicenseTests.RealStoreCheck()); return; } + if(args.Length==3&&args[0]=="--djev-live") { var installed=Path.GetFullPath(args[1]);