using System.Security.Cryptography; using System.Text; using System.Text.Json; using ClassNotify.Shared.Models; using Microsoft.Extensions.Logging; namespace ClassNotify.Service.Services; /// /// 防本地系统时间篡改与单调时钟评估器 (Anti-Time-Tamper & Monotonic Clock Trust Evaluator) /// 架构原则: /// 1. Server time is truth (服务端时间为绝对基准) /// 2. Windows 内核 Environment.TickCount64 单调递增 (防运行期倒拨与冻结) /// 3. DPAPI 加密高水位时间戳持久化 (防关机/开机倒拨时钟) /// 4. 离线租约服务端 HMAC 签名校验 (防本地修改文件) /// 5. 发现异常置为 TimeUntrusted (普通通知阻断,L5 紧急广播无条件放行,联网后自愈) /// public sealed class ClockTrustEvaluator { private readonly ILogger _logger; private readonly string _watermarkPath; private static readonly byte[] WatermarkEntropy = Encoding.UTF8.GetBytes("ClassNotify_Time_Watermark_V1"); private readonly object _lock = new(); private DateTimeOffset _highestObservedUtc; private DateTimeOffset _lastCheckLocalUtc; private long _lastTickCount64; private DateTimeOffset? _lastKnownServerUtc; private DateTimeOffset _lastWatermarkSaveUtc; private bool _isTimeUntrusted; private string? _untrustedReason; private readonly string _bootSessionId; public bool IsTimeUntrusted { get { lock (_lock) return _isTimeUntrusted; } } public string? UntrustedReason { get { lock (_lock) return _untrustedReason; } } public ClockTrustEvaluator(ILogger logger) { _logger = logger; var dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify"); Directory.CreateDirectory(dir); _watermarkPath = Path.Combine(dir, "time_watermark.bin"); _bootSessionId = Guid.NewGuid().ToString("N")[..8]; _lastCheckLocalUtc = DateTimeOffset.UtcNow; _lastTickCount64 = Environment.TickCount64; _highestObservedUtc = DateTimeOffset.UtcNow; _lastWatermarkSaveUtc = DateTimeOffset.UtcNow; Initialize(); } private void Initialize() { lock (_lock) { try { if (File.Exists(_watermarkPath)) { var cipher = File.ReadAllBytes(_watermarkPath); var plain = ProtectedData.Unprotect(cipher, WatermarkEntropy, DataProtectionScope.LocalMachine); var json = Encoding.UTF8.GetString(plain); var record = JsonSerializer.Deserialize(json); if (record != null && record.HighestObservedUtcTicks > 0) { var watermarkUtc = new DateTimeOffset(record.HighestObservedUtcTicks, TimeSpan.Zero); _highestObservedUtc = watermarkUtc; var now = DateTimeOffset.UtcNow; // Cold start rollback check (容许 5 分钟的容差以兼容时间校准微调) if (now < watermarkUtc.AddMinutes(-5)) { _isTimeUntrusted = true; _untrustedReason = $"系统时间 ({now:yyyy-MM-dd HH:mm:ss} UTC) 异常落后于历史记录点 ({watermarkUtc:yyyy-MM-dd HH:mm:ss} UTC)"; _logger.LogWarning("CLOCK ROLLBACK DETECTED ON STARTUP: {Reason}", _untrustedReason); return; } if (now > _highestObservedUtc) { _highestObservedUtc = now; } } } else { // First run: establish initial baseline SaveWatermarkInternal(force: true); } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to load time watermark. Will establish fresh baseline upon server sync."); } } } /// /// 记录权威服务端时间。联网且身份认证通过时调用,可立即自愈恢复可信状态 /// public void RecordServerTime(DateTimeOffset serverNowUtc) { lock (_lock) { _lastKnownServerUtc = serverNowUtc; if (serverNowUtc > _highestObservedUtc) { _highestObservedUtc = serverNowUtc; } if (_isTimeUntrusted) { _logger.LogInformation("Time trust self-healed via authoritative server sync: ServerNowUtc={ServerNowUtc:o}", serverNowUtc); _isTimeUntrusted = false; _untrustedReason = null; } SaveWatermarkInternal(force: true); } } /// /// 运行期每 30 秒或心跳时评估时钟可信度 /// public (bool IsUntrusted, string? Reason) Evaluate(DeviceLicenseStatusDto? currentLease) { lock (_lock) { var now = DateTimeOffset.UtcNow; var currentTick = Environment.TickCount64; var deltaLocalSec = (now - _lastCheckLocalUtc).TotalSeconds; var deltaMonotonicMs = currentTick - _lastTickCount64; _lastCheckLocalUtc = now; _lastTickCount64 = currentTick; // 1. Runtime Clock Rollback Check if (deltaLocalSec < -120) // System clock rewound by > 2 minutes { if (deltaLocalSec < -300) // Severe rollback > 5 minutes { _isTimeUntrusted = true; _untrustedReason = $"检测到系统时间发生倒拨跳变 (回退 {Math.Abs(deltaLocalSec):F0} 秒)"; _logger.LogWarning("RUNTIME CLOCK ROLLBACK DETECTED: {Reason}", _untrustedReason); SaveWatermarkInternal(force: true); return (true, _untrustedReason); } else { _logger.LogWarning("Minor clock adjustment detected: {Delta:F0}s backward", deltaLocalSec); } } // 2. Monotonic Freeze Check (uptime moved > 10 min while wall clock moved < 5 sec) if (deltaMonotonicMs > 600_000 && Math.Abs(deltaLocalSec) < 5) { _isTimeUntrusted = true; _untrustedReason = "检测到系统时钟停滞 (单调时间走动但系统时钟冻结)"; _logger.LogWarning("CLOCK FREEZE DETECTED: {Reason}", _untrustedReason); SaveWatermarkInternal(force: true); return (true, _untrustedReason); } // 3. High-Water Mark Invariant if (now < _highestObservedUtc.AddMinutes(-5)) { _isTimeUntrusted = true; _untrustedReason = $"系统时间低于最高安全水位点 ({_highestObservedUtc:yyyy-MM-dd HH:mm:ss})"; _logger.LogWarning("HIGH WATERMARK VIOLATION: {Reason}", _untrustedReason); return (true, _untrustedReason); } if (now > _highestObservedUtc) { _highestObservedUtc = now; } // 4. Offline Lease Integrity & Reverse Check if (currentLease != null) { // Lease issuance cannot be in the future relative to current time (with 5 min tolerance) if (now < currentLease.IssuedAtUtc.AddMinutes(-5)) { _isTimeUntrusted = true; _untrustedReason = "当前系统时间落后于许可证有效签发时间 (租约倒流)"; _logger.LogWarning("LEASE TIME INVERSION: {Reason}", _untrustedReason); return (true, _untrustedReason); } // Verify lease signature if (!string.IsNullOrEmpty(currentLease.LeaseSignature) && !string.IsNullOrEmpty(currentLease.DeviceId)) { var expectedSig = ComputeLeaseSignature(currentLease); if (!string.Equals(expectedSig, currentLease.LeaseSignature, StringComparison.Ordinal)) { _isTimeUntrusted = true; _untrustedReason = "许可证本地租约签名无效 (疑似文件被篡改)"; _logger.LogWarning("LEASE SIGNATURE MISMATCH: Expected={Expected}, Got={Got}", expectedSig, currentLease.LeaseSignature); return (true, _untrustedReason); } } } // 5. Periodic Low-Frequency Persistence (every 5~10 minutes to protect SSD/eMMC) if ((now - _lastWatermarkSaveUtc).TotalMinutes >= 5) { SaveWatermarkInternal(force: false); } return (_isTimeUntrusted, _untrustedReason); } } public static string ComputeLeaseSignature(DeviceLicenseStatusDto dto, string? secretKey = null) { var key = secretKey ?? $"{dto.DeviceId}_ClassNotify_Offline_Lease_2026"; var payload = $"{dto.DeviceId}|{dto.Status}|{dto.Tier}|{dto.LicensedUntilUtc?.ToUnixTimeSeconds()}|{dto.IssuedAtUtc.ToUnixTimeSeconds()}|{dto.OfflineGraceUntilUtc?.ToUnixTimeSeconds()}"; using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)); return Convert.ToBase64String(hash); } public void OnShutdown() { lock (_lock) { SaveWatermarkInternal(force: true); } } private void SaveWatermarkInternal(bool force) { try { var now = DateTimeOffset.UtcNow; var record = new TimeWatermarkRecord { HighestObservedUtcTicks = _highestObservedUtc.UtcTicks, LastServerUtcTicks = _lastKnownServerUtc?.UtcTicks ?? 0, LastSystemUtcTicks = now.UtcTicks, LastTickCount64 = Environment.TickCount64, BootSessionId = _bootSessionId, SavedAtUtc = now }; var json = JsonSerializer.Serialize(record); var plain = Encoding.UTF8.GetBytes(json); var cipher = ProtectedData.Protect(plain, WatermarkEntropy, DataProtectionScope.LocalMachine); var tmpPath = _watermarkPath + ".tmp"; File.WriteAllBytes(tmpPath, cipher); File.Move(tmpPath, _watermarkPath, overwrite: true); _lastWatermarkSaveUtc = now; } catch (Exception ex) { _logger.LogError(ex, "Failed to persist time watermark"); } } private sealed class TimeWatermarkRecord { public long HighestObservedUtcTicks { get; set; } public long LastServerUtcTicks { get; set; } public long LastSystemUtcTicks { get; set; } public long LastTickCount64 { get; set; } public string BootSessionId { get; set; } = string.Empty; public DateTimeOffset SavedAtUtc { get; set; } } }