diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.Encryption.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.Encryption.cs
index d3302e0f58..eec8ebe403 100644
--- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.Encryption.cs
+++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.Encryption.cs
@@ -792,30 +792,125 @@ private void PrepareTransparentEncryptionFinallyBlock(
/// Readonly dictionary with the map of parameter encryption rpc requests with the corresponding original rpc requests.
/// Indicates if this is a retry from a failed call.
private void ReadDescribeEncryptionParameterResults(
- SqlDataReader ds, // @TODO: Rename something more obvious
+ SqlDataReader ds,
ReadOnlyDictionary<_SqlRPC, _SqlRPC> describeParameterEncryptionRpcOriginalRpcMap,
bool isRetry)
{
- foreach (byte[] attestationInfo in ReadDescribeEncryptionParameterResultsCore(ds, describeParameterEncryptionRpcOriginalRpcMap))
+ PendingColumnEncryptionKeyOperations pending = new PendingColumnEncryptionKeyOperations();
+ int verifiedCount = 0;
+ foreach (byte[] attestationInfo in ReadDescribeEncryptionParameterResultsCore(ds, describeParameterEncryptionRpcOriginalRpcMap, pending))
{
+ // Reject untrusted keys before attestation creates and caches an enclave session.
+ verifiedCount = VerifyPendingColumnMasterKeySignatures(pending, verifiedCount);
EnclaveDelegate.Instance.CreateEnclaveSession(
_activeConnection.AttestationProtocol, _activeConnection.Parser.EnclaveType,
GetEnclaveSessionParameters(), attestationInfo, enclaveAttestationParameters,
customData, customDataLength, isRetry);
enclaveAttestationParameters = null;
}
+
+ VerifyPendingColumnMasterKeySignatures(pending, verifiedCount);
+
+ IReadOnlyList keyDecryptions = pending.KeyDecryptions;
+ for (int i = 0; i < keyDecryptions.Count; i++)
+ {
+ SqlSecurityUtility.DecryptSymmetricKey(keyDecryptions[i], _activeConnection, this);
+ }
+
+ CacheQueryMetadataIfNeeded();
+ }
+
+ ///
+ /// Verifies the column master key signatures recorded after the first entries.
+ ///
+ /// The number of signatures verified so far.
+ private int VerifyPendingColumnMasterKeySignatures(PendingColumnEncryptionKeyOperations pending, int startIndex)
+ {
+ IReadOnlyList verifications = pending.SignatureVerifications;
+ for (int i = startIndex; i < verifications.Count; i++)
+ {
+ ColumnMasterKeySignatureVerification verification = verifications[i];
+ SqlSecurityUtility.VerifyColumnMasterKeySignature(
+ verification.KeyStoreName,
+ verification.KeyPath,
+ verification.IsEnclaveEnabled,
+ verification.Signature,
+ _activeConnection,
+ this);
+ }
+
+ return verifications.Count;
}
+ ///
+ /// Asynchronously reads the output of sp_describe_parameter_encryption.
+ ///
+ ///
+ /// Async counterpart of . Result set parsing is
+ /// shared with the synchronous path; enclave session creation, column master key signature
+ /// verification, and column encryption key decryption use their asynchronous provider APIs.
+ ///
+ /// Resultset from calling to sp_describe_parameter_encryption
+ /// Readonly dictionary with the map of parameter encryption rpc requests with the corresponding original rpc requests.
+ /// Indicates if this is a retry from a failed call.
+ /// Token used to request cancellation of the operation
private async Task ReadDescribeEncryptionParameterResultsAsync(
SqlDataReader ds,
ReadOnlyDictionary<_SqlRPC, _SqlRPC> describeParameterEncryptionRpcOriginalRpcMap,
bool isRetry,
CancellationToken cancellationToken)
{
- foreach (byte[] attestationInfo in ReadDescribeEncryptionParameterResultsCore(ds, describeParameterEncryptionRpcOriginalRpcMap))
+ PendingColumnEncryptionKeyOperations pending = new PendingColumnEncryptionKeyOperations();
+ int verifiedCount = 0;
+ foreach (byte[] attestationInfo in ReadDescribeEncryptionParameterResultsCore(ds, describeParameterEncryptionRpcOriginalRpcMap, pending))
{
+ // Reject untrusted keys before attestation creates and caches an enclave session.
+ verifiedCount = await VerifyPendingColumnMasterKeySignaturesAsync(pending, verifiedCount, cancellationToken)
+ .ConfigureAwait(false);
await CreateEnclaveSessionAsync(attestationInfo, isRetry, cancellationToken).ConfigureAwait(false);
}
+
+ await VerifyPendingColumnMasterKeySignaturesAsync(pending, verifiedCount, cancellationToken)
+ .ConfigureAwait(false);
+
+ // Metadata entries frequently share a key. Resolve them sequentially so the first result
+ // populates the cache without creating additional waiters for the same key.
+ IReadOnlyList keyDecryptions = pending.KeyDecryptions;
+ for (int i = 0; i < keyDecryptions.Count; i++)
+ {
+ await SqlSecurityUtility.DecryptSymmetricKeyAsync(keyDecryptions[i], _activeConnection, this, cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ CacheQueryMetadataIfNeeded();
+ }
+
+ ///
+ /// Asynchronously verifies the column master key signatures recorded after the first
+ /// entries.
+ ///
+ /// The number of signatures verified so far.
+ private async Task VerifyPendingColumnMasterKeySignaturesAsync(
+ PendingColumnEncryptionKeyOperations pending,
+ int startIndex,
+ CancellationToken cancellationToken)
+ {
+ IReadOnlyList verifications = pending.SignatureVerifications;
+ for (int i = startIndex; i < verifications.Count; i++)
+ {
+ ColumnMasterKeySignatureVerification verification = verifications[i];
+ await SqlSecurityUtility.VerifyColumnMasterKeySignatureAsync(
+ verification.KeyStoreName,
+ verification.KeyPath,
+ verification.IsEnclaveEnabled,
+ verification.Signature,
+ _activeConnection,
+ this,
+ cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ return verifications.Count;
}
private async Task CreateEnclaveSessionAsync(byte[] attestationInfo, bool isRetry, CancellationToken cancellationToken)
@@ -827,10 +922,48 @@ await EnclaveDelegate.Instance.CreateEnclaveSessionAsync(
enclaveAttestationParameters = null;
}
- // Yield at attestation boundaries so both execution modes share metadata parsing and cache updates.
+ ///
+ /// Adds the encryption metadata for the current query to the query metadata cache when applicable.
+ ///
+ private void CacheQueryMetadataIfNeeded()
+ {
+ // If we are not in Batch RPC mode, update the query cache with the encryption MD.
+ if (!_batchRPCMode && ShouldCacheEncryptionMetadata && _parameters?.Count > 0)
+ {
+ SqlQueryMetadataCache.GetInstance().AddQueryMetadata(this, ignoreQueriesWithReturnValueParams: true);
+ }
+ }
+
+ ///
+ /// Parses the result sets returned by sp_describe_parameter_encryption.
+ ///
+ ///
+ ///
+ /// Column master key signature verification and column encryption key decryption are not performed
+ /// here; they are recorded in so that the caller can execute them either
+ /// synchronously or asynchronously. Deferring them also means no key store network call is made while
+ /// the describe-parameter-encryption reader is still positioned mid-stream.
+ ///
+ ///
+ /// Deferring these operations changes which exception surfaces when a query hits more than one
+ /// problem. Previously verification and decryption were interleaved with parsing, so a bad signature
+ /// on the first key was raised before the parameter metadata result set was parsed at all. Now parsing
+ /// completes first, except that recorded signatures are verified before each enclave session is created.
+ /// A malformed result set is therefore usually reported in preference to a key store failure.
+ ///
+ ///
+ /// The caller verifies signatures before creating enclave sessions, so an untrusted key is rejected
+ /// before attestation, as before. Key decryption now runs after enclave session creation, so a
+ /// decryption failure can leave a cached enclave session; the set of exceptions is unchanged.
+ ///
+ ///
+ /// Resultset from calling to sp_describe_parameter_encryption
+ /// Readonly dictionary with the map of parameter encryption rpc requests with the corresponding original rpc requests.
+ /// Collects the key store operations that the caller must complete
private IEnumerable ReadDescribeEncryptionParameterResultsCore(
- SqlDataReader ds,
- ReadOnlyDictionary<_SqlRPC, _SqlRPC> describeParameterEncryptionRpcOriginalRpcMap)
+ SqlDataReader ds, // @TODO: Rename something more obvious
+ ReadOnlyDictionary<_SqlRPC, _SqlRPC> describeParameterEncryptionRpcOriginalRpcMap,
+ PendingColumnEncryptionKeyOperations pending)
{
// @TODO: This should be SqlTceCipherInfoTable
Dictionary columnEncryptionKeyTable = new Dictionary();
@@ -862,7 +995,7 @@ private IEnumerable ReadDescribeEncryptionParameterResultsCore(
}
// 1) Read the first result set that contains the column encryption key list
- bool enclaveMetadataExists = ReadDescribeEncryptionParameterResultsKeys(ds, columnEncryptionKeyTable);
+ bool enclaveMetadataExists = ReadDescribeEncryptionParameterResultsKeys(ds, columnEncryptionKeyTable, pending);
if (!enclaveMetadataExists && !ds.NextResult())
{
throw SQL.UnexpectedDescribeParamFormatParameterMetadata();
@@ -896,7 +1029,7 @@ private IEnumerable ReadDescribeEncryptionParameterResultsCore(
int receivedMetadataCount = 0;
if (!enclaveMetadataExists || ds.NextResult())
{
- receivedMetadataCount = ReadDescribeEncryptionParameterResultsMetadata(ds, rpc, columnEncryptionKeyTable);
+ receivedMetadataCount = ReadDescribeEncryptionParameterResultsMetadata(ds, rpc, columnEncryptionKeyTable, pending);
}
// When the RPC object gets reused, the parameter array has more parameters that the valid params for the command.
@@ -947,12 +1080,64 @@ private IEnumerable ReadDescribeEncryptionParameterResultsCore(
}
}
}
+ }
- // If we are not in Batch RPC mode, update the query cache with the encryption MD.
- if (!_batchRPCMode && ShouldCacheEncryptionMetadata && _parameters?.Count > 0)
+ ///
+ /// Key store operations discovered while parsing sp_describe_parameter_encryption results, deferred so
+ /// that they can be executed either synchronously or asynchronously.
+ ///
+ private sealed class PendingColumnEncryptionKeyOperations
+ {
+ private List _signatureVerifications;
+ private List _keyDecryptions;
+
+ /// Column master key signatures that must be verified.
+ internal IReadOnlyList SignatureVerifications =>
+ (IReadOnlyList)_signatureVerifications ??
+ Array.Empty();
+
+ /// Column encryption keys that must be decrypted.
+ internal IReadOnlyList KeyDecryptions =>
+ (IReadOnlyList)_keyDecryptions ?? Array.Empty();
+
+ ///
+ /// Records a column master key signature that must be verified before the query runs.
+ ///
+ internal void AddSignatureVerification(string keyStoreName, string keyPath, bool isEnclaveEnabled, byte[] signature) =>
+ (_signatureVerifications ??= new List())
+ .Add(new ColumnMasterKeySignatureVerification(keyStoreName, keyPath, isEnclaveEnabled, signature));
+
+ ///
+ /// Records a column encryption key that must be decrypted before the query runs.
+ ///
+ internal void AddKeyDecryption(SqlCipherMetadata cipherMetadata) =>
+ (_keyDecryptions ??= new List()).Add(cipherMetadata);
+ }
+
+ ///
+ /// Describes a pending column master key signature verification.
+ ///
+ private readonly struct ColumnMasterKeySignatureVerification
+ {
+ internal ColumnMasterKeySignatureVerification(string keyStoreName, string keyPath, bool isEnclaveEnabled, byte[] signature)
{
- SqlQueryMetadataCache.GetInstance().AddQueryMetadata(this, ignoreQueriesWithReturnValueParams: true);
+ KeyStoreName = keyStoreName;
+ KeyPath = keyPath;
+ IsEnclaveEnabled = isEnclaveEnabled;
+ Signature = signature;
}
+
+ internal string KeyStoreName { get; }
+
+ internal string KeyPath { get; }
+
+ ///
+ /// Whether the server reported that this key is required by the enclave. Carried explicitly
+ /// rather than assumed, because it selects which signature the key store validates.
+ ///
+ internal bool IsEnclaveEnabled { get; }
+
+ internal byte[] Signature { get; }
}
private IEnumerable ReadDescribeEncryptionParameterResultsAttestation(SqlDataReader ds)
@@ -993,7 +1178,8 @@ private IEnumerable ReadDescribeEncryptionParameterResultsAttestation(Sq
private bool ReadDescribeEncryptionParameterResultsKeys(
SqlDataReader ds,
- Dictionary columnEncryptionKeyTable)
+ Dictionary columnEncryptionKeyTable,
+ PendingColumnEncryptionKeyOperations pending)
{
bool enclaveMetadataExists = true;
while (ds.Read())
@@ -1093,13 +1279,9 @@ private bool ReadDescribeEncryptionParameterResultsKeys(
length: keySignatureLength);
}
- SqlSecurityUtility.VerifyColumnMasterKeySignature(
- providerName,
- keyPath,
- isEnclaveEnabled: isRequestedByEnclave,
- keySignature,
- _activeConnection,
- this);
+ // Defer signature verification: it may reach a key store over the network and must not
+ // run while this reader is still positioned mid-result-set.
+ pending.AddSignatureVerification(providerName, keyPath, isRequestedByEnclave, keySignature);
// Lookup the key, failing which throw an exception
// @TODO: Seriously, we *just* did this, why are we looking it up again??
@@ -1134,7 +1316,8 @@ private bool ReadDescribeEncryptionParameterResultsKeys(
private int ReadDescribeEncryptionParameterResultsMetadata(
SqlDataReader ds,
_SqlRPC rpc,
- Dictionary columnEncryptionKeyTable)
+ Dictionary columnEncryptionKeyTable,
+ PendingColumnEncryptionKeyOperations pending)
{
Debug.Assert(rpc is not null, "Describe Parameter Encryption requested for non-TCE spec proc");
@@ -1189,8 +1372,10 @@ private int ReadDescribeEncryptionParameterResultsMetadata(
encryptionType: columnEncryptionType,
normalizationRuleVersion: columnNormalizationRuleVersion);
- // Decrypt the symmetric key. This will also validate and throw if needed.
- SqlSecurityUtility.DecryptSymmetricKey(sqlParameter.CipherMetadata, _activeConnection, this);
+ // Defer decryption of the symmetric key: it may reach a key store over the network
+ // and must not run while this reader is still positioned mid-result-set. Decryption
+ // also validates the metadata and will throw if it is invalid.
+ pending.AddKeyDecryption(sqlParameter.CipherMetadata);
// This is effective only for _batchRPCMode even though we set it for
// non-_batchRPCMode also, since for non-_batchRPCMode, param options
diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.NonQuery.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.NonQuery.cs
index 7369df8030..7cb9fd1a5f 100644
--- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.NonQuery.cs
+++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.NonQuery.cs
@@ -336,6 +336,8 @@ private void BeginExecuteNonQueryInternalReadStage(TaskCompletionSource