fix(secrets): malformed rows fail as SecretDecryptionException; one KEK snapshot per cipher op (scadaproj#45)
Secrets-004: AesGcmEnvelopeCipher.Decrypt now wraps the ArgumentException AesGcm throws for a wrong-length nonce/tag/wrapped DEK as SecretDecryptionException (as Rewrap already did), so the resolver's decryption-failed audit fires. Secrets-007: new MasterKeySnapshot (key + KekId from one reading, zeroed on Dispose) and a default-implemented IMasterKeyProvider.GetSnapshot(); MasterKeyProviderBase overrides it to resolve the source once and derive the id from that same key. Encrypt/Decrypt/Rewrap take one snapshot per KEK and dispose it, so a key file swapped mid-operation can no longer stamp a row with one key's id and wrap it under another. Intermediate key buffers are zeroed. On-disk format unchanged: a golden row written by the 0.6.5 cipher still decrypts. Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
@@ -21,4 +21,18 @@ public interface IMasterKeyProvider
|
||||
/// to the KEK that wrapped their DEK.
|
||||
/// </summary>
|
||||
string KekId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the key and its <see cref="KekId"/> as one consistent, caller-owned snapshot. The
|
||||
/// cipher takes exactly one snapshot per operation and disposes it (zeroing its key copy).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The default implementation reads <see cref="KekId"/> and then copies
|
||||
/// <see cref="GetMasterKey"/>; a provider whose source can change between those two reads (a
|
||||
/// file or environment variable) should override it to resolve the key once and derive the id
|
||||
/// from that same reading, as <c>MasterKeyProviderBase</c> does.
|
||||
/// </remarks>
|
||||
/// <returns>A snapshot the caller must dispose.</returns>
|
||||
/// <exception cref="MasterKeyUnavailableException">The master key cannot be resolved.</exception>
|
||||
MasterKeySnapshot GetSnapshot() => new(KekId, GetMasterKey().ToArray());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace ZB.MOM.WW.Secrets.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// One consistent reading of a master key (KEK): the 32 key bytes together with the
|
||||
/// <see cref="IMasterKeyProvider.KekId"/> that identifies <i>those</i> bytes. Obtained from
|
||||
/// <see cref="IMasterKeyProvider.GetSnapshot"/> once per cipher operation, so the id stamped on a
|
||||
/// row and the key that wraps it can never come from two different reads of a source that changed
|
||||
/// in between (a key file replaced mid-operation).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The snapshot owns its key buffer: <see cref="Dispose"/> zeroes it with
|
||||
/// <see cref="CryptographicOperations.ZeroMemory"/>. Always dispose a snapshot
|
||||
/// (<c>using var snapshot = provider.GetSnapshot();</c>) and never retain <see cref="Key"/> past it.
|
||||
/// </remarks>
|
||||
public sealed class MasterKeySnapshot : IDisposable
|
||||
{
|
||||
private readonly byte[] _key;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a snapshot that takes ownership of <paramref name="key"/> (it is zeroed on
|
||||
/// <see cref="Dispose"/>; pass a buffer nothing else uses).
|
||||
/// </summary>
|
||||
/// <param name="kekId">The non-secret id of <paramref name="key"/>.</param>
|
||||
/// <param name="key">The key bytes; ownership transfers to the snapshot.</param>
|
||||
public MasterKeySnapshot(string kekId, byte[] key)
|
||||
{
|
||||
KekId = kekId ?? throw new ArgumentNullException(nameof(kekId));
|
||||
_key = key ?? throw new ArgumentNullException(nameof(key));
|
||||
}
|
||||
|
||||
/// <summary>The non-secret identifier of <see cref="Key"/>.</summary>
|
||||
public string KekId { get; }
|
||||
|
||||
/// <summary>The key bytes. Valid only until <see cref="Dispose"/>, which zeroes them.</summary>
|
||||
public ReadOnlyMemory<byte> Key => _key;
|
||||
|
||||
/// <summary>Zeroes the key buffer.</summary>
|
||||
public void Dispose() => CryptographicOperations.ZeroMemory(_key);
|
||||
}
|
||||
@@ -22,8 +22,15 @@ namespace ZB.MOM.WW.Secrets.Crypto;
|
||||
/// 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"/>.
|
||||
/// leaks a raw cryptographic exception. A malformed row (a wrong-length nonce, tag or wrapped DEK,
|
||||
/// which <see cref="AesGcm"/> reports as <see cref="ArgumentException"/>) fails the same way. The
|
||||
/// transient DEK buffer is always zeroed with <see cref="CryptographicOperations.ZeroMemory"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Every operation takes exactly one <see cref="MasterKeySnapshot"/> per KEK
|
||||
/// (<see cref="IMasterKeyProvider.GetSnapshot"/>), so the KEK id stamped on or checked against a row
|
||||
/// and the key used for it always come from the same reading, and the snapshot's key copy is zeroed
|
||||
/// when the operation ends.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class AesGcmEnvelopeCipher : ISecretCipher
|
||||
@@ -49,8 +56,9 @@ public sealed class AesGcmEnvelopeCipher : ISecretCipher
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plaintext);
|
||||
|
||||
string kekId = _masterKeyProvider.KekId;
|
||||
ReadOnlySpan<byte> masterKey = _masterKeyProvider.GetMasterKey().Span;
|
||||
using MasterKeySnapshot kek = _masterKeyProvider.GetSnapshot();
|
||||
string kekId = kek.KekId;
|
||||
ReadOnlySpan<byte> masterKey = kek.Key.Span;
|
||||
|
||||
byte[] dek = new byte[KeySizeBytes];
|
||||
try
|
||||
@@ -110,13 +118,13 @@ public sealed class AesGcmEnvelopeCipher : ISecretCipher
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(secret);
|
||||
|
||||
string kekId = _masterKeyProvider.KekId;
|
||||
if (!string.Equals(kekId, secret.KekId, StringComparison.Ordinal))
|
||||
using MasterKeySnapshot kek = _masterKeyProvider.GetSnapshot();
|
||||
if (!string.Equals(kek.KekId, secret.KekId, StringComparison.Ordinal))
|
||||
{
|
||||
throw new SecretDecryptionException($"Row wrapped by unknown KEK '{secret.KekId}'.");
|
||||
}
|
||||
|
||||
ReadOnlySpan<byte> masterKey = _masterKeyProvider.GetMasterKey().Span;
|
||||
ReadOnlySpan<byte> masterKey = kek.Key.Span;
|
||||
|
||||
byte[] dek = new byte[KeySizeBytes];
|
||||
try
|
||||
@@ -148,6 +156,15 @@ public sealed class AesGcmEnvelopeCipher : ISecretCipher
|
||||
throw new SecretDecryptionException(
|
||||
$"Failed to decrypt secret '{secret.Name.Value}'.", ex);
|
||||
}
|
||||
// AesGcm throws ArgumentException for a wrong-length nonce or tag, or a ciphertext/plaintext
|
||||
// length mismatch (a WrappedDek that is not 32 bytes): a corrupt or truncated row. It is a
|
||||
// decryption failure like any other, so callers (the resolver's decryption-failed audit)
|
||||
// classify it correctly (Secrets-004). Mirrors Rewrap.
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
throw new SecretDecryptionException(
|
||||
$"Failed to decrypt secret '{secret.Name.Value}': the row is malformed.", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(dek);
|
||||
@@ -161,18 +178,21 @@ public sealed class AesGcmEnvelopeCipher : ISecretCipher
|
||||
ArgumentNullException.ThrowIfNull(oldKek);
|
||||
ArgumentNullException.ThrowIfNull(newKek);
|
||||
|
||||
using MasterKeySnapshot oldSnapshot = oldKek.GetSnapshot();
|
||||
|
||||
// Fail closed if the row is not actually wrapped by the supplied old KEK — a caller must
|
||||
// not silently "rewrap" a row that is already on a different key.
|
||||
if (!string.Equals(secret.KekId, oldKek.KekId, StringComparison.Ordinal))
|
||||
if (!string.Equals(secret.KekId, oldSnapshot.KekId, StringComparison.Ordinal))
|
||||
{
|
||||
throw new SecretDecryptionException(
|
||||
$"Cannot rewrap secret '{secret.Name.Value}': row is wrapped by KEK '{secret.KekId}', " +
|
||||
$"not the supplied old KEK '{oldKek.KekId}'.");
|
||||
$"not the supplied old KEK '{oldSnapshot.KekId}'.");
|
||||
}
|
||||
|
||||
ReadOnlySpan<byte> oldMasterKey = oldKek.GetMasterKey().Span;
|
||||
ReadOnlySpan<byte> newMasterKey = newKek.GetMasterKey().Span;
|
||||
string newKekId = newKek.KekId;
|
||||
using MasterKeySnapshot newSnapshot = newKek.GetSnapshot();
|
||||
ReadOnlySpan<byte> oldMasterKey = oldSnapshot.Key.Span;
|
||||
ReadOnlySpan<byte> newMasterKey = newSnapshot.Key.Span;
|
||||
string newKekId = newSnapshot.KekId;
|
||||
|
||||
byte[] dek = new byte[KeySizeBytes];
|
||||
try
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
|
||||
@@ -45,6 +46,7 @@ public sealed class FileMasterKeyProvider : MasterKeyProviderBase
|
||||
|
||||
// Otherwise treat the content as base64 text.
|
||||
string text = Encoding.UTF8.GetString(raw).Trim();
|
||||
CryptographicOperations.ZeroMemory(raw);
|
||||
try
|
||||
{
|
||||
return Convert.FromBase64String(text);
|
||||
|
||||
@@ -13,6 +13,11 @@ namespace ZB.MOM.WW.Secrets.MasterKey;
|
||||
/// file value takes effect without recreating the provider. <see cref="KekId"/> is likewise derived
|
||||
/// from the currently resolved key (unless an explicit id is configured), so it stays stable for a
|
||||
/// given key and shifts only when the key itself changes.
|
||||
/// <para>
|
||||
/// <see cref="GetSnapshot"/> resolves the source <b>once</b> and derives the id from that same
|
||||
/// reading, so a key file replaced mid-operation can never produce a row stamped with one key's id
|
||||
/// and wrapped under another (Secrets-007). Intermediate key buffers are zeroed.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public abstract class MasterKeyProviderBase : IMasterKeyProvider
|
||||
{
|
||||
@@ -45,7 +50,32 @@ public abstract class MasterKeyProviderBase : IMasterKeyProvider
|
||||
return explicitId;
|
||||
}
|
||||
|
||||
return DeriveKekId(ResolveValidatedKey());
|
||||
byte[] key = ResolveValidatedKey();
|
||||
try
|
||||
{
|
||||
return DeriveKekId(key);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public MasterKeySnapshot GetSnapshot()
|
||||
{
|
||||
byte[] key = ResolveValidatedKey();
|
||||
try
|
||||
{
|
||||
string? explicitId = _options.KekId;
|
||||
string kekId = string.IsNullOrEmpty(explicitId) ? DeriveKekId(key) : explicitId;
|
||||
return new MasterKeySnapshot(kekId, key);
|
||||
}
|
||||
catch
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(key);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +84,10 @@ public abstract class MasterKeyProviderBase : IMasterKeyProvider
|
||||
/// <see cref="MasterKeyUnavailableException"/> when the source is missing or malformed; length
|
||||
/// validation is applied by the base class.
|
||||
/// </summary>
|
||||
/// <returns>The resolved key bytes (any length; validated by the caller).</returns>
|
||||
/// <returns>
|
||||
/// The resolved key bytes (any length; validated by the caller), in a <b>freshly allocated</b>
|
||||
/// buffer the caller owns: the base class zeroes it after use, so never return a cached array.
|
||||
/// </returns>
|
||||
protected abstract byte[] ResolveKeyBytes();
|
||||
|
||||
private byte[] ResolveValidatedKey()
|
||||
@@ -62,6 +95,7 @@ public abstract class MasterKeyProviderBase : IMasterKeyProvider
|
||||
byte[] key = ResolveKeyBytes();
|
||||
if (key.Length != KeySizeBytes)
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(key);
|
||||
throw new MasterKeyUnavailableException(
|
||||
$"Master key must be exactly {KeySizeBytes} bytes (AES-256) but was {key.Length} bytes.");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user