| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- using System.Runtime.Versioning;
- using System.Security.Cryptography;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge;
- namespace Admin.NET.DataPlatform.Edge;
- internal sealed class EdgeLocalState(string directory)
- {
- internal string DirectoryPath { get; } = Path.GetFullPath(directory);
- private string KeyPath => Path.Combine(DirectoryPath, "queue-key.dpapi");
- internal void Initialize()
- {
- Directory.CreateDirectory(DirectoryPath);
- if (!OperatingSystem.IsWindows())
- File.SetUnixFileMode(DirectoryPath, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
- }
- internal byte[] ReadKey()
- {
- if (OperatingSystem.IsWindows()) return WindowsKey();
- var credentials = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
- var path = Environment.GetEnvironmentVariable("MDP_EDGE_KEY_FILE")
- ?? (string.IsNullOrEmpty(credentials) ? null : Path.Combine(credentials, "edge-queue-key"));
- if (string.IsNullOrEmpty(path)) throw new EdgeContractException("EDGE_QUEUE_KEY_REQUIRED");
- if ((File.GetUnixFileMode(path) & (UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.OtherRead | UnixFileMode.OtherWrite)) != 0)
- throw new EdgeContractException("EDGE_QUEUE_KEY_PERMISSIONS");
- var key = Convert.FromBase64String(File.ReadAllText(path).Trim());
- return key.Length == 32 ? key : throw new EdgeContractException("EDGE_QUEUE_KEY_INVALID");
- }
- [SupportedOSPlatform("windows")]
- private byte[] WindowsKey()
- {
- if (File.Exists(KeyPath))
- return ProtectedData.Unprotect(File.ReadAllBytes(KeyPath), null, DataProtectionScope.CurrentUser);
- var key = RandomNumberGenerator.GetBytes(32);
- var wrapped = ProtectedData.Protect(key, null, DataProtectionScope.CurrentUser);
- AtomicWrite(KeyPath, wrapped);
- return key;
- }
- internal X509Certificate2? ReadCertificate(byte[] key, bool pending = false)
- {
- var data = ReadEncrypted(pending ? "certificate.pending" : "certificate", key);
- if (data is null) return null;
- try { return new X509Certificate2(data, (string?)null, X509KeyStorageFlags.EphemeralKeySet); }
- finally { CryptographicOperations.ZeroMemory(data); }
- }
- internal void WriteCertificate(X509Certificate2 certificate, byte[] key, bool pending = false)
- {
- var bytes = certificate.Export(X509ContentType.Pfx);
- try { WriteEncrypted(pending ? "certificate.pending" : "certificate", key, bytes); }
- finally { CryptographicOperations.ZeroMemory(bytes); }
- }
- internal void PromoteCertificate() =>
- File.Move(Path.Combine(DirectoryPath, "certificate.pending"), Path.Combine(DirectoryPath, "certificate"), overwrite: true);
- internal EdgeTask? ReadTask(byte[] key)
- {
- var bytes = ReadEncrypted("task", key);
- if (bytes is null) return null;
- try { return JsonSerializer.Deserialize<EdgeTask>(bytes, EdgeProtocol.Json); }
- finally { CryptographicOperations.ZeroMemory(bytes); }
- }
- internal void WriteTask(EdgeTask task, byte[] key)
- {
- var bytes = JsonSerializer.SerializeToUtf8Bytes(task, EdgeProtocol.Json);
- try { WriteEncrypted("task", key, bytes); }
- finally { CryptographicOperations.ZeroMemory(bytes); }
- }
- private byte[]? ReadEncrypted(string name, byte[] key)
- {
- var path = Path.Combine(DirectoryPath, name);
- if (!File.Exists(path)) return null;
- var body = File.ReadAllBytes(path);
- if (body.Length < 28) throw new EdgeContractException("EDGE_LOCAL_STATE_INVALID");
- var bytes = new byte[body.Length - 28];
- using var aes = new AesGcm(key, 16);
- aes.Decrypt(body.AsSpan(0, 12), body.AsSpan(28), body.AsSpan(12, 16), bytes, Encoding.ASCII.GetBytes(name.Split('.')[0]));
- return bytes;
- }
- private void WriteEncrypted(string name, byte[] key, byte[] value)
- {
- var body = new byte[28 + value.Length];
- RandomNumberGenerator.Fill(body.AsSpan(0, 12));
- using var aes = new AesGcm(key, 16);
- aes.Encrypt(body.AsSpan(0, 12), value, body.AsSpan(28), body.AsSpan(12, 16), Encoding.ASCII.GetBytes(name.Split('.')[0]));
- AtomicWrite(Path.Combine(DirectoryPath, name), body);
- }
- internal static void AtomicWrite(string path, byte[] bytes)
- {
- var temporary = path + ".tmp";
- using (var file = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
- {
- if (!OperatingSystem.IsWindows())
- File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite);
- file.Write(bytes);
- file.Flush(flushToDisk: true);
- }
- File.Move(temporary, path, overwrite: true);
- }
- }
|