using System; using System.IO; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Text.Json; using ClassNotify.Shared.Models; namespace ClassNotify.Service.Services; public static class DeviceCredentialProtector { private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("ClassNotify_Device_Credential_V1"); private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true, WriteIndented = true }; public static byte[] Encrypt(byte[] data) { return ProtectedData.Protect(data, Entropy, DataProtectionScope.LocalMachine); } public static byte[] Decrypt(byte[] cipherText) { return ProtectedData.Unprotect(cipherText, Entropy, DataProtectionScope.LocalMachine); } public static DeviceCredentials? LoadCredentials( string filePath, Action? logInfo = null, Action? logWarning = null, Action? logError = null) { if (!File.Exists(filePath)) return null; try { var rawBytes = File.ReadAllBytes(filePath); if (rawBytes.Length == 0) return null; // Check if file is legacy plaintext JSON (starts with '{' after trimming leading whitespace) int firstCharIdx = 0; while (firstCharIdx < rawBytes.Length && char.IsWhiteSpace((char)rawBytes[firstCharIdx])) { firstCharIdx++; } if (firstCharIdx < rawBytes.Length && rawBytes[firstCharIdx] == (byte)'{') { logWarning?.Invoke($"[DeviceCredentialProtector] Detected legacy plaintext credentials at {filePath}. Performing automatic DPAPI migration...", null); var json = Encoding.UTF8.GetString(rawBytes); var creds = JsonSerializer.Deserialize(json, JsonOptions); if (creds != null && !string.IsNullOrEmpty(creds.DeviceId) && !string.IsNullOrEmpty(creds.DeviceToken)) { try { // Transparent auto-migration to DPAPI LocalMachine with hardened ACLs (fail-closed) SaveCredentials(filePath, creds, logInfo, logError); logInfo?.Invoke("[DeviceCredentialProtector] Successfully migrated legacy credentials to DPAPI LocalMachine encrypted storage."); return creds; } catch (Exception migEx) { logError?.Invoke($"[DeviceCredentialProtector] Legacy credential migration failed due to encryption or ACL hardening failure. Failing closed.", migEx); throw; } } } // Otherwise, decrypt ciphertext via DPAPI LocalMachine var decryptedBytes = Decrypt(rawBytes); var decryptedJson = Encoding.UTF8.GetString(decryptedBytes); return JsonSerializer.Deserialize(decryptedJson, JsonOptions); } catch (CryptographicException cryptEx) { logError?.Invoke($"[DeviceCredentialProtector] CryptographicException: Unable to decrypt credentials at {filePath}. Machine key mismatch or corrupted file.", cryptEx); return null; } catch (Exception ex) { logError?.Invoke($"[DeviceCredentialProtector] Failed to load device credentials from {filePath}.", ex); throw; } } public static void SaveCredentials( string filePath, DeviceCredentials credentials, Action? logInfo = null, Action? logError = null) { string? tempPath = null; try { var dir = Path.GetDirectoryName(filePath); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var jsonBytes = JsonSerializer.SerializeToUtf8Bytes(credentials, JsonOptions); var cipherBytes = Encrypt(jsonBytes); tempPath = filePath + ".tmp"; File.WriteAllBytes(tempPath, cipherBytes); // Apply strict NTFS ACLs to temp file before moving (fail-closed if ACL fails) SetHardenedFileAcl(tempPath, logError); File.Move(tempPath, filePath, overwrite: true); tempPath = null; // Successfully moved // Ensure destination file also has hardened ACLs and verify SetHardenedFileAcl(filePath, logError); VerifyHardenedFileAcl(filePath); logInfo?.Invoke($"[DeviceCredentialProtector] Saved DPAPI-encrypted credentials with hardened ACL to {filePath}."); } catch (Exception ex) { if (tempPath != null && File.Exists(tempPath)) { try { File.Delete(tempPath); } catch { } } logError?.Invoke($"[DeviceCredentialProtector] Failed to save encrypted credentials to {filePath}.", ex); throw; } } public static void SetHardenedFileAcl(string filePath, Action? logError = null) { try { var fileInfo = new FileInfo(filePath); var fileSecurity = new FileSecurity(); // Disable inheritance and remove existing inherited rules fileSecurity.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); // SYSTEM: FullControl fileSecurity.AddAccessRule(new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); // Administrators: FullControl fileSecurity.AddAccessRule(new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); // Ordinary Users / Everyone are intentionally omitted (effectively DENIED) fileInfo.SetAccessControl(fileSecurity); } catch (Exception ex) { logError?.Invoke($"[DeviceCredentialProtector] SECURITY: Failed to set hardened NTFS ACL on {filePath}.", ex); throw; // Fail-closed! } } public static void VerifyHardenedFileAcl(string filePath) { var fileInfo = new FileInfo(filePath); var security = fileInfo.GetAccessControl(); if (!security.AreAccessRulesProtected) { throw new InvalidOperationException($"Hardened ACL verification failed on {filePath}: ACL inheritance is not protected."); } var rules = security.GetAccessRules(includeExplicit: true, includeInherited: false, typeof(SecurityIdentifier)); bool systemFullControl = false; bool adminFullControl = false; var localSystemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null).Value; var administratorsSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Value; foreach (FileSystemAccessRule rule in rules) { if (rule.AccessControlType == AccessControlType.Allow) { var sid = rule.IdentityReference.Value; bool isFullControl = (rule.FileSystemRights & FileSystemRights.FullControl) == FileSystemRights.FullControl; if (sid == localSystemSid) { if (isFullControl) systemFullControl = true; } else if (sid == administratorsSid) { if (isFullControl) adminFullControl = true; } else { // Strict allowlist: Any other SID is rejected immediately! throw new InvalidOperationException($"Strict ACL allowlist violation on {filePath}: Unauthorized identity '{sid}' has Allow ACE."); } } } if (!systemFullControl || !adminFullControl) { throw new InvalidOperationException($"Hardened ACL verification failed on {filePath}: SYSTEM or Administrators missing FullControl rights."); } } }