Skip to content

Commit 07d11eb

Browse files
DeagleGrossCopilotBrennanConroy
authored
[Experimental] DirectTls transport implementation (#67912)
* Add experimental DirectTls transport for Kestrel Adds Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls, an opt-in, per-endpoint transport that terminates TLS directly on the connection socket file descriptor via the runtime TlsContext/TlsSocketSession API, driven by an epoll event pump, bypassing SslStream. Primarily focused on Linux and requires OpenSSL on the host. Public API (all [Experimental ASPNETCORE_DIRECTTLS_001]): UseDirectTlsTransport(), DirectTlsEndpoint, DirectTlsEndpointOptions, DirectTlsTransportOptions. Features: per-SNI certificate selection, raw ClientHello bytes callback, ALPN/HTTP-2 (ITlsApplicationProtocolFeature set directly), mutual TLS client-certificate modes (DelayCertificate not supported), and the TLS handshake/connection features at parity with the SslStream path. Includes a sample app and tests. Test certificates are generated locally via scripts/generate-certs.sh and git-ignored, never committed. Wired into AspNetCore.slnx and Kestrel.slnf. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * DirectTls: apply API-review-approved cosmetic changes Applies the changes requested during the #67909 public API review: 1. Rename WebHostBuilderDirectTlsExtensions.UseDirectTlsTransport -> UseDirectTls. 2. Remove the (int port, DirectTlsEndpointOptions options) constructor on DirectTlsEndpoint (the (IPAddress, int, options) overload covers it). 3. Remove HttpProtocols from DirectTlsEndpointOptions; the transport now sources the HTTP protocols (ALPN) from ListenOptions.Protocols. The factory reads the matching endpoint via KestrelServerOptions.GetListenOptions() (new one-line InternalsVisibleTo from Kestrel.Core), keeping the approved options.Listen(endpoint) surface unchanged. 4. Change TlsClientHelloBytesCallback from Action<ConnectionContext, ReadOnlySequence<byte>> to a new DirectTlsClientHelloBytesCallback delegate taking ReadOnlySpan<byte> (the ClientHello bytes are already contiguous in memory). Updates PublicAPI.Unshipped.txt, the sample app, and tests. Builds clean; 19/19 DirectTls tests pass. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * DirectTls: drop custom ClientHello delegate; move protocols off factory DI Address API-review follow-ups on the cosmetic-changes commit: 1. Remove the public DirectTlsClientHelloBytesCallback delegate. The ClientHello-bytes callback is now typed System.Buffers.ReadOnlySpanAction< byte, ConnectionContext> (a BCL type), so no new public delegate is added. Action<ConnectionContext, ReadOnlySpan<byte>> is not expressible because ReadOnlySpan<byte> is a ref struct and cannot be an Action<> type argument. The callback argument order is now (bytes, connection). 2. Remove the IOptions<KestrelServerOptions> dependency from DirectTlsTransportFactory. A new internal IPostConfigureOptions< KestrelServerOptions> (DirectTlsEndpointProtocolsSetup) copies each DirectTlsEndpoint ListenOptions.Protocols onto a new internal DirectTlsEndpointOptions.HttpProtocols after all endpoints are configured. The factory reads that internal field at bind time. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * DirectTls: revert ClientHello callback to Action<ConnectionContext, ReadOnlySequence<byte>> A ReadOnlySpan<byte> is a poor fit for a stored callback: its lifetime is undetermined and it cannot be a type argument to Action<> (ref struct). Use ReadOnlySequence<byte> instead, which is a normal struct and works with a plain Action<> in the natural (connection, bytes) argument order. No custom public delegate is needed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * DirectTls: move DirectTlsEndpoint(+Options) into Kestrel.Core; socket transport refuses it Move DirectTlsEndpoint and DirectTlsEndpointOptions from the DirectTls transport assembly into Kestrel.Core (namespace unchanged, so the approved public API names are identical). This makes the endpoint a first-class Kestrel concept that the default socket transport can reference cheaply. SocketTransportFactory.CanBind now returns false for DirectTlsEndpoint. Because DirectTlsEndpoint derives from IPEndPoint, the socket transport would otherwise accept it and could bind it as a plaintext socket if it were tried before the DirectTls transport. Combined with DirectTlsTransportFactory.CanBind (which returns true ONLY for DirectTlsEndpoint), this guarantees - regardless of transport registration order - that a DirectTls endpoint is served only by the DirectTls transport, and no other endpoint is ever served by it. Transport.Sockets now references Kestrel.Core (acyclic: Core does not reference Sockets). Added a Sockets.BindTests case locking in the exclusion. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * Ship DirectTls transport as a standalone NuGet package Convert Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls from a shared-framework assembly to a standalone shipping NuGet package: remove IsAspNetCoreApp (so it is no longer part of Microsoft.AspNetCore.App) and set IsPackable=true. The transport was never actually enumerated in the generated shared-framework list (eng/SharedFramework.Local.props) or its baselines, and the sample/tests already consumed it via ProjectReference, so the IsAspNetCoreApp flag was effectively dead. Making it a package keeps this experimental transport opt-in and easy to remove later. The endpoint/options public types live in Kestrel.Core (shared framework); only the transport implementation and UseDirectTls extension method ship in this package. Its references to shared-framework assemblies (Kestrel.Core, etc.) become a FrameworkReference to Microsoft.AspNetCore.App in the produced nupkg. Verified: pack produces a nupkg with frameworkReference Microsoft.AspNetCore.App; sample builds clean; 19/19 DirectTls tests pass. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * Add package README and processor-based default WorkerCount for DirectTls Two small refinements to the DirectTls transport package: - Add a minimal package README (PackageReadmeFile) so the produced nupkg no longer warns about a missing readme. Content is intentionally a single sentence noting this is an experimental, Linux-only, fd-bound native OpenSSL TLS transport. - Give DirectTlsTransportOptions.WorkerCount a processor-based default instead of a hard-coded 4, mirroring the sockets transport IOQueue heuristic (capped at 16 for up to 32 processors, half the processor count beyond that). The heuristic is exposed only as an internal static DefaultWorkerCount, so no new public API is introduced. Verified: pack produces a nupkg containing README.md with <readme> in the nuspec; build clean; 19/19 DirectTls tests pass. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * Remove package README from DirectTls transport A package README is not required to ship the DirectTls NuGet package; drop the README.md and its PackageReadmeFile/None wiring. The processor-based default WorkerCount change from the previous commit is unaffected. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * Fix DirectTls epoll P/Invokes missing SetLastError=true The libc epoll P/Invokes in Interop/NativeTls.cs used [LibraryImport] without SetLastError=true, which defaults to false. As a result every Marshal.GetLastWin32Error() call in TlsEventPump read a stale/garbage errno rather than the real one from the failed syscall. The critical impact is in PumpLoop's epoll_wait EINTR handling: on a signal interrupt epoll_wait returns -1 with errno==EINTR (4), and the loop is supposed to `continue`. With a garbage errno the check almost never matched, so the pump logged an error and broke out of the loop, permanently terminating that worker thread and orphaning its connections. The other errno sites (exception messages and warning logs) also reported garbage values. Add SetLastError=true to epoll_create1, both epoll_ctl overloads, epoll_wait and close so GetLastWin32Error returns the real errno. This matches how the runtime's own Sockets epoll interop is declared. Verified: build clean; 19/19 DirectTls tests pass. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * log error on epoll closure fail * cleanup tlspumpeventpool ; add per-endpoint workercount * fix renego read/write collapses * cover connectionIoState with tests * comment on dispose/shutdown race condition problem * Fix DirectTls accept loop spin on listen socket teardown Stop accepting on all pumps (de-register the listen fd from each pump's epoll set and clear the cached _listenFd) before the listener closes the listen socket, in both DisposeAsync and UnbindAsync. This prevents a pump from calling Accept() on a closed fd - or misrouting a client fd that reuses the closed listen fd's number into the accept path - and spinning. AcceptConnections now guards on _running/_listenFd and breaks on any accept error, returning to epoll_wait (level-triggered re-arm) rather than looping, so a dead listen fd can never tight-spin. AcceptOne/ProcessAcceptedSocket are split out as test seams; TlsEventPump is unsealed for the scripted fake. Adds TlsEventPumpAcceptTests covering the accept-loop control flow and StopAccepting without a live listen socket, epoll, or the pump thread. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * Dispose DirectTls native TLS contexts on listener teardown The per-listener bootstrap TlsContext and the per-SNI TlsContext cache each acquire OpenSSL server credentials (a long-lived SSL_CTX with the loaded cert chain and private key) and were never disposed, leaking for the listener's lifetime. Wrap them in ServerTlsContexts and dispose it from DirectTlsConnectionListener.DisposeAsync, after the pump pool is stopped so no in-flight handshake can be using a context. DisposeAsync is now idempotent. UnbindAsync intentionally does not free the contexts (established connections keep serving). Not disposing established _connections sessions from TlsEventPump.Dispose is intentional: every entry is owned by a DirectTlsConnection that disposes it, so a pump-side dispose would double-Shutdown the same native SSL* from two threads. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * Dispose accepted client certificate on DirectTls connection teardown On the fd fast path the runtime's TlsSession transfers ownership of the accepted client leaf certificate to the caller: SetRemoteCertificateValidationResult(None) promotes the pending cert into TlsSession._remoteCertificate, which TlsSession.Dispose() deliberately never frees (unlike _externalPendingCert and the intermediate certificates). DirectTlsConnection surfaced that leaf as ITlsConnectionFeature.ClientCertificate but never disposed it, leaking one native key handle per accepted mTLS connection. Track the runtime-handed leaf in a private _ownedClientCertificate field (set alongside the settable feature property so we dispose exactly the cert the runtime gave us, never an app-reassigned object) and dispose it once in both teardown paths, mirroring how SslStream disposes RemoteCertificate with the stream. Disposal is idempotent, so this is safe even if a future runtime also frees the leaf. The two GetRemoteCertificate() calls in TlsEventPump return the same session-owned instance, so there was no double allocation to fix there. Extends the mTLS functional test to assert the app can read the client certificate thumbprint during the request, guarding against disposing too early. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * defend for linux OS * Trim unrelated AspNetCore.slnx reordering churn Adding the DirectTls projects caused slnx tooling to also re-sort the Components/Testing and ProjectTemplates folders. Restore their original ordering so the solution diff shows only the three new DirectTls entries. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * Disable AIA certificate downloads during client-cert chain build chain.Build for client-certificate validation runs on the pump thread. RevocationMode.NoCheck only suppresses CRL/OCSP; it does not stop the chain engine from making synchronous AIA fetches for missing intermediates. An attacker-supplied leaf with an unreachable AIA URL could stall every connection owned by that pump (a DoS vector). Set ChainPolicy.DisableCertificateDownloads = true, mirroring SslStream, which sets the same flag on the server side (SslStream.Protocol.cs). Legitimate clients send intermediates in the handshake, which are already loaded into ChainPolicy.ExtraStore, so valid connections are unaffected. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * Extract ClientCertificateValidator seam and add unit tests Factor the completed-handshake client-certificate validation (chain build, policy, callback) out of TlsEventPump into an internal static ClientCertificateValidator so it can be unit tested without epoll or a live TLS session. Behavior is unchanged. Also collapse the redundant post-validation GetRemoteCertificate() call: on the accept path the runtime promotes the pending cert into its canonical slot as the same instance, so the leaf surfaced to Kestrel reuses presentedCertificate instead of re-reading it. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * Add DirectTls HandshakeTimeout option and enforce it in the pump Adds a public HandshakeTimeout property to DirectTlsEndpointOptions (mirroring HttpsConnectionAdapterOptions: 10s default, rejects non-positive values, normalizes Timeout.InfiniteTimeSpan to TimeSpan.MaxValue) and enforces it in TlsEventPump: each handshaking connection gets a deadline set at accept, and PumpLoop sweeps expired handshakes every ~10ms via a bounded stackalloc buffer. This bounds slow/stalled handshakes (e.g. slowloris ClientHello) that would otherwise pin an fd and native TLS session indefinitely. Also renames the pump test seams off the *ForTests suffix and groups them into a single internal-for-testing block. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655 * cleanup * DirectTls: dispose-race fix, Linux-only test gating, backpressure buffer options - Fix a lost read-cancellation race in DirectTlsConnection dispose so a `Connection: close` response reliably reaches the client (ConnectionIoState, TlsAwaitable). - Gate the native-OpenSSL-dependent tests to Linux via [ConditionalFact] + [OSSkipCondition] so they skip instead of failing on Windows/macOS. - Add MaxReadBufferSize/MaxWriteBufferSize transport options plus the receive/ send plumbing that applies read- and write-side backpressure. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * DirectTls: de-flake e2e backpressure functional tests Rework both e2e backpressure tests to poll-until-stalled with 100 MiB payloads sent in 4 KiB chunks (Interlocked/Volatile progress counters + Assert.InRange), mirroring the canonical MaxRequestBufferSizeTests.LargeUpload idiom so they are robust on slow machines. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Fix DirectTls transport concurrency races (pump busy-spin, SSL op serialization, teardown) - Pump busy-spin: the drop paths in TlsEventPump.HandleConnectionEvent now de-register the fd from epoll (EPOLL_CTL_DEL) in addition to removing it from the connection table. Established-connection events are level-triggered, so a still-registered dead fd re-fired on every epoll_wait and was re-dropped at the _connections lookup, tight-spinning the pump thread at 100% CPU and starving every other connection it owned until disposal. Adds deterministic Linux-only unit tests. - Serialize per-connection SSL operations: a per-connection _sslLock now guards the native RawRead/RawWrite calls and the read/write state machine, so a completing read on the pump thread and a concurrent app write can no longer interleave into the same SSL session or drop a parked write's EPOLLOUT. - Locked Dispose: shutdown (close_notify) is emitted under _sslLock so it cannot race a concurrent SSL_read/SSL_write and corrupt the record stream. - Abort unblocks both loops: Abort now cancels the reusable read/write awaitables and the pending flush in addition to the pending read, so an app-initiated abort mid-response tears the connection down immediately instead of waiting for the peer's timeout (DirectTls closes the socket in DisposeAsync, not synchronously). - Log swallowed AuthenticationExceptions at Debug instead of silently mapping to EOF. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * DirectTls: make _sslLock I/O transitions structurally synchronous Follow-up hardening for the _sslLock serialization added in the previous commit. - Inline the read/write initiation and the pump-side completion transitions (ReadAsyncCore/WriteAsyncCore/OnReadableCore/OnWritableCore) directly into their lock (_sslLock) blocks in ReadAsync/WriteAsync/OnReadable/OnWritable. The bodies are moved verbatim (no behavior change), but keeping them lexically inside the lock makes any future await on these paths a CS1996 compile error instead of silently releasing the Monitor for the continuation - which would reintroduce the concurrent SSL_read/ SSL_write and epoll-interest races the lock exists to prevent. A plain helper call could hide such an await behind the method boundary and defeat that guard. - Rename the completion helpers TryCompleteRead/TryCompleteWrite -> TryCompleteReadUnsynchronized/TryCompleteWriteUnsynchronized and document that the caller must already hold _sslLock; they mutate the I/O state machine and issue the absolute epoll_ctl (via UpdateEvents) without taking the lock themselves. Validated: ConnectionIoStateTests 15/15 on Windows and the full DirectTls suite 66/66 on Linux, clean build (0 warnings). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Harden DirectTls resource ownership and pump failures Use Kestrel's memory pool factory and make each listener own its pool. Transfer accepted socket handles explicitly and isolate pump-loop failures. Require non-null logging dependencies and update lifecycle coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Address DirectTls review feedback Release early connections during pump shutdown and dispose converted client certificates. Regenerate project reference lists and use resolved references from tests and the sample. Correct ClientHello fd logging and add ownership regression coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * sync interest for DestinationTooSmall / NeedMoreData * safeguard connectioniostate disposal * proper order in complete handshake * guard against flushasync backpressure * arch agnostic epoll native structs * proper LIBC name * verify version * simplify * simplify abort * drop catching auth exception from session read/write * ssl lock on the cancel * handshake tracker + cap * cache and dispose socket for IConnectionSocketFeature * refactor to CTS-style pump stop * react to failed epoll_ctl * guard acceptedSocket * fail connection if callback failed * update interest on specific closed+armed EPOLLOUT case * dispose allocated resources on transport.Bind() failures * handle EPOLLERR/EPOLLHUP * accept4 to simplify creation * cap accepting connections in a single epoll wakeup iteration * use min alloc buffer size for memory alloc * practically select a suitable poll timeout * dont catch object disposed while tls fatal error * nit * document blocking callback behavior * use SOCK_CLOEXEC * cap early * critical epoll error leading to host shutdown * add explicit lock on socket creation / disposal * fire and forget conncetion disposal for closed-channel shutdown failure * nit --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Brennan Conroy <brecon@microsoft.com> Copilot-Session: 3d22b61a-2dc4-4417-ab8a-54529a87c655
1 parent efe577d commit 07d11eb

60 files changed

Lines changed: 7990 additions & 4 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AspNetCore.slnx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1062,6 +1062,7 @@
10621062
<Project Path="src/Servers/Kestrel/perf/Microbenchmarks/Microsoft.AspNetCore.Server.Kestrel.Microbenchmarks.csproj" />
10631063
</Folder>
10641064
<Folder Name="/src/Servers/Kestrel/samples/">
1065+
<Project Path="src/Servers/Kestrel/samples/DirectTlsTransportApp/DirectTlsTransportApp.csproj" />
10651066
<Project Path="src/Servers/Kestrel/samples/http2cat/http2cat.csproj" />
10661067
<Project Path="src/Servers/Kestrel/samples/Http2SampleApp/Http2SampleApp.csproj" />
10671068
<Project Path="src/Servers/Kestrel/samples/Http3SampleApp/Http3SampleApp.csproj" />
@@ -1080,6 +1081,10 @@
10801081
<Folder Name="/src/Servers/Kestrel/tools/">
10811082
<Project Path="src/Servers/Kestrel/tools/CodeGenerator/CodeGenerator.csproj" />
10821083
</Folder>
1084+
<Folder Name="/src/Servers/Kestrel/Transport.DirectTls/">
1085+
<Project Path="src/Servers/Kestrel/Transport.DirectTls/src/Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.csproj" />
1086+
<Project Path="src/Servers/Kestrel/Transport.DirectTls/test/Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.Tests.csproj" />
1087+
</Folder>
10831088
<Folder Name="/src/Servers/Kestrel/Transport.Quic/">
10841089
<Project Path="src/Servers/Kestrel/Transport.Quic/src/Microsoft.AspNetCore.Server.Kestrel.Transport.Quic.csproj" />
10851090
<Project Path="src/Servers/Kestrel/Transport.Quic/test/Microsoft.AspNetCore.Server.Kestrel.Transport.Quic.Tests.csproj" />

‎eng/ProjectReferences.props‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Server.IIS" ProjectPath="$(RepoRoot)src\Servers\IIS\IIS\src\Microsoft.AspNetCore.Server.IIS.csproj" />
5252
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Server.Kestrel.Core" ProjectPath="$(RepoRoot)src\Servers\Kestrel\Core\src\Microsoft.AspNetCore.Server.Kestrel.Core.csproj" />
5353
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Server.Kestrel" ProjectPath="$(RepoRoot)src\Servers\Kestrel\Kestrel\src\Microsoft.AspNetCore.Server.Kestrel.csproj" />
54+
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls" ProjectPath="$(RepoRoot)src\Servers\Kestrel\Transport.DirectTls\src\Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.csproj" />
5455
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes" ProjectPath="$(RepoRoot)src\Servers\Kestrel\Transport.NamedPipes\src\Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.csproj" />
5556
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Server.Kestrel.Transport.Quic" ProjectPath="$(RepoRoot)src\Servers\Kestrel\Transport.Quic\src\Microsoft.AspNetCore.Server.Kestrel.Transport.Quic.csproj" />
5657
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets" ProjectPath="$(RepoRoot)src\Servers\Kestrel\Transport.Sockets\src\Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.csproj" />

‎eng/ShippingAssemblies.props‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@
120120
<AspNetCoreShippingAssembly Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" />
121121
<AspNetCoreShippingAssembly Include="Microsoft.AspNetCore.Identity.Specification.Tests" />
122122
<AspNetCoreShippingAssembly Include="Microsoft.AspNetCore.Identity.UI" />
123+
<AspNetCoreShippingAssembly Include="Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls" />
123124
<AspNetCoreShippingAssembly Include="Microsoft.AspNetCore.Authentication.Certificate" />
124125
<AspNetCoreShippingAssembly Include="Microsoft.AspNetCore.Authentication.DeviceBoundSessions" />
125126
<AspNetCoreShippingAssembly Include="Microsoft.AspNetCore.Authentication.Facebook" />

‎eng/TrimmableProjects.props‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
<TrimmableProject Include="Microsoft.AspNetCore.Server.IIS" />
4242
<TrimmableProject Include="Microsoft.AspNetCore.Server.Kestrel.Core" />
4343
<TrimmableProject Include="Microsoft.AspNetCore.Server.Kestrel" />
44+
<TrimmableProject Include="Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls" />
4445
<TrimmableProject Include="Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes" />
4546
<TrimmableProject Include="Microsoft.AspNetCore.Server.Kestrel.Transport.Quic" />
4647
<TrimmableProject Include="Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets" />
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Diagnostics.CodeAnalysis;
5+
using System.Net;
6+
7+
namespace Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls;
8+
9+
/// <summary>
10+
/// An <see cref="IPEndPoint"/> that opts an endpoint into the DirectTls transport. Bind it with
11+
/// <c>KestrelServerOptions.Listen(...)</c> (or <c>ListenAnyIP</c>/<c>ListenLocalhost</c>) to serve that
12+
/// endpoint over the native, file-descriptor-bound OpenSSL TLS session instead of <c>SslStream</c>.
13+
/// </summary>
14+
/// <remarks>
15+
/// <para>
16+
/// DirectTls is TLS-only. The endpoint's <see cref="Options"/> must supply a server certificate (via
17+
/// <see cref="DirectTlsEndpointOptions.ServerCertificate"/> or
18+
/// <see cref="DirectTlsEndpointOptions.ServerCertificateSelector"/>).
19+
/// </para>
20+
/// </remarks>
21+
[Experimental("ASPNETCORE_DIRECTTLS_001", UrlFormat = "https://aka.ms/aspnetcore/directtls")]
22+
public sealed class DirectTlsEndpoint : IPEndPoint
23+
{
24+
/// <summary>
25+
/// Initializes a new <see cref="DirectTlsEndpoint"/> with a default <see cref="DirectTlsEndpointOptions"/>.
26+
/// </summary>
27+
/// <param name="address">The IP address to listen on.</param>
28+
/// <param name="port">The port to listen on.</param>
29+
public DirectTlsEndpoint(IPAddress address, int port)
30+
: this(address, port, new DirectTlsEndpointOptions())
31+
{
32+
}
33+
34+
/// <summary>
35+
/// Initializes a new <see cref="DirectTlsEndpoint"/> with the specified TLS options.
36+
/// </summary>
37+
/// <param name="address">The IP address to listen on.</param>
38+
/// <param name="port">The port to listen on.</param>
39+
/// <param name="options">The per-endpoint TLS configuration.</param>
40+
public DirectTlsEndpoint(IPAddress address, int port, DirectTlsEndpointOptions options)
41+
: base(address, port)
42+
{
43+
ArgumentNullException.ThrowIfNull(options);
44+
Options = options;
45+
}
46+
47+
/// <summary>
48+
/// Initializes a new <see cref="DirectTlsEndpoint"/> from an existing <see cref="IPEndPoint"/> with the specified TLS options.
49+
/// </summary>
50+
/// <param name="endpoint">The IP endpoint (address and port) to listen on.</param>
51+
/// <param name="options">The per-endpoint TLS configuration.</param>
52+
public DirectTlsEndpoint(IPEndPoint endpoint, DirectTlsEndpointOptions options)
53+
: this((endpoint ?? throw new ArgumentNullException(nameof(endpoint))).Address, endpoint.Port, options)
54+
{
55+
}
56+
57+
/// <summary>
58+
/// The per-endpoint TLS configuration for this endpoint.
59+
/// </summary>
60+
public DirectTlsEndpointOptions Options { get; }
61+
}
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Buffers;
5+
using System.Diagnostics.CodeAnalysis;
6+
using System.Net.Security;
7+
using System.Security.Authentication;
8+
using System.Security.Cryptography.X509Certificates;
9+
using Microsoft.AspNetCore.Connections;
10+
using Microsoft.AspNetCore.Server.Kestrel.Core;
11+
using Microsoft.AspNetCore.Server.Kestrel.Https;
12+
13+
namespace Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls;
14+
15+
/// <summary>
16+
/// Per-endpoint TLS configuration for an endpoint served by the DirectTls transport.
17+
/// </summary>
18+
/// <remarks>
19+
/// DirectTls is TLS-only: every endpoint served by this transport terminates TLS, so a server certificate
20+
/// (either <see cref="ServerCertificate"/> or <see cref="ServerCertificateSelector"/>) is required.
21+
/// </remarks>
22+
[Experimental("ASPNETCORE_DIRECTTLS_001", UrlFormat = "https://aka.ms/aspnetcore/directtls")]
23+
public sealed class DirectTlsEndpointOptions
24+
{
25+
/// <summary>
26+
/// The server certificate presented during the TLS handshake. Used when
27+
/// <see cref="ServerCertificateSelector"/> is not set or returns <see langword="null"/>.
28+
/// </summary>
29+
public X509Certificate2? ServerCertificate { get; set; }
30+
31+
/// <summary>
32+
/// A callback that selects the server certificate based on the connection and the SNI host name parsed
33+
/// from the ClientHello. When set, it is invoked once per connection before the certificate is installed;
34+
/// returning <see langword="null"/> falls back to <see cref="ServerCertificate"/>.
35+
/// </summary>
36+
/// <remarks>
37+
/// The first argument is the <see cref="ConnectionContext"/> for the connection being negotiated (already
38+
/// allocated so it carries the same connection id that will later serve the request); the second is the
39+
/// requested SNI host name, or <see langword="null"/> when the client did not send one.
40+
/// <para>
41+
/// This callback runs synchronously on the epoll worker thread that owns the connection and must not block.
42+
/// A blocking or long-running callback stalls the handshake and I/O of every connection assigned to that worker.
43+
/// </para>
44+
/// </remarks>
45+
public Func<ConnectionContext?, string?, X509Certificate2?>? ServerCertificateSelector { get; set; }
46+
47+
/// <summary>
48+
/// The allowable TLS protocol versions. <see cref="SslProtocols.None"/> (the default) lets the operating
49+
/// system choose an appropriate default set.
50+
/// </summary>
51+
public SslProtocols SslProtocols { get; set; } = SslProtocols.None;
52+
53+
/// <summary>
54+
/// Whether a client certificate is requested and/or required during the handshake (mutual TLS).
55+
/// </summary>
56+
/// <remarks>
57+
/// Defaults to <see cref="ClientCertificateMode.NoCertificate"/>.
58+
/// <see cref="ClientCertificateMode.DelayCertificate"/> is not supported (see https://github.com/dotnet/aspnetcore/issues/67915)
59+
/// </remarks>
60+
public ClientCertificateMode ClientCertificateMode { get; set; } = ClientCertificateMode.NoCertificate;
61+
62+
/// <summary>
63+
/// A callback used to validate a client certificate when <see cref="ClientCertificateMode"/> requests one.
64+
/// Return <see langword="true"/> to accept the certificate. When not set, a certificate is accepted only
65+
/// when it produced no <see cref="SslPolicyErrors"/>.
66+
/// </summary>
67+
/// <remarks>
68+
/// This callback runs synchronously on the epoll worker thread that owns the connection and must not block.
69+
/// A blocking or long-running callback stalls the handshake and I/O of every connection assigned to that worker.
70+
/// </remarks>
71+
public Func<X509Certificate2, X509Chain?, SslPolicyErrors, bool>? ClientCertificateValidation { get; set; }
72+
73+
/// <summary>
74+
/// An optional callback invoked with the raw ClientHello record bytes as soon as they are parsed, before
75+
/// the handshake completes.
76+
/// </summary>
77+
/// <remarks>
78+
/// The <see cref="ReadOnlySequence{T}"/> is only valid for the duration of the callback; copy the bytes
79+
/// (for example with <c>ToArray()</c>) if they must outlive the call. The first argument is the
80+
/// <see cref="ConnectionContext"/> for the connection being negotiated.
81+
/// <para>
82+
/// This callback runs synchronously on the epoll worker thread that owns the connection and must not block.
83+
/// A blocking or long-running callback stalls the handshake and I/O of every connection assigned to that worker.
84+
/// </para>
85+
/// </remarks>
86+
public Action<ConnectionContext, ReadOnlySequence<byte>>? TlsClientHelloBytesCallback { get; set; }
87+
88+
/// <summary>
89+
/// Overrides the transport-wide worker count (<c>DirectTlsTransportOptions.WorkerCount</c>) for this
90+
/// endpoint. When <see langword="null"/> (the default), the transport-wide worker count is used.
91+
/// </summary>
92+
/// <remarks>
93+
/// Each DirectTls endpoint runs its own pool of worker threads, so a server's total thread count is the sum
94+
/// of every bound endpoint's worker count. Set this on individual endpoints to bound threads when hosting
95+
/// several DirectTls endpoints — for example, a low-traffic management port can use far fewer workers than a
96+
/// public HTTPS port. Must be greater than zero when set.
97+
/// </remarks>
98+
public int? WorkerCount
99+
{
100+
get;
101+
set
102+
{
103+
if (value is <= 0)
104+
{
105+
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(WorkerCount)} must be greater than zero when set.");
106+
}
107+
108+
field = value;
109+
}
110+
}
111+
112+
/// <summary>
113+
/// The maximum amount of time allowed for the TLS handshake to complete on a connection to this endpoint.
114+
/// A connection whose handshake does not finish within this window is dropped. Defaults to 10 seconds.
115+
/// Set to <see cref="Timeout.InfiniteTimeSpan"/> to disable the timeout; any other non-positive value is rejected.
116+
/// </summary>
117+
/// <remarks>
118+
/// This bounds slow or stalled handshakes — for example a client that opens a connection and then dribbles
119+
/// the ClientHello one byte at a time — which would otherwise keep a file descriptor and its native TLS
120+
/// session pinned to a worker indefinitely. It mirrors <see cref="HttpsConnectionAdapterOptions.HandshakeTimeout"/>,
121+
/// which provides the same protection for the <see cref="SslStream"/>-based HTTPS middleware, and shares its
122+
/// 10-second default.
123+
/// </remarks>
124+
public TimeSpan HandshakeTimeout
125+
{
126+
get;
127+
set
128+
{
129+
if (value <= TimeSpan.Zero && value != Timeout.InfiniteTimeSpan)
130+
{
131+
throw new ArgumentOutOfRangeException(nameof(value), CoreStrings.PositiveTimeSpanRequired);
132+
}
133+
134+
field = value != Timeout.InfiniteTimeSpan ? value : TimeSpan.MaxValue;
135+
}
136+
} = HttpsConnectionAdapterOptions.DefaultHandshakeTimeout;
137+
138+
/// <summary>
139+
/// The HTTP protocols (ALPN) advertised for this endpoint,
140+
/// sourced from <see cref="ListenOptions.Protocols"/> after the endpoint has been configured.
141+
/// </summary>
142+
internal HttpProtocols HttpProtocols { get; set; } = HttpProtocols.Http1AndHttp2;
143+
}

‎src/Servers/Kestrel/Core/src/Microsoft.AspNetCore.Server.Kestrel.Core.csproj‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
<IsPackable>false</IsPackable>
1111
<DefineConstants>$(DefineConstants);KESTREL</DefineConstants>
1212
<NoWarn>$(NoWarn);IDE0060</NoWarn><!-- APIs in HTTP3 are work in progress and produce these warnings frequently-->
13+
<NoWarn>$(NoWarn);ASPNETCORE_DIRECTTLS_001</NoWarn> <!-- ASPNETCORE_DIRECTTLS_001 is the [Experimental] id on the DirectTls endpoint/options types defined here -->
1314
<IsTrimmable>true</IsTrimmable>
1415
<EnablePreviewFeatures>true</EnablePreviewFeatures>
1516
<GenerateRequiresPreviewFeaturesAttribute>false</GenerateRequiresPreviewFeaturesAttribute>
@@ -74,6 +75,7 @@
7475
<InternalsVisibleTo Include="InMemory.FunctionalTests" />
7576
<InternalsVisibleTo Include="Sockets.BindTests" />
7677
<InternalsVisibleTo Include="Microsoft.AspNetCore.Server.Kestrel" />
78+
<InternalsVisibleTo Include="Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls" />
7779
<InternalsVisibleTo Include="Microsoft.AspNetCore.Server.Kestrel.Core.Tests" />
7880
<InternalsVisibleTo Include="Microsoft.AspNetCore.Server.Kestrel.Microbenchmarks" />
7981
<InternalsVisibleTo Include="Microsoft.AspNetCore.Server.Kestrel.Transport.NamedPipes.Tests" />
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,25 @@
11
#nullable enable
2+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpoint
3+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpoint.DirectTlsEndpoint(System.Net.IPAddress! address, int port) -> void
4+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpoint.DirectTlsEndpoint(System.Net.IPAddress! address, int port, Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions! options) -> void
5+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpoint.DirectTlsEndpoint(System.Net.IPEndPoint! endpoint, Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions! options) -> void
6+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpoint.Options.get -> Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions!
7+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions
8+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.DirectTlsEndpointOptions() -> void
9+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.ClientCertificateMode.get -> Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode
10+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.ClientCertificateMode.set -> void
11+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.ClientCertificateValidation.get -> System.Func<System.Security.Cryptography.X509Certificates.X509Certificate2!, System.Security.Cryptography.X509Certificates.X509Chain?, System.Net.Security.SslPolicyErrors, bool>?
12+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.ClientCertificateValidation.set -> void
13+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.HandshakeTimeout.get -> System.TimeSpan
14+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.HandshakeTimeout.set -> void
15+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.ServerCertificate.get -> System.Security.Cryptography.X509Certificates.X509Certificate2?
16+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.ServerCertificate.set -> void
17+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.ServerCertificateSelector.get -> System.Func<Microsoft.AspNetCore.Connections.ConnectionContext?, string?, System.Security.Cryptography.X509Certificates.X509Certificate2?>?
18+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.ServerCertificateSelector.set -> void
19+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.SslProtocols.get -> System.Security.Authentication.SslProtocols
20+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.SslProtocols.set -> void
21+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.TlsClientHelloBytesCallback.get -> System.Action<Microsoft.AspNetCore.Connections.ConnectionContext!, System.Buffers.ReadOnlySequence<byte>>?
22+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.TlsClientHelloBytesCallback.set -> void
23+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.WorkerCount.get -> int?
24+
Microsoft.AspNetCore.Server.Kestrel.Transport.DirectTls.DirectTlsEndpointOptions.WorkerCount.set -> void
225
static Microsoft.AspNetCore.Hosting.ListenOptionsHttpsExtensions.UseTlsClientHelloListener(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions! listenOptions, System.Action<Microsoft.AspNetCore.Connections.ConnectionContext!, System.Buffers.ReadOnlySequence<byte>>! tlsClientHelloBytesCallback, System.TimeSpan? timeout = null) -> Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions!

0 commit comments

Comments
 (0)