EdgeLocalState.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System.Runtime.Versioning;
  2. using System.Security.Cryptography;
  3. using System.Security.Cryptography.X509Certificates;
  4. using System.Text;
  5. using System.Text.Json;
  6. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
  7. namespace Admin.NET.DataPlatform.Edge;
  8. internal sealed class EdgeLocalState(string directory)
  9. {
  10. internal string DirectoryPath { get; } = Path.GetFullPath(directory);
  11. private string KeyPath => Path.Combine(DirectoryPath, "queue-key.dpapi");
  12. internal void Initialize()
  13. {
  14. Directory.CreateDirectory(DirectoryPath);
  15. if (!OperatingSystem.IsWindows())
  16. File.SetUnixFileMode(DirectoryPath, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
  17. }
  18. internal byte[] ReadKey()
  19. {
  20. if (OperatingSystem.IsWindows()) return WindowsKey();
  21. var credentials = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
  22. var path = Environment.GetEnvironmentVariable("MDP_EDGE_KEY_FILE")
  23. ?? (string.IsNullOrEmpty(credentials) ? null : Path.Combine(credentials, "edge-queue-key"));
  24. if (string.IsNullOrEmpty(path)) throw new EdgeContractException("EDGE_QUEUE_KEY_REQUIRED");
  25. if ((File.GetUnixFileMode(path) & (UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.OtherRead | UnixFileMode.OtherWrite)) != 0)
  26. throw new EdgeContractException("EDGE_QUEUE_KEY_PERMISSIONS");
  27. var key = Convert.FromBase64String(File.ReadAllText(path).Trim());
  28. return key.Length == 32 ? key : throw new EdgeContractException("EDGE_QUEUE_KEY_INVALID");
  29. }
  30. [SupportedOSPlatform("windows")]
  31. private byte[] WindowsKey()
  32. {
  33. if (File.Exists(KeyPath))
  34. return ProtectedData.Unprotect(File.ReadAllBytes(KeyPath), null, DataProtectionScope.CurrentUser);
  35. var key = RandomNumberGenerator.GetBytes(32);
  36. var wrapped = ProtectedData.Protect(key, null, DataProtectionScope.CurrentUser);
  37. AtomicWrite(KeyPath, wrapped);
  38. return key;
  39. }
  40. internal X509Certificate2? ReadCertificate(byte[] key, bool pending = false)
  41. {
  42. var data = ReadEncrypted(pending ? "certificate.pending" : "certificate", key);
  43. if (data is null) return null;
  44. try { return new X509Certificate2(data, (string?)null, X509KeyStorageFlags.EphemeralKeySet); }
  45. finally { CryptographicOperations.ZeroMemory(data); }
  46. }
  47. internal void WriteCertificate(X509Certificate2 certificate, byte[] key, bool pending = false)
  48. {
  49. var bytes = certificate.Export(X509ContentType.Pfx);
  50. try { WriteEncrypted(pending ? "certificate.pending" : "certificate", key, bytes); }
  51. finally { CryptographicOperations.ZeroMemory(bytes); }
  52. }
  53. internal void PromoteCertificate() =>
  54. File.Move(Path.Combine(DirectoryPath, "certificate.pending"), Path.Combine(DirectoryPath, "certificate"), overwrite: true);
  55. internal EdgeTask? ReadTask(byte[] key)
  56. {
  57. var bytes = ReadEncrypted("task", key);
  58. if (bytes is null) return null;
  59. try { return JsonSerializer.Deserialize<EdgeTask>(bytes, EdgeProtocol.Json); }
  60. finally { CryptographicOperations.ZeroMemory(bytes); }
  61. }
  62. internal void WriteTask(EdgeTask task, byte[] key)
  63. {
  64. var bytes = JsonSerializer.SerializeToUtf8Bytes(task, EdgeProtocol.Json);
  65. try { WriteEncrypted("task", key, bytes); }
  66. finally { CryptographicOperations.ZeroMemory(bytes); }
  67. }
  68. private byte[]? ReadEncrypted(string name, byte[] key)
  69. {
  70. var path = Path.Combine(DirectoryPath, name);
  71. if (!File.Exists(path)) return null;
  72. var body = File.ReadAllBytes(path);
  73. if (body.Length < 28) throw new EdgeContractException("EDGE_LOCAL_STATE_INVALID");
  74. var bytes = new byte[body.Length - 28];
  75. using var aes = new AesGcm(key, 16);
  76. aes.Decrypt(body.AsSpan(0, 12), body.AsSpan(28), body.AsSpan(12, 16), bytes, Encoding.ASCII.GetBytes(name.Split('.')[0]));
  77. return bytes;
  78. }
  79. private void WriteEncrypted(string name, byte[] key, byte[] value)
  80. {
  81. var body = new byte[28 + value.Length];
  82. RandomNumberGenerator.Fill(body.AsSpan(0, 12));
  83. using var aes = new AesGcm(key, 16);
  84. aes.Encrypt(body.AsSpan(0, 12), value, body.AsSpan(28), body.AsSpan(12, 16), Encoding.ASCII.GetBytes(name.Split('.')[0]));
  85. AtomicWrite(Path.Combine(DirectoryPath, name), body);
  86. }
  87. internal static void AtomicWrite(string path, byte[] bytes)
  88. {
  89. var temporary = path + ".tmp";
  90. using (var file = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
  91. {
  92. if (!OperatingSystem.IsWindows())
  93. File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite);
  94. file.Write(bytes);
  95. file.Flush(flushToDisk: true);
  96. }
  97. File.Move(temporary, path, overwrite: true);
  98. }
  99. }