diff --git a/src/Titano.Core.Windows/Security/Dpapi.cs b/src/Titano.Core.Windows/Security/Dpapi.cs new file mode 100644 index 00000000..3b0b4589 --- /dev/null +++ b/src/Titano.Core.Windows/Security/Dpapi.cs @@ -0,0 +1,111 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace Titano.Core.Windows.Security; + +/// +/// Windows Data Protection API in the current-user scope (BRIEF §15): secrets such as server tokens are encrypted +/// with a key derived from the user's logon credentials, so only the same Windows user can decrypt them. +/// Optional entropy binds a secret to a purpose (it must be supplied again to decrypt). +/// +public static unsafe partial class Dpapi +{ + private const uint CRYPTPROTECT_UI_FORBIDDEN = 0x1; + + /// Encryption failed. + public static byte[] Protect(ReadOnlySpan plaintext, ReadOnlySpan entropy = default) + { + // An empty span pins to null, but the API wants a valid pointer even for zero bytes. + byte empty = 0; + fixed (byte* input = plaintext) + fixed (byte* salt = entropy) + { + var inputBlob = new DataBlob { Size = (uint)plaintext.Length, Data = input == null ? &empty : input }; + var entropyBlob = new DataBlob { Size = (uint)entropy.Length, Data = salt }; + DataBlob output = default; + if (!CryptProtectData(&inputBlob, null, entropy.IsEmpty ? null : &entropyBlob, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &output)) + throw new CryptographicException(Marshal.GetLastPInvokeErrorMessage()); + return TakeOutput(output, clear: false); + } + } + + /// The data was protected by another user, tampered with, or the entropy differs. + public static byte[] Unprotect(ReadOnlySpan protectedData, ReadOnlySpan entropy = default) + { + byte empty = 0; + fixed (byte* input = protectedData) + fixed (byte* salt = entropy) + { + var inputBlob = new DataBlob { Size = (uint)protectedData.Length, Data = input == null ? &empty : input }; + var entropyBlob = new DataBlob { Size = (uint)entropy.Length, Data = salt }; + DataBlob output = default; + if (!CryptUnprotectData(&inputBlob, null, entropy.IsEmpty ? null : &entropyBlob, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &output)) + throw new CryptographicException(Marshal.GetLastPInvokeErrorMessage()); + return TakeOutput(output, clear: true); + } + } + + /// Protects a UTF-8 string and returns Base64, convenient for JSON settings. + public static string ProtectString(string value, ReadOnlySpan entropy = default) + { + var bytes = Encoding.UTF8.GetBytes(value); + try + { + return Convert.ToBase64String(Protect(bytes, entropy)); + } + finally + { + CryptographicOperations.ZeroMemory(bytes); + } + } + + /// Reverses . + /// The text is not Base64. + /// The data cannot be decrypted by this user with this entropy. + public static string UnprotectString(string protectedBase64, ReadOnlySpan entropy = default) + { + var bytes = Unprotect(Convert.FromBase64String(protectedBase64), entropy); + try + { + return Encoding.UTF8.GetString(bytes); + } + finally + { + CryptographicOperations.ZeroMemory(bytes); + } + } + + private static byte[] TakeOutput(DataBlob output, bool clear) + { + try + { + var native = new Span(output.Data, (int)output.Size); + var result = native.ToArray(); + if (clear) CryptographicOperations.ZeroMemory(native); + return result; + } + finally + { + LocalFree((nint)output.Data); + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct DataBlob + { + public uint Size; + public byte* Data; + } + + [LibraryImport("crypt32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CryptProtectData(DataBlob* dataIn, char* description, DataBlob* entropy, nint reserved, nint prompt, uint flags, DataBlob* dataOut); + + [LibraryImport("crypt32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CryptUnprotectData(DataBlob* dataIn, char** description, DataBlob* entropy, nint reserved, nint prompt, uint flags, DataBlob* dataOut); + + [LibraryImport("kernel32.dll")] + private static partial nint LocalFree(nint memory); +} diff --git a/tests/Titano.Core.Windows.Tests/Security/DpapiTests.cs b/tests/Titano.Core.Windows.Tests/Security/DpapiTests.cs new file mode 100644 index 00000000..eed58197 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Security/DpapiTests.cs @@ -0,0 +1,48 @@ +using System.Security.Cryptography; +using System.Text; +using Titano.Core.Windows.Security; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Security; + +[WindowsOnly] +public sealed class DpapiTests +{ + private static readonly byte[] Secret = Encoding.UTF8.GetBytes("titano-refresh-token-0123456789"); + + [Test] + public void RoundTripsBytes() + { + var protectedData = Dpapi.Protect(Secret); + Assert.False(protectedData.AsSpan().SequenceEqual(Secret), "ciphertext equals plaintext"); + Assert.Greater(protectedData.Length, Secret.Length); + Assert.BytesEqual(Secret, Dpapi.Unprotect(protectedData)); + } + + [Test] + public void EntropyMustMatch() + { + var entropy = "Titano.Uploader.Token"u8.ToArray(); + var protectedData = Dpapi.Protect(Secret, entropy); + Assert.BytesEqual(Secret, Dpapi.Unprotect(protectedData, entropy)); + Assert.Throws(() => Dpapi.Unprotect(protectedData, "other"u8)); + Assert.Throws(() => Dpapi.Unprotect(protectedData)); + } + + [Test] + public void TamperedDataIsRejected() + { + var protectedData = Dpapi.Protect(Secret); + protectedData[^1] ^= 0x5A; + Assert.Throws(() => Dpapi.Unprotect(protectedData)); + } + + [Test] + public void RoundTripsStringsAndEmptyValues() + { + var stored = Dpapi.ProtectString("päss wörd ✓"); + Assert.Equal("päss wörd ✓", Dpapi.UnprotectString(stored)); + Assert.Equal(string.Empty, Dpapi.UnprotectString(Dpapi.ProtectString(string.Empty))); + Assert.Empty(Dpapi.Unprotect(Dpapi.Protect([]))); + } +}