using System.Runtime.InteropServices; using XFESystem.Tls; namespace XFESystem.NativeRuntime.Application.Security; internal static unsafe class NativeTlsSecurity { [DllImport("xfe_pal", EntryPoint = "xfe_runtime_random_fill")] private static extern int FillNative(byte* destination, uint length); [DllImport("xfe_pal", EntryPoint = "xfe_runtime_random_capabilities")] private static extern uint CapabilitiesNative(); [DllImport("xfe_pal", EntryPoint = "xfe_runtime_utc_filetime")] private static extern ulong UtcFileTimeNative(); internal static readonly ITlsSecurityContext Context = new TlsPlatformSecurityContext(ReadUtc, Fill); internal static uint Capabilities => CapabilitiesNative(); internal static DateTime ReadUtc() { ulong value = UtcFileTimeNative(); if (value == 0 || value > long.MaxValue) throw new InvalidOperationException("HTTPS requires a live firmware UTC clock."); DateTime utc = DateTime.FromFileTimeUtc((long)value); if (utc.Year < 2024) throw new InvalidOperationException("The firmware UTC clock is unavailable or predates the supported epoch."); return utc; } internal static void Fill(Span destination) { if (destination.Length > 1_048_576) throw new ArgumentOutOfRangeException(nameof(destination)); fixed (byte* pointer = destination) if (FillNative(pointer, (uint)destination.Length) != 1) { destination.Clear(); throw new InvalidOperationException("No healthy CPU cryptographic random source is available; HTTPS is refused."); } } internal static uint Random32() { Span bytes = stackalloc byte[4]; Fill(bytes); return (uint)(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24); } }