125 lines
6.2 KiB
C#
125 lines
6.2 KiB
C#
using System.ComponentModel;
|
||
using System.Runtime.InteropServices;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using Microsoft.Win32;
|
||
using System.Runtime.CompilerServices;
|
||
|
||
// 存储集成测试必须使用专用目录与注册表项,不能接触当前账号的真实试用记录。
|
||
[assembly: InternalsVisibleTo("D3Startup.Smoke")]
|
||
|
||
namespace SopHelper.Engine.Licensing;
|
||
|
||
/// <summary>授权记录独立于安装目录;Windows 使用当前账号 DPAPI 并镜像到注册表,避免重装或删单个文件重置试用。</summary>
|
||
public sealed class ProtectedLicenseStore : ILicenseStore
|
||
{
|
||
private readonly string _registryPath;
|
||
private readonly string _path;
|
||
private readonly byte[] _entropy;
|
||
|
||
/// <summary>固定用户数据目录,不受配方工作区和程序位置影响;Linux 使用硬件机器码派生密钥及仅本人可读写权限。</summary>
|
||
public ProtectedLicenseStore(string machine)
|
||
: this(machine, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||
"Bellwether", "AISOP", "license.dat"), @"Software\Bellwether\AISOP\Licensing") { }
|
||
|
||
/// <summary>仅供友元测试注入隔离路径,生产构造函数始终固定用户授权目录。</summary>
|
||
internal ProtectedLicenseStore(string machine, string path, string registryPath)
|
||
{
|
||
_path = path;
|
||
_registryPath = registryPath;
|
||
_entropy = SHA256.HashData(Encoding.UTF8.GetBytes("AISOP-state-v1|" + machine));
|
||
}
|
||
|
||
/// <summary>文件和镜像均存在时必须一致;损坏、硬件不匹配和权限错误均上抛,禁止静默重置。</summary>
|
||
public byte[]? Read()
|
||
{
|
||
byte[]? file = File.Exists(_path) ? File.ReadAllBytes(_path) : null;
|
||
if (OperatingSystem.IsWindows())
|
||
{
|
||
using var key = Registry.CurrentUser.OpenSubKey(_registryPath);
|
||
var mirrorValue = key?.GetValue("State");
|
||
if (mirrorValue is not null && mirrorValue is not byte[])
|
||
throw new InvalidDataException("授权注册表记录类型错误");
|
||
var mirror = mirrorValue as byte[];
|
||
if (file is not null && mirror is not null && !file.SequenceEqual(mirror))
|
||
throw new InvalidDataException("授权文件与注册表记录不一致,请恢复一致的备份并联系发行方。");
|
||
file ??= mirror;
|
||
}
|
||
if (file is null) return null;
|
||
return OperatingSystem.IsWindows() ? Dpapi(file, false) : Decrypt(file);
|
||
}
|
||
|
||
/// <summary>先原子替换文件,再写入相同密文的注册表镜像;任一步失败都必须向调用方报告。</summary>
|
||
public void Write(byte[] value)
|
||
{
|
||
var encrypted = OperatingSystem.IsWindows() ? Dpapi(value, true) : Encrypt(value);
|
||
var directory = Path.GetDirectoryName(_path)!;
|
||
Directory.CreateDirectory(directory);
|
||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||
var temporary = _path + ".tmp";
|
||
File.WriteAllBytes(temporary, encrypted);
|
||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||
File.Move(temporary, _path, true);
|
||
if (OperatingSystem.IsWindows())
|
||
{
|
||
using var key = Registry.CurrentUser.CreateSubKey(_registryPath);
|
||
key.SetValue("State", encrypted, RegistryValueKind.Binary);
|
||
key.Flush();
|
||
}
|
||
}
|
||
|
||
// Linux 没有 DPAPI;此密钥只阻止随意编辑,无法抵御具有本机调试能力的管理员。
|
||
private byte[] Encrypt(byte[] value)
|
||
{
|
||
var result = new byte[28 + value.Length];
|
||
RandomNumberGenerator.Fill(result.AsSpan(0, 12));
|
||
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)
|
||
{
|
||
if (value.Length < 28) throw new InvalidDataException("授权记录损坏");
|
||
var result = new byte[value.Length - 28];
|
||
using var aes = new AesGcm(_entropy, 16);
|
||
aes.Decrypt(value.AsSpan(0, 12), value.AsSpan(28), value.AsSpan(12, 16), result);
|
||
return result;
|
||
}
|
||
|
||
// 使用系统 DPAPI 避免引入额外运行时包;所有非托管缓冲区由当前调用负责释放。
|
||
private byte[] Dpapi(byte[] value, 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 output = new Blob();
|
||
try
|
||
{
|
||
Marshal.Copy(value, 0, input.Data, value.Length);
|
||
Marshal.Copy(_entropy, 0, entropy.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);
|
||
if (!success) throw new Win32Exception(Marshal.GetLastWin32Error(), "授权记录保护校验失败");
|
||
var result = new byte[output.Length];
|
||
Marshal.Copy(output.Data, result, 0, result.Length);
|
||
return result;
|
||
}
|
||
finally
|
||
{
|
||
Marshal.FreeHGlobal(input.Data); Marshal.FreeHGlobal(entropy.Data);
|
||
if (output.Data != IntPtr.Zero) LocalFree(output.Data);
|
||
}
|
||
}
|
||
|
||
[StructLayout(LayoutKind.Sequential)]
|
||
private struct Blob { public int Length; public IntPtr Data; }
|
||
[DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||
[return: MarshalAs(UnmanagedType.Bool)]
|
||
private static extern bool CryptProtectData(ref Blob input, string? description, ref Blob entropy, IntPtr reserved, IntPtr prompt, int flags, out Blob output);
|
||
[DllImport("crypt32.dll", SetLastError = true)]
|
||
[return: MarshalAs(UnmanagedType.Bool)]
|
||
private static extern bool CryptUnprotectData(ref Blob input, IntPtr description, ref Blob entropy, IntPtr reserved, IntPtr prompt, int flags, out Blob output);
|
||
[DllImport("kernel32.dll")]
|
||
private static extern IntPtr LocalFree(IntPtr memory);
|
||
}
|