feat(windows): add DPAPI token protection
Dpapi.Protect/Unprotect wrap CryptProtectData/CryptUnprotectData in the current-user scope with optional entropy and no UI; decrypted native buffers are zeroed before LocalFree. String helpers return Base64 for JSON settings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
2 files changed
+159
No files matched your search
@@ -0,0 +1,111 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Titano.Core.Windows.Security;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static unsafe partial class Dpapi
|
||||
{
|
||||
private const uint CRYPTPROTECT_UI_FORBIDDEN = 0x1;
|
||||
|
||||
/// <exception cref="CryptographicException">Encryption failed.</exception>
|
||||
public static byte[] Protect(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="CryptographicException">The data was protected by another user, tampered with, or the entropy differs.</exception>
|
||||
public static byte[] Unprotect(ReadOnlySpan<byte> protectedData, ReadOnlySpan<byte> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Protects a UTF-8 string and returns Base64, convenient for JSON settings.</summary>
|
||||
public static string ProtectString(string value, ReadOnlySpan<byte> entropy = default)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(value);
|
||||
try
|
||||
{
|
||||
return Convert.ToBase64String(Protect(bytes, entropy));
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reverses <see cref="ProtectString"/>.</summary>
|
||||
/// <exception cref="FormatException">The text is not Base64.</exception>
|
||||
/// <exception cref="CryptographicException">The data cannot be decrypted by this user with this entropy.</exception>
|
||||
public static string UnprotectString(string protectedBase64, ReadOnlySpan<byte> 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<byte>(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);
|
||||
}
|
||||
@@ -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<CryptographicException>(() => Dpapi.Unprotect(protectedData, "other"u8));
|
||||
Assert.Throws<CryptographicException>(() => Dpapi.Unprotect(protectedData));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TamperedDataIsRejected()
|
||||
{
|
||||
var protectedData = Dpapi.Protect(Secret);
|
||||
protectedData[^1] ^= 0x5A;
|
||||
Assert.Throws<CryptographicException>(() => 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([])));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user