Skip to content

Commit c16bf36

Browse files
Isolate enclave session cache entries by attestation protocol (#4829)
* Isolate enclave session cache entries by attestation protocol Include the connection's attestation protocol in the enclave session cache key so a session established under one attestation policy cannot be reused by a connection configured for a different policy. The key is now a tuple, which also keeps server, database and attestation URL as separate fields. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Add end-to-end test for enclave session isolation across attestation protocols Verifies against a VBS enclave server that sessions created with Attestation Protocol=None and HGS for the same server, database and attestation URL are not shared, for sync and async paths and both connection orders. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Derive None connection string from HGS string in enclave isolation test The None connection now differs from the HGS connection only by attestation protocol, so the test isolates the cache-key dimension under test. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> (cherry picked from commit f6ae2ac)
1 parent 2d4321a commit c16bf36

7 files changed

Lines changed: 360 additions & 8 deletions

File tree

‎doc/snippets/Microsoft.Data.SqlClient/SqlConnectionStringBuilder.xml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,9 @@ The following example supplies a simple SQL Server connection string in the <xre
261261
</value>
262262
<remarks>
263263
When no value is specified, secure enclaves are disabled on the connection.
264+
Enclave sessions are cached separately for each attestation protocol. A session
265+
established with <see cref="F:Microsoft.Data.SqlClient.SqlConnectionAttestationProtocol.None" />
266+
cannot satisfy a connection configured to require HGS or AAS attestation.
264267
</remarks>
265268
</AttestationProtocol>
266269
<Authentication>

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/EnclaveSessionCache.cs‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ internal class EnclaveSessionCache
2424
// Retrieves a SqlEnclaveSession from the cache
2525
internal SqlEnclaveSession GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, out long counter)
2626
{
27-
string cacheKey = GenerateCacheKey(enclaveSessionParameters);
27+
Tuple<SqlConnectionAttestationProtocol, string, string, string> cacheKey =
28+
GenerateCacheKey(enclaveSessionParameters);
2829
SqlEnclaveSession enclaveSession = enclaveMemoryCache.Get<SqlEnclaveSession>(cacheKey);
2930
counter = Interlocked.Increment(ref _counter);
3031
return enclaveSession;
@@ -33,7 +34,8 @@ internal SqlEnclaveSession GetEnclaveSession(EnclaveSessionParameters enclaveSes
3334
// Invalidates a SqlEnclaveSession entry in the cache
3435
internal void InvalidateSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate)
3536
{
36-
string cacheKey = GenerateCacheKey(enclaveSessionParameters);
37+
Tuple<SqlConnectionAttestationProtocol, string, string, string> cacheKey =
38+
GenerateCacheKey(enclaveSessionParameters);
3739

3840
lock (enclaveCacheLock)
3941
{
@@ -57,7 +59,8 @@ internal void InvalidateSession(EnclaveSessionParameters enclaveSessionParameter
5759
// Creates a new SqlEnclaveSession and adds it to the cache
5860
internal SqlEnclaveSession CreateSession(EnclaveSessionParameters enclaveSessionParameters, byte[] sharedSecret, long sessionId, out long counter)
5961
{
60-
string cacheKey = GenerateCacheKey(enclaveSessionParameters);
62+
Tuple<SqlConnectionAttestationProtocol, string, string, string> cacheKey =
63+
GenerateCacheKey(enclaveSessionParameters);
6164
SqlEnclaveSession enclaveSession = null;
6265
lock (enclaveCacheLock)
6366
{
@@ -70,10 +73,16 @@ internal SqlEnclaveSession CreateSession(EnclaveSessionParameters enclaveSession
7073
return enclaveSession;
7174
}
7275

73-
// Generates the cache key for the enclave session cache
74-
private string GenerateCacheKey(EnclaveSessionParameters enclaveSessionParameters)
76+
// Keep the attestation policy and field boundaries in the identity while preserving
77+
// the existing case-insensitive, null/empty-equivalent string matching.
78+
private static Tuple<SqlConnectionAttestationProtocol, string, string, string> GenerateCacheKey(
79+
EnclaveSessionParameters enclaveSessionParameters)
7580
{
76-
return (enclaveSessionParameters.ServerName + '+' + enclaveSessionParameters.Database + enclaveSessionParameters.AttestationUrl).ToLowerInvariant();
81+
return Tuple.Create(
82+
enclaveSessionParameters.AttestationProtocol,
83+
(enclaveSessionParameters.ServerName ?? string.Empty).ToLowerInvariant(),
84+
(enclaveSessionParameters.Database ?? string.Empty).ToLowerInvariant(),
85+
(enclaveSessionParameters.AttestationUrl ?? string.Empty).ToLowerInvariant());
7786
}
7887
}
7988
}

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.Encryption.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,8 @@ private EnclaveSessionParameters GetEnclaveSessionParameters() =>
241241
new EnclaveSessionParameters(
242242
_activeConnection.DataSource,
243243
_activeConnection.EnclaveAttestationUrl,
244-
_activeConnection.Database);
244+
_activeConnection.Database,
245+
_activeConnection.AttestationProtocol);
245246

246247
// @TODO: Isn't this doing things asynchronously? We should just have a purely asynchronous and a purely synchronous pathway instead of this mix of check this check that and flags.
247248
private SqlDataReader GetParameterEncryptionDataReader(

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,15 @@ internal class EnclaveSessionParameters
6262
internal string ServerName { get; set; } // The name of the SQL Server instance containing the enclave.
6363
internal string AttestationUrl { get; set; } // The endpoint of an attestation service for attesting the enclave.
6464
internal string Database { get; set; } // The database that SqlClient contacts to request an enclave session.
65+
internal SqlConnectionAttestationProtocol AttestationProtocol { get; }
6566

66-
internal EnclaveSessionParameters(string serverName, string attestationUrl, string database)
67+
internal EnclaveSessionParameters(string serverName, string attestationUrl, string database,
68+
SqlConnectionAttestationProtocol attestationProtocol)
6769
{
6870
ServerName = serverName;
6971
AttestationUrl = attestationUrl;
7072
Database = database;
73+
AttestationProtocol = attestationProtocol;
7174
}
7275
}
7376
}

‎src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/ApiShould.cs‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2498,6 +2498,140 @@ public void TestRetryWhenAEParameterMetadataCacheIsStale(string connectionString
24982498
cmd.ExecuteNonQuery();
24992499
}
25002500

2501+
/// <summary>
2502+
/// Enclave queries reuse a same-policy session across connections and establish a new
2503+
/// session after invalidation, for both synchronous and asynchronous execution.
2504+
/// Run with each configured HGS, AAS, and None enclave connection.
2505+
/// </summary>
2506+
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.IsTargetReadyForAeWithKeyStore), nameof(DataTestUtility.EnclaveEnabled))]
2507+
[ClassData(typeof(AEConnectionStringProviderWithBooleanVariable))]
2508+
public async Task TestEnclaveSessionReuseAcrossConnections(string connectionString, bool isAsync)
2509+
{
2510+
CleanUpTable(connectionString, _tableName);
2511+
const int customerId = 50;
2512+
InsertRows(_tableName, 1, GetValues(dataHint: customerId), connectionString);
2513+
2514+
object originalSession = null;
2515+
for (int attempt = 0; attempt < 3; attempt++)
2516+
{
2517+
using SqlConnection connection = new(connectionString);
2518+
if (isAsync)
2519+
{
2520+
await connection.OpenAsync();
2521+
}
2522+
else
2523+
{
2524+
connection.Open();
2525+
}
2526+
2527+
using SqlCommand command = new(
2528+
$"SELECT CustomerId FROM [{_tableName}] WHERE CustomerId > @CustomerId",
2529+
connection, null, SqlCommandColumnEncryptionSetting.Enabled);
2530+
command.Parameters.Add("@CustomerId", SqlDbType.Int).Value = 0;
2531+
using SqlDataReader reader = isAsync
2532+
? await command.ExecuteReaderAsync()
2533+
: command.ExecuteReader();
2534+
object session = CommandHelper.GetEnclaveSession(command);
2535+
2536+
Assert.True(isAsync ? await reader.ReadAsync() : reader.Read());
2537+
Assert.Equal(customerId, reader.GetInt32(0));
2538+
Assert.False(isAsync ? await reader.ReadAsync() : reader.Read());
2539+
2540+
if (attempt == 0)
2541+
{
2542+
originalSession = session;
2543+
}
2544+
else if (attempt == 1)
2545+
{
2546+
Assert.Same(originalSession, session);
2547+
CommandHelper.InvalidateEnclaveSession(command);
2548+
}
2549+
else
2550+
{
2551+
Assert.NotSame(originalSession, session);
2552+
}
2553+
}
2554+
}
2555+
2556+
/// <summary>
2557+
/// An enclave session established under one attestation protocol must not be reused by a
2558+
/// connection that requests a different attestation protocol, even when the server, database
2559+
/// and attestation URL are identical. The HGS connection must perform its own attestation.
2560+
/// </summary>
2561+
[ConditionalTheory(typeof(ApiShould), nameof(IsHgsVbsEnclaveSetup))]
2562+
[InlineData(false, false)]
2563+
[InlineData(false, true)]
2564+
[InlineData(true, false)]
2565+
[InlineData(true, true)]
2566+
public async Task TestEnclaveSessionIsNotSharedAcrossAttestationProtocols(bool noneFirst, bool isAsync)
2567+
{
2568+
string hgsConnectionString = DataTestUtility.TCPConnectionStringHGSVBS;
2569+
2570+
// Derive the None connection from the HGS one so the attestation protocol is the only
2571+
// difference; server, database and attestation URL stay identical.
2572+
SqlConnectionStringBuilder noneBuilder = new(hgsConnectionString)
2573+
{
2574+
AttestationProtocol = SqlConnectionAttestationProtocol.None
2575+
};
2576+
string noneConnectionString = noneBuilder.ConnectionString;
2577+
2578+
const int customerId = 51;
2579+
CleanUpTable(hgsConnectionString, _tableName);
2580+
InsertRows(_tableName, 1, GetValues(dataHint: customerId), hgsConnectionString);
2581+
2582+
// Start from an empty cache for both protocols.
2583+
await ExecuteEnclaveQueryAsync(noneConnectionString, customerId, isAsync, invalidateSession: true);
2584+
await ExecuteEnclaveQueryAsync(hgsConnectionString, customerId, isAsync, invalidateSession: true);
2585+
await ExecuteEnclaveQueryAsync(noneConnectionString, customerId, isAsync, invalidateSession: true);
2586+
2587+
string firstConnectionString = noneFirst ? noneConnectionString : hgsConnectionString;
2588+
string secondConnectionString = noneFirst ? hgsConnectionString : noneConnectionString;
2589+
2590+
object firstSession = await ExecuteEnclaveQueryAsync(firstConnectionString, customerId, isAsync);
2591+
object secondSession = await ExecuteEnclaveQueryAsync(secondConnectionString, customerId, isAsync);
2592+
2593+
Assert.NotSame(firstSession, secondSession);
2594+
2595+
// Each protocol continues to reuse its own session.
2596+
Assert.Same(firstSession, await ExecuteEnclaveQueryAsync(firstConnectionString, customerId, isAsync));
2597+
Assert.Same(secondSession, await ExecuteEnclaveQueryAsync(secondConnectionString, customerId, isAsync));
2598+
}
2599+
2600+
public static bool IsHgsVbsEnclaveSetup() =>
2601+
DataTestUtility.IsTargetReadyForAeWithKeyStore() &&
2602+
DataTestUtility.EnclaveEnabled &&
2603+
!string.IsNullOrEmpty(DataTestUtility.TCPConnectionStringHGSVBS);
2604+
2605+
private async Task<object> ExecuteEnclaveQueryAsync(string connectionString, int expectedCustomerId, bool isAsync, bool invalidateSession = false)
2606+
{
2607+
using SqlConnection connection = new(connectionString);
2608+
if (isAsync)
2609+
{
2610+
await connection.OpenAsync();
2611+
}
2612+
else
2613+
{
2614+
connection.Open();
2615+
}
2616+
2617+
using SqlCommand command = new(
2618+
$"SELECT CustomerId FROM [{_tableName}] WHERE CustomerId > @CustomerId",
2619+
connection, null, SqlCommandColumnEncryptionSetting.Enabled);
2620+
command.Parameters.Add("@CustomerId", SqlDbType.Int).Value = 0;
2621+
using SqlDataReader reader = isAsync ? await command.ExecuteReaderAsync() : command.ExecuteReader();
2622+
object session = CommandHelper.GetEnclaveSession(command);
2623+
2624+
Assert.True(isAsync ? await reader.ReadAsync() : reader.Read());
2625+
Assert.Equal(expectedCustomerId, reader.GetInt32(0));
2626+
Assert.False(isAsync ? await reader.ReadAsync() : reader.Read());
2627+
2628+
if (invalidateSession)
2629+
{
2630+
CommandHelper.InvalidateEnclaveSession(command);
2631+
}
2632+
return session;
2633+
}
2634+
25012635
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE), nameof(DataTestUtility.EnclaveEnabled))]
25022636
[ClassData(typeof(AEConnectionStringProvider))]
25032637
public void TestRetryWhenAEEnclaveCacheIsStale(string connectionString)

