EdgeLocalState.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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
  45. {
  46. // Schannel needs a user key container for certificates used in TLS.
  47. var flags = OperatingSystem.IsWindows() ? X509KeyStorageFlags.UserKeySet : X509KeyStorageFlags.EphemeralKeySet;
  48. return new X509Certificate2(data, (string?)null, flags);
  49. }
  50. finally { CryptographicOperations.ZeroMemory(data); }
  51. }
  52. internal void WriteCertificate(X509Certificate2 certificate, byte[] key, bool pending = false)
  53. {
  54. var bytes = certificate.Export(X509ContentType.Pfx);
  55. try { WriteEncrypted(pending ? "certificate.pending" : "certificate", key, bytes); }
  56. finally { CryptographicOperations.ZeroMemory(bytes); }
  57. }
  58. internal void PromoteCertificate() =>
  59. File.Move(Path.Combine(DirectoryPath, "certificate.pending"), Path.Combine(DirectoryPath, "certificate"), overwrite: true);
  60. internal EdgeTask? ReadTask(byte[] key)
  61. {
  62. var bytes = ReadEncrypted("task", key);
  63. if (bytes is null) return null;
  64. try { return JsonSerializer.Deserialize<EdgeTask>(bytes, EdgeProtocol.Json); }
  65. finally { CryptographicOperations.ZeroMemory(bytes); }
  66. }
  67. internal void WriteTask(EdgeTask task, byte[] key)
  68. {
  69. var bytes = JsonSerializer.SerializeToUtf8Bytes(task, EdgeProtocol.Json);
  70. try { WriteEncrypted("task", key, bytes); }
  71. finally { CryptographicOperations.ZeroMemory(bytes); }
  72. }
  73. private byte[]? ReadEncrypted(string name, byte[] key)
  74. {
  75. var path = Path.Combine(DirectoryPath, name);
  76. if (!File.Exists(path)) return null;
  77. var body = File.ReadAllBytes(path);
  78. if (body.Length < 28) throw new EdgeContractException("EDGE_LOCAL_STATE_INVALID");
  79. var bytes = new byte[body.Length - 28];
  80. using var aes = new AesGcm(key, 16);
  81. aes.Decrypt(body.AsSpan(0, 12), body.AsSpan(28), body.AsSpan(12, 16), bytes, Encoding.ASCII.GetBytes(name.Split('.')[0]));
  82. return bytes;
  83. }
  84. private void WriteEncrypted(string name, byte[] key, byte[] value)
  85. {
  86. var body = new byte[28 + value.Length];
  87. RandomNumberGenerator.Fill(body.AsSpan(0, 12));
  88. using var aes = new AesGcm(key, 16);
  89. aes.Encrypt(body.AsSpan(0, 12), value, body.AsSpan(28), body.AsSpan(12, 16), Encoding.ASCII.GetBytes(name.Split('.')[0]));
  90. AtomicWrite(Path.Combine(DirectoryPath, name), body);
  91. }
  92. internal static void AtomicWrite(string path, byte[] bytes)
  93. {
  94. var temporary = path + ".tmp";
  95. using (var file = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
  96. {
  97. if (!OperatingSystem.IsWindows())
  98. File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite);
  99. file.Write(bytes);
  100. file.Flush(flushToDisk: true);
  101. }
  102. File.Move(temporary, path, overwrite: true);
  103. }
  104. }