-
Notifications
You must be signed in to change notification settings - Fork 5.2k
[WinHTTP] Certificate caching on WinHttpHandler to eliminate extra call to Custom Certificate Validation #111791
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
liveans
merged 23 commits into
dotnet:main
from
liveans:winhttp_servervalidationcallback_cache_certificate_experiment
Apr 8, 2025
Merged
Changes from 7 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
aed71f0
Certificate caching on WinHttpHandler to eliminate extra call to Cust…
liveans f08a569
Review feedback
liveans 80ee04c
Merge branch 'main' into winhttp_servervalidationcallback_cache_certi…
liveans 63de970
Review feedback
liveans 00640e2
Framework compat + Review Feedback
liveans 4ed25ff
Implement Timer to clear cache
liveans b15191d
Review feedback
liveans 736944d
Review Feedback
liveans a8e05d0
Merge branch 'main' into winhttp_servervalidationcallback_cache_certi…
liveans 548e6fd
Review feedback
liveans c365911
Fix RemoteExecutor issue and change delay to ms
liveans 9e00762
Review feedback
liveans 7f8540b
Apply suggestions from code review
liveans e0a9524
Merge branch 'main' into winhttp_servervalidationcallback_cache_certi…
liveans 7d2bbbf
Merge branch 'main' into winhttp_servervalidationcallback_cache_certi…
liveans ae27025
Add ExecutionContext SuppressFlow
liveans 61e7e88
Merge branch 'main' into winhttp_servervalidationcallback_cache_certi…
liveans adcce2b
Fix alignment issues
liveans 2a6529f
Add offset docs for IPAddress parsing
liveans 930d589
Merge branch 'winhttp_servervalidationcallback_cache_certificate_expe…
liveans 3497e8f
Merge branch 'main' into winhttp_servervalidationcallback_cache_certi…
liveans 12dfec6
Use RawDataMemory for lookup in Modern .NET
liveans 23c2f94
Merge branch 'winhttp_servervalidationcallback_cache_certificate_expe…
liveans File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
15 changes: 15 additions & 0 deletions
15
src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/CachedCertificateValue.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Collections.Generic; | ||
using System.Text; | ||
|
||
namespace System.Net.Http | ||
{ | ||
internal sealed class CachedCertificateValue(byte[] rawCertificateData, long lastUsedTime) | ||
{ | ||
public byte[] RawCertificateData { get; } = rawCertificateData; | ||
public long LastUsedTime { get; set; } = lastUsedTime; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,12 +2,16 @@ | |
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Buffers.Binary; | ||
using System.Diagnostics; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Net.Security; | ||
using System.Net.Sockets; | ||
using System.Runtime.CompilerServices; | ||
using System.Runtime.InteropServices; | ||
using System.Security.Cryptography.X509Certificates; | ||
|
||
using System.Threading; | ||
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; | ||
|
||
namespace System.Net.Http | ||
|
@@ -20,6 +24,8 @@ internal static class WinHttpRequestCallback | |
public static Interop.WinHttp.WINHTTP_STATUS_CALLBACK StaticCallbackDelegate = | ||
new Interop.WinHttp.WINHTTP_STATUS_CALLBACK(WinHttpCallback); | ||
|
||
public static bool CertificateCachingAppContextSwitchEnabled { get; } = AppContext.TryGetSwitch("System.Net.Http.UseWinHttpCertificateCaching", out bool enabled) && enabled; | ||
|
||
public static void WinHttpCallback( | ||
IntPtr handle, | ||
IntPtr context, | ||
|
@@ -56,6 +62,14 @@ private static void RequestCallback( | |
{ | ||
switch (internetStatus) | ||
{ | ||
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER: | ||
if (CertificateCachingAppContextSwitchEnabled) | ||
{ | ||
liveans marked this conversation as resolved.
Show resolved
Hide resolved
|
||
IPAddress connectedToIPAddress = IPAddress.Parse(Marshal.PtrToStringUni(statusInformation)!); | ||
liveans marked this conversation as resolved.
Show resolved
Hide resolved
|
||
OnRequestConnectedToServer(state, connectedToIPAddress); | ||
} | ||
return; | ||
|
||
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: | ||
OnRequestHandleClosing(state); | ||
return; | ||
|
@@ -121,6 +135,21 @@ private static void RequestCallback( | |
} | ||
} | ||
|
||
private static void OnRequestConnectedToServer(WinHttpRequestState state, IPAddress connectedIPAddress) | ||
{ | ||
Debug.Assert(state != null); | ||
Debug.Assert(state.Handler != null); | ||
|
||
if (state.Handler.TryRemoveCertificateFromCache(connectedIPAddress)) | ||
liveans marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
{ | ||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"Removed cached certificate for {connectedIPAddress}"); | ||
} | ||
else | ||
{ | ||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"No cached certificate for {connectedIPAddress} to remove"); | ||
liveans marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
private static void OnRequestHandleClosing(WinHttpRequestState state) | ||
{ | ||
Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null"); | ||
|
@@ -231,6 +260,7 @@ private static void OnRequestRedirect(WinHttpRequestState state, Uri redirectUri | |
private static void OnRequestSendingRequest(WinHttpRequestState state) | ||
{ | ||
Debug.Assert(state != null, "OnRequestSendingRequest: state is null"); | ||
Debug.Assert(state.Handler != null, "OnRequestSendingRequest: state.Handler is null"); | ||
Debug.Assert(state.RequestMessage != null, "OnRequestSendingRequest: state.RequestMessage is null"); | ||
Debug.Assert(state.RequestMessage.RequestUri != null, "OnRequestSendingRequest: state.RequestMessage.RequestUri is null"); | ||
|
||
|
@@ -279,6 +309,53 @@ private static void OnRequestSendingRequest(WinHttpRequestState state) | |
var serverCertificate = new X509Certificate2(certHandle); | ||
Interop.Crypt32.CertFreeCertificateContext(certHandle); | ||
|
||
IPAddress? ipAddress = null; | ||
if (CertificateCachingAppContextSwitchEnabled) | ||
{ | ||
unsafe | ||
{ | ||
Interop.WinHttp.WINHTTP_CONNECTION_INFO connectionInfo; | ||
Interop.WinHttp.WINHTTP_CONNECTION_INFO* pConnectionInfo = &connectionInfo; | ||
uint infoSize = (uint)sizeof(Interop.WinHttp.WINHTTP_CONNECTION_INFO); | ||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(state, $"sizeof(WINHTTP_CONNECTION_INFO)={infoSize}"); | ||
liveans marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
if (Interop.WinHttp.WinHttpQueryOption( | ||
state.RequestHandle, | ||
// This option is available on Windows XP SP2 and later; Windows 2003 with SP1 and later. | ||
Interop.WinHttp.WINHTTP_OPTION_CONNECTION_INFO, | ||
(IntPtr)pConnectionInfo, | ||
ref infoSize)) | ||
{ | ||
ReadOnlySpan<byte> remoteAddressSpan = new ReadOnlySpan<byte>(connectionInfo.RemoteAddress, 128); | ||
AddressFamily addressFamily = (AddressFamily)(remoteAddressSpan[0] + (remoteAddressSpan[1] << 8)); | ||
ipAddress = addressFamily switch | ||
{ | ||
AddressFamily.InterNetwork => new IPAddress(BinaryPrimitives.ReadUInt32LittleEndian(remoteAddressSpan.Slice(4))), | ||
AddressFamily.InterNetworkV6 => new IPAddress(remoteAddressSpan.Slice(8, 16).ToArray()), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit.
liveans marked this conversation as resolved.
Show resolved
Hide resolved
|
||
_ => null | ||
}; | ||
Debug.Assert(ipAddress != null, "AddressFamily is not supported"); | ||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(state, $"ipAddress: {ipAddress}"); | ||
|
||
} | ||
else | ||
{ | ||
int lastError = Marshal.GetLastWin32Error(); | ||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(state, $"Error getting WINHTTP_OPTION_CONNECTION_INFO, {lastError}"); | ||
} | ||
} | ||
|
||
if (ipAddress is not null && state.Handler.GetCertificateFromCache(ipAddress, out byte[]? rawCertData) && rawCertData.SequenceEqual(serverCertificate.RawData)) | ||
{ | ||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(state, $"Skipping certificate validation. ipAddress: {ipAddress}, Thumbprint: {serverCertificate.Thumbprint}"); | ||
serverCertificate.Dispose(); | ||
return; | ||
} | ||
else | ||
{ | ||
liveans marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(state, $"Certificate validation is required! IPAddress = {ipAddress}, Thumbprint: {serverCertificate.Thumbprint}"); | ||
} | ||
} | ||
|
||
X509Chain? chain = null; | ||
SslPolicyErrors sslPolicyErrors; | ||
bool result = false; | ||
|
@@ -298,6 +375,10 @@ private static void OnRequestSendingRequest(WinHttpRequestState state) | |
serverCertificate, | ||
chain, | ||
sslPolicyErrors); | ||
if (CertificateCachingAppContextSwitchEnabled && result && ipAddress is not null) | ||
{ | ||
_ = state.Handler.TryAddCertificateToCache(ipAddress, serverCertificate.RawData); | ||
} | ||
} | ||
catch (Exception ex) | ||
{ | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.