Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d275fdb

Browse files
rzikmmatouskozak
authored andcommittedApr 30, 2024
Avoid frequent calls to CertificateValidationPal.IsLocalCertificateUsed (dotnet#100513)
* Avoid frequent calls to CertificateValidationPal.IsLocalCertificateUsed * Code review feedback
1 parent d811c59 commit d275fdb

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed
 

‎src/libraries/System.Net.Security/src/System/Net/Security/SslStream.IO.cs

+3
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,9 @@ private async Task ForceAuthenticationAsync<TIOAdapter>(bool receiveFirst, byte[
360360
}
361361

362362
token.ReleasePayload();
363+
364+
// reset the cached flag which has potentially outdated value.
365+
_localClientCertificateUsed = -1;
363366
}
364367

365368
if (NetEventSource.Log.IsEnabled())

‎src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs

+21-1
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ internal static bool DisableTlsResume
5757
private X509Certificate2? _remoteCertificate;
5858
private bool _remoteCertificateExposed;
5959

60+
// -1 for uninitialized, 0 for false, 1 for true, should be accessed via IsLocalClientCertificateUsed property
61+
private int _localClientCertificateUsed = -1;
62+
6063
// These are the MAX encrypt buffer output sizes, not the actual sizes.
6164
private int _headerSize = 5; //ATTN must be set to at least 5 by default
6265
private int _trailerSize = 16;
@@ -82,11 +85,28 @@ internal X509Certificate? LocalServerCertificate
8285
}
8386
}
8487

88+
// IsLocalCertificateUsed is expensive, but it does not change during the lifetime of the SslStream except for renegotiation, so we
89+
// can cache the value.
90+
private bool IsLocalClientCertificateUsed
91+
{
92+
get
93+
{
94+
if (_localClientCertificateUsed == -1)
95+
{
96+
_localClientCertificateUsed = CertificateValidationPal.IsLocalCertificateUsed(_credentialsHandle, _securityContext!)
97+
? 1
98+
: 0;
99+
}
100+
101+
return _localClientCertificateUsed == 1;
102+
}
103+
}
104+
85105
internal X509Certificate? LocalClientCertificate
86106
{
87107
get
88108
{
89-
if (_selectedClientCertificate != null && CertificateValidationPal.IsLocalCertificateUsed(_credentialsHandle, _securityContext!))
109+
if (_selectedClientCertificate != null && IsLocalClientCertificateUsed)
90110
{
91111
return _selectedClientCertificate;
92112
}

0 commit comments

Comments
 (0)
Please sign in to comment.