‎src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/CommandHelper.cs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ internal static class CommandHelper
1313
private static MethodInfo s_completePendingReadWithSuccess = s_sqlCommand.GetMethod("CompletePendingReadWithSuccess", BindingFlags.NonPublic | BindingFlags.Instance);
1414
private static MethodInfo s_completePendingReadWithFailure = s_sqlCommand.GetMethod("CompletePendingReadWithFailure", BindingFlags.NonPublic | BindingFlags.Instance);
1515
private static MethodInfo s_invalidateEnclaveSession = s_sqlCommand.GetMethod("InvalidateEnclaveSession", BindingFlags.NonPublic | BindingFlags.Instance);
16+
private static readonly FieldInfo s_enclavePackage = s_sqlCommand.GetField("enclavePackage", BindingFlags.NonPublic | BindingFlags.Instance);
1617
#if DEBUG
1718
private static FieldInfo s_forceRetryableEnclaveQueryExecutionExceptionDuringGenerateEnclavePackage =
1819
s_sqlCommand.GetField(@"_forceRetryableEnclaveQueryExecutionExceptionDuringGenerateEnclavePackage", BindingFlags.NonPublic | BindingFlags.Static);
@@ -41,6 +42,23 @@ internal static void InvalidateEnclaveSession(SqlCommand command)
4142
s_invalidateEnclaveSession.Invoke(command, null);
4243
}
4344

45+
/// <summary>
46+
/// Gets the session used for a command's enclave package without exposing its key material.
47+
/// Call while the command still retains its encryption state.
48+
/// </summary>
49+
/// <param name="command">An executed command requiring enclave computations.</param>
50+
/// <returns>The session object, for reference-identity assertions.</returns>
51+
internal static object GetEnclaveSession(SqlCommand command)
52+
{
53+
object package = s_enclavePackage.GetValue(command)
54+
?? throw new InvalidOperationException("The command did not generate an enclave package.");
55+
PropertyInfo sessionProperty = package.GetType().GetProperty(
56+
"EnclaveSession", BindingFlags.NonPublic | BindingFlags.Instance)
57+
?? throw new MissingMemberException(package.GetType().FullName, "EnclaveSession");
58+
return sessionProperty.GetValue(package)
59+
?? throw new InvalidOperationException("The enclave package has no session.");
60+
}
61+
4462
#if DEBUG
4563
internal static void ForceThrowDuringGenerateEnclavePackage(SqlCommand command)
4664
{

0 commit comments

Comments
 (0)