Skip to content

Accept moving write buffers for socket-bound TLS sessions - #131759

Merged
rzikm merged 2 commits into
dotnet:mainfrom
rzikm:tlssession-buffer-pinning
Aug 4, 2026
Merged

rzikm merged 2 commits into
dotnet:mainfrom
rzikm:tlssession-buffer-pinning

Conversation

@rzikm

@rzikm rzikm commented Aug 3, 2026

Copy link
Copy Markdown
Member

Problem

A socket-bound TlsSocketSession can fail a perfectly valid write retry with:

System.Security.Authentication.AuthenticationException : Authentication failed, see inner exception.
---- Interop+OpenSsl+SslException : Encrypt failed with OpenSSL error - bad write retry.
   at System.Net.Security.TlsSession.MapSslError(SslErrorCode error, String sslErrorTemplate)

In fd-mode, TryFastWrite passes ref MemoryMarshal.GetReference(buffer) — a GC-heap address that is pinned only for the duration of the P/Invoke. When the socket send buffer is full, SSL_write reports WANT_WRITE (surfaced as DestinationTooSmall) and OpenSSL stores that address in wpend_buf. Before the caller retries, the GC can relocate the array, so ssl3_write_bytes sees a different pointer and fails with SSL_R_BAD_WRITE_RETRY.

This is not something the caller can work around: a ReadOnlySpan<byte> cannot be kept pinned across two separate calls, so retrying with the exact same byte[] is already the correct thing to do — and it still fails intermittently, depending on GC timing.

Not reachable through SslStream: its managed-span BIO grows on demand and never reports WANT_WRITE.

Fix

Enable SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER — the mode OpenSSL provides precisely for relocating heaps — on socket-bound SSL objects only (useFd in SafeSslHandle.Create). This skips the address comparison. The wpend_tot > len check still enforces the real contract, and the pending record is flushed from OpenSSL's internal write buffer, so the retry buffer's contents are never re-read. SslStream's BIO path is untouched.

  • pal_ssl.h / pal_ssl.c / entrypoints.c: new CryptoNative_SslSetAcceptMovingWriteBuffer shim.
  • Interop.Ssl.cs: LibraryImport and the call site in SafeSslHandle.Create.

Testing

New TlsSessionTests.SocketBoundSession_WriteRetryWithRelocatedBuffer_Succeeds theory fills the socket send buffer to induce WANT_WRITE, then retries and drives the write to Complete while a client drains. Two cases:

  • a cloned buffer (deterministically different address);
  • the same array after a forced compacting GC — the actual customer scenario.

Verified locally on Linux/x64:

  • Both cases fail with the fix reverted (bad write retry in each).
  • Both pass with the fix.
  • TlsSessionTests: 47/47 passed.
  • Full System.Net.Security.Tests: 5034 passed, 0 failed, 8 skipped.

Note

This pull request description was generated with the assistance of GitHub Copilot.

In fd-mode, TlsSession hands SSL_write a span over GC-tracked memory. When
the socket send buffer is full, SSL_write reports WANT_WRITE (surfaced as
DestinationTooSmall) and OpenSSL remembers the address of the plaintext
buffer as the pending write. A managed caller retrying the write has no way
to keep that memory pinned across two separate calls, so the GC may have
relocated it; OpenSSL then rejects the retry with SSL_R_BAD_WRITE_RETRY,
which the session surfaces as an AuthenticationException.

Enable SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER on socket-bound SSL objects so
the address comparison is skipped. The length check still enforces the real
contract, and the pending record is flushed from OpenSSL's internal write
buffer, so the retry buffer's contents are not re-read. SslStream's BIO path
is unaffected: its managed-span BIO grows on demand and never reports
WANT_WRITE.

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings August 3, 2026 17:21
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 4 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@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 updates the OpenSSL-backed socket-bound TLS session path to tolerate write retries where the managed plaintext buffer’s address changes between SSL_write attempts (GC relocation), by enabling OpenSSL’s SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER for fd-backed SSL objects. It also adds a regression test to validate that a DestinationTooSmall/WANT_WRITE retry succeeds even when the retry buffer is at a different address.

Changes:

  • Add a new native CryptoNative shim to enable SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER on an SSL*.
  • Call the new shim during SafeSslHandle.Create when creating socket-bound (useFd) sessions.
  • Add a functional regression test that induces WANT_WRITE and verifies retry success with both a cloned buffer and a GC-relocated buffer.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/native/libs/System.Security.Cryptography.Native/pal_ssl.h Declares the new exported shim API for enabling the OpenSSL mode.
src/native/libs/System.Security.Cryptography.Native/pal_ssl.c Implements the shim by calling SSL_set_mode(..., SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER).
src/native/libs/System.Security.Cryptography.Native/entrypoints.c Exposes the new shim via the CryptoNative entrypoint table.
src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs Adds a LibraryImport and invokes it for useFd SafeSslHandle creation.
src/libraries/System.Net.Security/tests/FunctionalTests/TlsSessionTests.cs Adds a regression test covering retry semantics with a moved write buffer.

@wfurt wfurt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Copilot AI review requested due to automatic review settings August 4, 2026 08:45
@rzikm
rzikm enabled auto-merge (squash) August 4, 2026 08:47

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 5 out of 5 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/libraries/System.Net.Security/tests/FunctionalTests/TlsSessionTests.cs:3158

  • drain is awaited without a timeout. If SslStream.ReadAsync(..., drainCts.Token) fails to observe cancellation promptly (or hangs for any reason), this test can hang the entire run. Most other waits in this file are bounded via WaitAsync(TimeSpan...).
            finally
            {
                drainCts.Cancel();
                await drain;
            }

@rzikm
rzikm merged commit 2dd5330 into dotnet:main Aug 4, 2026
104 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-rc1 milestone Aug 5, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 4, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants