Skip to content

PoC: low level TLS machine#128744

Closed
wfurt wants to merge 68 commits into
dotnet:mainfrom
wfurt:TlsSession
Closed

PoC: low level TLS machine#128744
wfurt wants to merge 68 commits into
dotnet:mainfrom
wfurt:TlsSession

Conversation

@wfurt

@wfurt wfurt commented May 29, 2026

Copy link
Copy Markdown
Member

early prototype -> ignore.

wfurt and others added 11 commits May 27, 2026 02:40
Introduces internal-preview public types TlsContext, TlsSession, and
TlsOperationStatus exposing a non-blocking, transport-agnostic TLS
state machine. The PoC implementation is Linux/FreeBSD-only and reuses
the existing SslStreamPal (AcceptSecurityContext / InitializeSecurityContext
/ EncryptMessage / DecryptMessage). On other platforms the types are
present as PlatformNotSupportedException stubs so ApiCompat passes.

SslStream is intentionally untouched (Stage 1 of the proposal).

Adds TlsSessionTests covering:
  - Server TlsSession against a real SslStream client (handshake + ping/pong)
  - ArgumentNullException from TlsContext.Create
  - InvalidOperationException from Encrypt/Decrypt before handshake
Adds an internal wedge in SslStream that routes NextMessage / Encrypt /
Decrypt through TlsSession on Linux/FreeBSD. On other platforms the
partial method stubs return false and the existing PAL path runs
unchanged.

TlsSession additions:
  - TlsContext.WrapShared() so the wedge can reuse SslStream's own
    SslAuthenticationOptions bag (preserves SNI / cert selection results
    and avoids double Dispose).
  - HandshakeStepForSslStream / EncryptForSslStream / DecryptForSslStream
    surface that keeps SslStream's ProtocolToken-based plumbing intact.
  - SecurityContext / CredentialsHandle accessors so SslStream can mirror
    the SafeHandles back into its own fields for cert validation, channel
    binding, ProcessHandshakeSuccess, and Dispose to continue working.
  - TlsOperationStatus.WantCredentials surfaced from ProcessHandshake
    when the PAL reports CredentialsNeeded (OpenSSL client cert path).
  - Decrypt now treats Renegotiate as transparent: OpenSSL handles
    renegotiation internally inside SSL_read, so we just consume the
    frame and ask for more input.

The wedge calls AcquireServerCredentials / AcquireClientCredentials on
the very first server / client handshake step to preserve the legacy
GenerateToken bootstrap (resolves the cert via the various delegates
and assigns CertificateContext, which Interop.OpenSsl asserts on).

Test status: 4969 of 4977 pass with wedge active; remaining 8 are TLS
1.3 post-handshake auth scenarios (mutual auth + client-cert callback
returning null) that need follow-up. No new tests broken vs. baseline.
Adds public TlsOperationStatus Shutdown(Span<byte>, out int) to TlsSession
on Linux/FreeBSD plus a PNSE stub on other platforms. Drives
SslStreamPal.ApplyShutdownToken followed by one PAL handshake step to
extract the close_notify bytes into pending output. Idempotent across
drains; returns Closed once fully drained.

Adds test ServerSession_Shutdown_DeliversCloseNotifyToSslStreamClient
verifying an SslStream client observes EOF after the server-side shutdown.
Adds public ChannelBinding? GetChannelBinding(ChannelBindingKind) to
TlsSession on Linux/FreeBSD plus a PNSE stub on other platforms.
Delegates to SslStreamPal.QueryContextChannelBinding so the binding
material matches what SslStream produces over the same session.

Adds test ServerSession_ChannelBinding_MatchesSslStreamClient that
authenticates an SslStream client against a TlsSession server and
verifies both sides derive the same tls-unique channel binding bytes.
Adds two public APIs on TlsSession (Linux/FreeBSD) with PNSE stubs on
other platforms:

- X509Certificate2? LocalCertificate { get; } returns the server cert on
  a server session, or the negotiated client cert on a client session
  (using CertificateValidationPal.IsLocalCertificateUsed to gate the
  client-side case after handshake).
- TlsOperationStatus RequestClientCertificate(Span<byte>, out int) drives
  SslStreamPal.Renegotiate which, on TLS 1.3, issues a post-handshake
  CertificateRequest, and on TLS 1.2 initiates renegotiation. The
  generated bytes flow through the pending-output buffer. After the
  caller forwards them and continues normal Decrypt, the peer's response
  is processed transparently by OpenSSL and the new certificate becomes
  observable via GetRemoteCertificate.

The mutual-auth round trip is not yet end-to-end covered by a TlsSession
test because TlsSession lacks plumbing for RemoteCertificateValidationCallback
on the standalone path (Interop.OpenSsl.CertVerifyCallback derefs
options.SslStream, which TlsSession does not own). That gap also affects
any initial-handshake mutual-auth scenario on a standalone TlsSession
and is tracked as a separate follow-up.
Standalone TlsSession instances did not invoke the user-supplied
RemoteCertificateValidationCallback because the OpenSSL CertVerifyCallback
dereferenced options.SslStream, which is only set when an SslStream owns
the session. Mutual-auth (including TLS 1.3 PHA) failed with
'certificate verify failed'.

Decouple the verify callback from SslStream:
- Add VerifyRemoteCertificateCallback delegate + RemoteCertificateValidator
  hook on SslAuthenticationOptions, plus a SafeSslHandle slot populated by
  SafeSslHandle.Create.
- Extract SslStream.VerifyRemoteCertificate's core into a static helper
  (VerifyRemoteCertificateCore) shared by SslStream and TlsSession.
- TlsSession.Create registers its own validator on the options when one
  isn't already set (SslStream wedge keeps its own).
- Interop.OpenSsl.CertVerifyCallback now drives the hook + handle on
  options instead of options.SslStream.

Add a server-side mutual-auth test that verifies the standalone
TlsSession surfaces the client certificate to the user callback.
The Encrypt/Decrypt wedge was a pure pass-through: both the wedged and
direct paths called SslStreamPal.{Encrypt,Decrypt}Message on the same
_securityContext (TlsSession mirrors that handle back to SslStream
after each handshake step). There was no PAL difference to hide, just
an extra hop, two partial methods, and the TlsSession-side helpers.

Remove TryEncryptViaTlsSession / TryDecryptViaTlsSession (both partial
declarations and Unix/NotUnix implementations), inline the PAL call in
SslStream.Encrypt / SslStream.Decrypt, and drop the now-dead
EncryptForSslStream / DecryptForSslStream helpers on TlsSession.

The handshake wedge stays — that one owns credentials acquisition and
the ProtocolToken plumbing, so it's a meaningful demonstration that
TlsSession can host SslStream's TLS engine.
Two new tests:

1. TwoSessions_HandshakeAndPingPong_InMemory_Succeeds
   Pure in-memory TlsSession <-> TlsSession: no transport, no async at all.
   Drives both sides synchronously through ProcessHandshake by swapping
   byte arrays. Proves the TlsSession surface is a self-contained TLS
   engine that doesn't need SslStream or any I/O abstraction.

   Pinned to TLS 1.2: a pure in-memory two-session loop currently does
   not handle the TLS 1.3 post-handshake NewSessionTicket records OpenSSL
   emits after the server consumes the client Finished. With SslStream
   on one side those records are absorbed by SslStream's data path. The
   standalone TlsSession surface does not yet handle them (same scope
   as the PHA / renegotiation gap).

2. ClientSession_AgainstSslStreamServer_HandshakeAndPingPong_Succeeds
   Mirror of the existing server-side test: TlsSession is the client,
   SslStream is the server. Confirms the handshake driver is role-
   agnostic. Renamed DriveServerHandshakeAsync to DriveHandshakeAsync
   to reflect that it works for either role.
Two changes:

1. Fix the in-memory two-session TLS 1.3 case. The previous 'bad MAC'
   failure was not a bug -- it was OpenSSL's normal TLS 1.3 state
   machine behavior surfacing in an unusual call pattern. After the
   server consumes the client Finished it emits NewSessionTicket
   records on the server->client side. The client MUST consume those
   records (via Decrypt) before its first Encrypt call: otherwise
   OpenSSL on the client has not yet finalized its write-key
   transition from client_handshake_traffic_secret to
   client_application_traffic_secret, and the server (which has
   already moved its receive key) rejects the resulting ciphertext as
   'decryption failed or bad record mac'. In real network deployments
   the client's receive pump always consumes these bytes before
   sending; in this synchronous in-memory loop we drain them
   explicitly. Test is now a [Theory] covering both TLS 1.2 and
   TLS 1.3.

2. Add ServerSession_OnNonBlockingSocket_AgainstSslStreamClient_Succeeds.
   Drives a TlsSession-as-server against a real loopback Socket in
   non-blocking mode (Socket.Blocking = false). Sends and receives go
   through Socket.Send/Receive directly and handle WouldBlock by
   polling. The peer is a plain SslStream client over a NetworkStream.
   Exercises the 'give me raw socket bytes, I don't care about your
   I/O model' contract end to end: TlsSession itself never blocks on
   I/O; the caller is responsible for transport readiness.
On TLS 1.3, SChannel surfaces SEC_I_RENEGOTIATE from DecryptMessage for post-handshake records (NewSessionTicket, KeyUpdate, post-handshake CertificateRequest). The decrypted inner record must be fed back into AcceptSecurityContext/InitializeSecurityContext or the next DecryptMessage returns SEC_E_CONTEXT_EXPIRED.

Decrypt now invokes a new ProcessPostHandshakeMessage helper and returns Complete so the caller's loop re-enters to process any application data that arrived in the same TCP segment as the NST.

All TlsSessionTests pass (13/13).
@wfurt wfurt added the NO-MERGE The PR is not ready for merge yet (see discussion for detailed reasons) label May 29, 2026
Copilot AI review requested due to automatic review settings May 29, 2026 05:21
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/ncl, @bartonjs, @vcsjones
See info in area-owners.md if you want to be subscribed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR prototypes a low-level, caller-driven TLS state machine for System.Net.Security, exposing TlsContext, TlsSession, and TlsOperationStatus, and wiring Linux/FreeBSD SslStream handshakes through that implementation as a wedge.

Changes:

  • Adds new public TLS session/context APIs and platform-specific implementations/stubs.
  • Refactors certificate validation plumbing so OpenSSL callbacks can be shared by SslStream and TlsSession.
  • Adds functional tests for handshake, encryption/decryption, ALPN, SNI, shutdown, channel binding, and renegotiation scenarios.

Reviewed changes

Copilot reviewed 17 out of 17 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/libraries/System.Net.Security/ref/System.Net.Security.cs Adds public API surface for TlsContext, TlsSession, and TlsOperationStatus.
src/libraries/System.Net.Security/src/System.Net.Security.csproj Includes new TLS session and SslStream wedge files by platform.
src/libraries/System.Net.Security/src/System/Net/Security/TlsContext.cs Adds reusable TLS configuration wrapper over SslAuthenticationOptions.
src/libraries/System.Net.Security/src/System/Net/Security/TlsOperationStatus.cs Adds operation status enum for non-blocking TLS operations.
src/libraries/System.Net.Security/src/System/Net/Security/TlsSession.cs Implements the low-level TLS state machine.
src/libraries/System.Net.Security/src/System/Net/Security/TlsSession.Stub.cs Adds unsupported-platform stub implementation.
src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Unix.cs Routes Unix SslStream handshake steps through TlsSession.
src/libraries/System.Net.Security/src/System/Net/Security/SslStream.NotUnix.cs Keeps non-Unix SslStream on the existing path.
src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs Adds wedge hook and shared certificate validation core.
src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs Wires OpenSSL certificate validation callback through options.
src/libraries/System.Net.Security/src/System/Net/Security/SslAuthenticationOptions.cs Adds callback and handle slots for OpenSSL validation plumbing.
src/libraries/System.Net.Security/src/System/Net/Security/NetEventSource.Security.cs Generalizes certificate validation logging sender type.
src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs Stores the created SafeSslHandle on authentication options.
src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs Uses the new options-based validation callback path.
src/libraries/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj Includes new TLS session tests on Unix/Windows targets.
src/libraries/System.Net.Security/tests/FunctionalTests/TlsSessionTests.cs Adds functional coverage for the prototype API.
src/libraries/System.Net.Security/tests/UnitTests/Fakes/FakeSslStream.Implementation.cs Updates fake options to match the new callback field.

Comment on lines +871 to +882
SslStream.VerifyRemoteCertificateCore(
this,
_context.Options,
_securityContext,
ref _remoteCertificate,
ref _connectionInfo,
cert,
chain,
trust: null,
ref alertToken,
out _,
out _);
TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256 = (ushort)53251,
TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256 = (ushort)53253,
}
public enum TlsOperationStatus
// can drive the user RemoteCertificateValidationCallback even for a
// standalone TlsSession. If SslStream wraps this session (wedge mode),
// it sets its own validator first and we leave it untouched.
context.Options.RemoteCertificateValidator ??= session.VerifyRemoteCertificate;
Comment on lines +862 to +864
bool needsValidation = !_context.IsServer || _context.Options.RemoteCertRequired;
if (needsValidation)
{
Mirror legacy GenerateToken's bookkeeping: when AcquireClientCredentials is
re-run with newCredentialsRequested=true (in response to SChannel's
CredentialsNeeded after parsing the server's CertificateRequest), set
refreshCredentialNeeded so the finally-block publishes the new cert-bound
credential to SslSessionsCache. Without this, subsequent connections always
missed the cache (anonymous cred cached, cert-bound cred discarded) and the
SChannel session ticket never resumed.

Also routes credential ownership through TlsContext so the wedge and standalone
TlsContext.Create paths share lifetime semantics, and removes diagnostic
file-logging used during root-cause analysis.

Validated: System.Net.Security.Tests full suite — Total 5247, Failed 0, Skipped 40.
Copilot AI review requested due to automatic review settings May 29, 2026 20:26

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 4 comments.

Comment on lines +690 to +698
public enum TlsOperationStatus
{
Complete = 0,
WantRead = 1,
WantWrite = 2,
Closed = 3,
WantCredentials = 4,
NeedsCertificateValidation = 5,
}
Comment on lines +85 to +90
// Provide a default cert validation hook so OpenSSL's CertVerifyCallback
// can drive the user RemoteCertificateValidationCallback even for a
// standalone TlsSession. If SslStream wraps this session (wedge mode),
// it sets its own validator first and we leave it untouched.
context.Options.RemoteCertificateValidator ??= session.VerifyRemoteCertificate;
}
Comment on lines +235 to +236
SetRemoteCertificateValidationResult(ok ? SslPolicyErrors.None : sslPolicyErrors);
return sslPolicyErrors;
Comment on lines +1070 to +1081
SslStream.VerifyRemoteCertificateCore(
this,
_context.Options,
_securityContext,
ref _remoteCertificate,
ref _connectionInfo,
cert,
chain,
trust: null,
ref alertToken,
out _,
out _);
wfurt added 2 commits May 29, 2026 15:04
… 3.0+

Wires up the OpenSSL 3.0 SSL_set_retry_verify lightup so SslStream-style
external certificate validation can suspend the TLS handshake mid-stream
on 3.0+ and resume after the application accepts/rejects the peer cert.
Falls back to the existing post-handshake suspension on 1.1.x.

Native:
 - Add CryptoNative_SslSetRetryVerify export (LIGHTUP_FUNCTION pattern).
 - Add PAL_SSL_ERROR_WANT_RETRY_VERIFY (= 12) and forward-declare
   SSL_set_retry_verify in osslcompat_30.h; ifndef-guard the error code
   for 1.1.x headers.

Managed:
 - Add SslErrorCode.SSL_ERROR_WANT_RETRY_VERIFY and matching P/Invoke.
 - DoSslHandshake maps the new error to NeedsRemoteCertificateValidation.
 - CertVerifyCallback calls SslSetRetryVerify and returns -1 to suspend
   when DeferCertificateValidation is set and no managed validator is
   provided; otherwise falls through to the legacy accept-and-validate
   path.
 - Add internal SslAuthenticationOptions.DeferCertificateValidation
   (OpenSSL only).
 - TlsSession enables DeferCertificateValidation, drops the dummy
   AcceptAllForExternalValidation callback, and tracks
   _externalValidationResolved so the second ProcessHandshake call after
   validation succeeds returns Complete rather than throwing.

Tests: System.Net.Security functional suite 4965 / 0 fail / 19 skip on
macOS arm64.
…erOptions)

Allow TlsContext.Create to be called with null SslServerAuthenticationOptions
so the caller can inspect the peer's ClientHello (SNI, supported versions)
before supplying server options. ProcessHandshake parses the first ClientHello,
exposes it via TlsSession.ClientHelloInfo, and returns NeedsServerOptions with
consumed = 0. The caller then calls SetServerOptions(...) and re-feeds the
same input buffer to resume the handshake.

- TlsOperationStatus.NeedsServerOptions = 6
- TlsContext.Create(SslServerAuthenticationOptions?) accepts null
- TlsSession.ClientHelloInfo / SetServerOptions surface and resume the suspend
- ProcessHandshake parses ClientHello via TlsFrameHelper, suspends with
  consumed=0, and re-returns NeedsServerOptions on subsequent calls until
  options are supplied; on OpenSSL the retry-verify suspension semantics
  are restored after ApplyServerOptions
- Ref assembly and Stub updated to match
Copilot AI review requested due to automatic review settings May 29, 2026 22:48

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 25 out of 25 changed files in this pull request and generated 6 comments.

[Fact]
public void TlsContext_RejectsNullOptions()
{
Assert.Throws<ArgumentNullException>(() => TlsContext.Create((SslServerAuthenticationOptions)null!));
TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256 = (ushort)53251,
TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256 = (ushort)53253,
}
public enum TlsOperationStatus
Comment on lines +458 to +460
// CertVerifyCallback needs the SafeSslHandle to stash a
// CertificateValidationException; expose it via the options.
options.SafeSslHandle = handle;
Comment on lines +222 to +225
// On success VerifyRemoteCertificateCore set _remoteCertificate = _externalPendingCert, so
// SetRemoteCertificateValidationResult below leaves it alone. On failure we must dispose the
// pending cert ourselves because no one adopted it.
SetRemoteCertificateValidationResult(ok ? SslPolicyErrors.None : sslPolicyErrors);
Comment on lines +97 to +100
public string? TargetHostName
{
get => _context.Options.TargetHost;
set => _context.Options.TargetHost = value ?? string.Empty;
Comment on lines +320 to +326
_context.ApplyServerOptions(options);
#if !TARGET_WINDOWS && !SYSNETSECURITY_NO_OPENSSL
// Preserve the retry-verify suspension semantics that TlsSession.Create
// would have configured up front had server options been available then.
_context.Options.DeferCertificateValidation = true;
#endif
_clientHelloInfo = null;
Copilot AI review requested due to automatic review settings July 6, 2026 03:08
@wfurt

wfurt commented Jul 6, 2026

Copy link
Copy Markdown
Member Author

Setup

  • 30 iterations × 128 invocations × warmup 10, InProcessEmitToolchain
  • Pinned to a single core (taskset -c 2)
  • Loopback TCP, self-signed cert, ping/pong after handshake
  • [Params(false, true)] AllowResume toggles TLS session resumption on both sides
  • Rows sorted by protocol + resume state, Baseline = SslStream_Server

Results

Method Protocol AllowResume Mean (µs) Error StdDev Ratio Allocated
SslStream_Server Tls12 False 2,786 32 41 1.00 10.55 KB
TlsSession_Buffered_Server Tls12 False 2,310 14 19 0.83 46.15 KB
TlsSession_Fd_Server Tls12 False 2,244 7 10 0.81 7.80 KB
TlsSession_Fd_Deferred_Server Tls12 False 2,262 5 7 0.81 8.27 KB
SslStream_Server Tls12 True 1,176 6 9 1.00 10.79 KB
TlsSession_Buffered_Server Tls12 True 1,009 7 11 0.86 46.17 KB
TlsSession_Fd_Server Tls12 True 959 5 7 0.82 8.04 KB
TlsSession_Fd_Deferred_Server Tls12 True 982 6 9 0.84 8.54 KB
SslStream_Server Tls13 False 2,798 4 6 1.00 10.45 KB
TlsSession_Buffered_Server Tls13 False 2,463 7 10 0.88 46.11 KB
TlsSession_Fd_Server Tls13 False 2,406 5 8 0.86 7.63 KB
TlsSession_Fd_Deferred_Server Tls13 False 2,445 7 11 0.87 8.19 KB
SslStream_Server Tls13 True 1,640 6 8 1.00 10.78 KB
TlsSession_Buffered_Server Tls13 True 1,494 8 12 0.91 46.33 KB
TlsSession_Fd_Server Tls13 True 1,442 4 7 0.88 8.01 KB
TlsSession_Fd_Deferred_Server Tls13 True 1,466 7 11 0.89 8.59 KB

Fd → Fd_Deferred overhead (peek + parse + BIO handoff)

Config Δ time Δ alloc % of handshake
Tls12 full +18 µs +0.47 KB +0.8%
Tls13 full +39 µs +0.56 KB +1.6%
Tls12 resume +23 µs +0.50 KB +2.4%
Tls13 resume +25 µs +0.58 KB +1.7%

Confirmed assumptions

  1. Fd_Deferred vs Fd overhead is ~18-39 µs, ~500 B. Consistent across protocols and resumption. That's the peek + parse + SslClientHelloInfo (SNI string) + BIO handoff, dominated by one extra recv syscall.
  2. The parse portion (~5-10 µs, ~500 B for the SNI string) is what we'd skip on an "always capture, no parse" path when options are already supplied up front. Real cost of always-capture without parse: ~10-15 µs, ~50-100 B.
  3. Both are well inside the noise floor of a real network handshake — loopback here is best case; real RTT adds tens of ms which dwarfs the µs deltas.
  4. Earlier claims about "Tls12 shows bigger delta than Tls13" were pure noise from short runs bouncing across cores. With pinning + 30×128 iterations the deltas are stable and roughly protocol-independent.

Implication for the ClientHello-capture API

The cost is low enough to justify always capturing ClientHello bytes on the server side by default, with an AppContext opt-out (System.Net.Security.CaptureClientHello, cached once at process init) for anyone who wants the last ~1%.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 42 out of 43 changed files in this pull request and generated 3 comments.

Comment on lines +690 to +707
public enum TlsOperationStatus
{
Complete = 0,
WantRead = 1,
WantWrite = 2,
Closed = 3,
WantCredentials = 4,
NeedsCertificateValidation = 5,
NeedsServerOptions = 6,
}
[System.Diagnostics.CodeAnalysis.ExperimentalAttribute("SYSLIB5007", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")]
public sealed partial class TlsContext : System.IDisposable
{
internal TlsContext() { }
public bool IsServer { get { throw null; } }
public static System.Net.Security.TlsContext Create(System.Net.Security.SslServerAuthenticationOptions? options) { throw null; }
public static System.Net.Security.TlsContext Create(System.Net.Security.SslClientAuthenticationOptions options) { throw null; }
public void Dispose() { }
Comment on lines 16 to +23
#include "pal_networkframework.h"
#include <Foundation/Foundation.h>
#include <Network/Network.h>
#include <Security/Security.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
Comment on lines +497 to +503
_options.CertificateContext = context;

// Drop the cached credentials handle (acquired without a client cert) so the
// next ProcessHandshake re-acquires with the supplied context.
_context.CredentialsHandle?.Dispose();
_context.CredentialsHandle = null;
_resumeAfterCredentials = true;
wfurt added 4 commits July 6, 2026 06:36
…Context

SetClientCertificateContext used to dispose and null the shared

TlsContext.CredentialsHandle, which raced with any concurrent session

on the same context (crashes or wrong-cert delivery on SChannel).

Introduce a session-local override acquired eagerly in

SetClientCertificateContext. ActiveCredentialsRef() returns a ref to

the session-local handle when set, else the shared context handle.

Session Dispose releases the session-local handle.

Also fix pal_networkframework.m: add missing #include <errno.h>.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 43 out of 44 changed files in this pull request and generated 2 comments.

Comment on lines +2111 to +2114
// Disposes the underlying SafeSocketHandle as well (ownership transferred at Create).
_socket?.Dispose();
_socket = null;
_socketHandle = null;
Comment on lines +412 to +416
if (listener == NULL)
{
LOG_ERROR(context, "Failed to create server listener");
return NULL;
}
wfurt added 6 commits July 7, 2026 00:47
Same bug class as SetClientCertificateContext (fixed in cbbf7a3):

acquiring credentials into the shared TlsContext.CredentialsHandle races

with concurrent sessions on the same bootstrap. On SChannel the first

session to resolve to a tenant would stamp its credentials into the shared

field and every subsequent session on the same bootstrap would inherit

them regardless of which tenant it resolved to.

Acquire session-local eagerly in SetServerContext for consistency with

the client-side flow. Adds a concurrent-tenant-dispatch regression test.
WantRead -> NeedMoreData
WantWrite -> DestinationTooSmall
WantCredentials -> CertificateRequested
NeedsServerOptions -> NeedsTlsContext

Also flag the enum as [Experimental(SYSLIB5007)].
…ublic IsServer

Options are now non-nullable. Deferred server flow is triggered by passing an
empty SslServerAuthenticationOptions (no cert / no selection callback), which
suspends the first handshake call on NeedsTlsContext.
- TlsContext.Create -> CreateServer / CreateClient (non-nullable options).
  Deferred-server flow now uses new SslServerAuthenticationOptions() (empty bag).
  TlsContext.IsServer downgraded to internal.
- TlsSession: sealed -> abstract with private protected ctor.
- Split into TlsBufferSession (buffer-based Handshake/Read/Write/Shutdown/
  RequestClientCertificate/DrainPendingOutput) and TlsSocketSession
  (socket-bound Handshake/Read/Write/Shutdown/RequestClientCertificate).
  Both subclasses have parameterless / socket-only constructors; the caller
  binds a TlsContext via SetContext.
- GetClientHelloBytes (span) replaced by GetClientHelloLength +
  TryGetClientHelloBytes(Span<byte>, out int).
- SetClientCertificateContext parameter is nullable (client may decline).
Copilot AI review requested due to automatic review settings July 8, 2026 03:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 45 out of 46 changed files in this pull request and generated 6 comments.

Comment on lines +147 to +151
public string? TargetHostName
{
get => _options.TargetHost;
set => _options.TargetHost = value ?? string.Empty;
}
Comment on lines +248 to +252
if (!_externalValidationPending)
{
throw new InvalidOperationException(
"AcceptWithDefaultValidation can only be called after ProcessHandshake returned NeedsCertificateValidation.");
}
Comment on lines +317 to +321
if (!_externalValidationPending)
{
throw new InvalidOperationException(
"SetRemoteCertificateValidationResult can only be called after ProcessHandshake returned NeedsCertificateValidation.");
}
Comment on lines +86 to +88
// True when the transport reported EOF before NW signalled a clean close_notify;
// any pending or future app receive should surface as IOException(net_io_eof) rather than 0.
private bool _transportEofUnclean;
Comment on lines +341 to +343
<data name="net_ssl_client_hello_bytes_unavailable" xml:space="preserve">
<value>The ClientHello bytes are not available on this session. The property is server-side only, requires the ClientHello to have been received, and requires ClientHello capture to be enabled (System.Net.Security.CaptureClientHello AppContext switch, default true).</value>
</data>
Comment on lines +690 to +710
[System.Diagnostics.CodeAnalysis.ExperimentalAttribute("SYSLIB5007", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")]
public enum TlsOperationStatus
{
Complete = 0,
DestinationTooSmall = 1,
NeedMoreData = 2,
Closed = 3,
CertificateRequested = 4,
NeedsCertificateValidation = 5,
NeedsTlsContext = 6,
}
[System.Diagnostics.CodeAnalysis.ExperimentalAttribute("SYSLIB5007", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")]
public sealed partial class TlsContext : System.IDisposable
{
internal TlsContext() { }
public static System.Net.Security.TlsContext CreateServer(System.Net.Security.SslServerAuthenticationOptions options) { throw null; }
public static System.Net.Security.TlsContext CreateClient(System.Net.Security.SslClientAuthenticationOptions options) { throw null; }
public void Dispose() { }
}
[System.Diagnostics.CodeAnalysis.ExperimentalAttribute("SYSLIB5007", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")]
public abstract partial class TlsSession : System.IDisposable
- Fix SafeSocketHandle leak in Dispose when native fd-binding path is used
- Fix dispatch_queue leak in pal_networkframework.m on listener create failure
- Add ThrowIfContextNotSet() guard to TargetHostName property
- Fix stale ProcessHandshake references in exception messages
- Mark _transportEofUnclean as volatile for cross-thread safety
- Remove unused net_ssl_client_hello_bytes_unavailable resource string
Copilot AI review requested due to automatic review settings July 8, 2026 04:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 45 out of 46 changed files in this pull request and generated 3 comments.

Comment on lines +19 to +29
/// <summary>
/// The destination buffer was too small for the pending output. Call the
/// operation again with a larger buffer, or drain via
/// <see cref="TlsBufferSession.DrainPendingOutput"/>.
/// </summary>
DestinationTooSmall = 1,

/// <summary>
/// The session needs more ciphertext from the peer to make progress.
/// </summary>
NeedMoreData = 2,
Comment on lines +300 to +306
return error switch
{
Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_READ => TlsOperationStatus.NeedMoreData,
Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_WRITE => TlsOperationStatus.DestinationTooSmall,
Interop.Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN => TlsOperationStatus.Closed,
_ => throw new AuthenticationException($"OpenSSL {op} failed: {error}"),
};
Comment thread TlsSession-proposal.md
Comment on lines +18 to +20
- Single `TlsSession` type (no `TlsDetachedSession` / `TlsSocketBoundSession` split).
- Cross-platform API surface. Linux is an implementation fast path, not a separate type.
- Role (client vs. server) bound to `TlsContext` via the options type; no `bool isServer`.
@DeagleGross

Copy link
Copy Markdown
Member

Latest PR seems to be at #130366

@wfurt wfurt closed this Jul 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Net.Security NO-MERGE The PR is not ready for merge yet (see discussion for detailed reasons)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants