feat(secrets): AES-256-GCM envelope cipher with AAD binding
This commit is contained in:
@@ -4,7 +4,17 @@ namespace ZB.MOM.WW.Secrets.Abstractions;
|
||||
public sealed class MasterKeyUnavailableException(string message) : InvalidOperationException(message);
|
||||
|
||||
/// <summary>Thrown when a secret's ciphertext cannot be decrypted or its authentication tag fails to verify.</summary>
|
||||
public sealed class SecretDecryptionException(string message) : InvalidOperationException(message);
|
||||
public sealed class SecretDecryptionException : InvalidOperationException
|
||||
{
|
||||
/// <summary>Creates the exception with a message describing the decryption failure.</summary>
|
||||
/// <param name="message">The failure description.</param>
|
||||
public SecretDecryptionException(string message) : base(message) { }
|
||||
|
||||
/// <summary>Creates the exception, preserving the underlying cryptographic fault.</summary>
|
||||
/// <param name="message">The failure description.</param>
|
||||
/// <param name="innerException">The original cryptographic exception that caused the failure.</param>
|
||||
public SecretDecryptionException(string message, Exception innerException) : base(message, innerException) { }
|
||||
}
|
||||
|
||||
/// <summary>Thrown when a requested secret does not exist (or is tombstoned) in the store.</summary>
|
||||
public sealed class SecretNotFoundException(string message) : InvalidOperationException(message);
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.Secrets.Crypto;
|
||||
|
||||
/// <summary>
|
||||
/// The default <see cref="ISecretCipher"/>: AES-256-GCM envelope encryption.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Each secret is sealed under a fresh, per-secret 32-byte data-encryption key (DEK). The
|
||||
/// DEK encrypts the UTF-8 plaintext with AES-256-GCM (12-byte nonce, 16-byte tag), binding the
|
||||
/// secret <see cref="SecretName.Value"/> as additional authenticated data (AAD) so ciphertext
|
||||
/// cannot be silently relocated to a different name. The DEK is then <i>wrapped</i> with a second
|
||||
/// AES-256-GCM operation under the master key (KEK) from an <see cref="IMasterKeyProvider"/>,
|
||||
/// binding the provider's <see cref="IMasterKeyProvider.KekId"/> as AAD so a row can only be
|
||||
/// unwrapped by the KEK that is claimed to have sealed it.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// GCM's authentication tag provides constant-time integrity verification, so no additional
|
||||
/// constant-time comparison is required. Every cryptographic failure path — a mismatched tag,
|
||||
/// a wrong or unknown KEK, or any other <see cref="CryptographicException"/> — is surfaced as a
|
||||
/// <see cref="SecretDecryptionException"/>; the cipher never returns a wrong plaintext and never
|
||||
/// leaks a raw cryptographic exception. The transient DEK buffer is always zeroed with
|
||||
/// <see cref="CryptographicOperations.ZeroMemory"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class AesGcmEnvelopeCipher : ISecretCipher
|
||||
{
|
||||
private const int KeySizeBytes = 32; // AES-256
|
||||
private const int NonceSizeBytes = 12; // AES-GCM standard nonce
|
||||
private const int TagSizeBytes = 16; // AES-GCM full tag
|
||||
|
||||
private readonly IMasterKeyProvider _masterKeyProvider;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a cipher that wraps and unwraps DEKs with the master key supplied by
|
||||
/// <paramref name="masterKeyProvider"/>.
|
||||
/// </summary>
|
||||
/// <param name="masterKeyProvider">The source of the AES-256 master key (KEK) and its id.</param>
|
||||
public AesGcmEnvelopeCipher(IMasterKeyProvider masterKeyProvider)
|
||||
{
|
||||
_masterKeyProvider = masterKeyProvider ?? throw new ArgumentNullException(nameof(masterKeyProvider));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public StoredSecret Encrypt(SecretName name, string plaintext, SecretContentType contentType)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plaintext);
|
||||
|
||||
string kekId = _masterKeyProvider.KekId;
|
||||
ReadOnlySpan<byte> masterKey = _masterKeyProvider.GetMasterKey().Span;
|
||||
|
||||
byte[] dek = new byte[KeySizeBytes];
|
||||
try
|
||||
{
|
||||
RandomNumberGenerator.Fill(dek);
|
||||
|
||||
// Layer 1: seal the plaintext under the DEK, binding the secret name as AAD.
|
||||
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
|
||||
byte[] nonce = new byte[NonceSizeBytes];
|
||||
byte[] tag = new byte[TagSizeBytes];
|
||||
byte[] ciphertext = new byte[plaintextBytes.Length];
|
||||
byte[] nameAad = Encoding.UTF8.GetBytes(name.Value);
|
||||
|
||||
RandomNumberGenerator.Fill(nonce);
|
||||
using (var bodyGcm = new AesGcm(dek, TagSizeBytes))
|
||||
{
|
||||
bodyGcm.Encrypt(nonce, plaintextBytes, ciphertext, tag, nameAad);
|
||||
}
|
||||
|
||||
// Layer 2: wrap the DEK under the master key, binding the KEK id as AAD.
|
||||
byte[] wrapNonce = new byte[NonceSizeBytes];
|
||||
byte[] wrapTag = new byte[TagSizeBytes];
|
||||
byte[] wrappedDek = new byte[KeySizeBytes];
|
||||
byte[] kekAad = Encoding.UTF8.GetBytes(kekId);
|
||||
|
||||
RandomNumberGenerator.Fill(wrapNonce);
|
||||
using (var wrapGcm = new AesGcm(masterKey, TagSizeBytes))
|
||||
{
|
||||
wrapGcm.Encrypt(wrapNonce, dek, wrappedDek, wrapTag, kekAad);
|
||||
}
|
||||
|
||||
return new StoredSecret
|
||||
{
|
||||
Name = name,
|
||||
ContentType = contentType,
|
||||
Ciphertext = ciphertext,
|
||||
Nonce = nonce,
|
||||
Tag = tag,
|
||||
WrappedDek = wrappedDek,
|
||||
WrapNonce = wrapNonce,
|
||||
WrapTag = wrapTag,
|
||||
KekId = kekId,
|
||||
Revision = 0,
|
||||
IsDeleted = false,
|
||||
CreatedUtc = default,
|
||||
UpdatedUtc = default,
|
||||
};
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(dek);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Decrypt(StoredSecret secret)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(secret);
|
||||
|
||||
string kekId = _masterKeyProvider.KekId;
|
||||
if (!string.Equals(kekId, secret.KekId, StringComparison.Ordinal))
|
||||
{
|
||||
throw new SecretDecryptionException($"Row wrapped by unknown KEK '{secret.KekId}'.");
|
||||
}
|
||||
|
||||
ReadOnlySpan<byte> masterKey = _masterKeyProvider.GetMasterKey().Span;
|
||||
|
||||
byte[] dek = new byte[KeySizeBytes];
|
||||
try
|
||||
{
|
||||
// Unwrap the DEK under the master key, verifying the KEK-id AAD binding.
|
||||
byte[] kekAad = Encoding.UTF8.GetBytes(secret.KekId);
|
||||
using (var wrapGcm = new AesGcm(masterKey, TagSizeBytes))
|
||||
{
|
||||
wrapGcm.Decrypt(secret.WrapNonce, secret.WrappedDek, secret.WrapTag, dek, kekAad);
|
||||
}
|
||||
|
||||
// Decrypt the body under the DEK, verifying the name AAD binding.
|
||||
byte[] nameAad = Encoding.UTF8.GetBytes(secret.Name.Value);
|
||||
byte[] plaintextBytes = new byte[secret.Ciphertext.Length];
|
||||
using (var bodyGcm = new AesGcm(dek, TagSizeBytes))
|
||||
{
|
||||
bodyGcm.Decrypt(secret.Nonce, secret.Ciphertext, secret.Tag, plaintextBytes, nameAad);
|
||||
}
|
||||
|
||||
return Encoding.UTF8.GetString(plaintextBytes);
|
||||
}
|
||||
catch (AuthenticationTagMismatchException ex)
|
||||
{
|
||||
throw new SecretDecryptionException(
|
||||
$"Failed to decrypt secret '{secret.Name.Value}': authentication tag mismatch.", ex);
|
||||
}
|
||||
catch (CryptographicException ex)
|
||||
{
|
||||
throw new SecretDecryptionException(
|
||||
$"Failed to decrypt secret '{secret.Name.Value}'.", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(dek);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user