|
6 | 6 | using System.Collections.ObjectModel; |
7 | 7 | using System.Diagnostics; |
8 | 8 | using System.Net.Security; |
| 9 | +using System.Net.Sockets; |
9 | 10 | using System.Runtime.CompilerServices; |
10 | 11 | using System.Runtime.InteropServices; |
11 | 12 | using System.Runtime.InteropServices.Marshalling; |
@@ -117,6 +118,15 @@ internal static unsafe ushort[] GetDefaultSignatureAlgorithms() |
117 | 118 | [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetBio")] |
118 | 119 | internal static partial void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio); |
119 | 120 |
|
| 121 | + // The OpenSSL shims below report errors via out params + the OpenSSL error |
| 122 | + // queue (SSL_get_error / ERR_get_error); they do not set errno. SetLastError is |
| 123 | + // omitted so we don't pay the marshaller cost of capturing a value no caller reads. |
| 124 | + [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetFd")] |
| 125 | + internal static partial int SslSetFd(SafeSslHandle ssl, SafeSocketHandle socket); |
| 126 | + |
| 127 | + [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDoHandshake")] |
| 128 | + internal static partial int SslDoHandshake(SafeSslHandle ssl, out SslErrorCode error); |
| 129 | + |
120 | 130 | [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslHandshake", SetLastError = true)] |
121 | 131 | internal static unsafe partial int SslHandshake( |
122 | 132 | SafeSslHandle ssl, |
@@ -166,6 +176,38 @@ internal static unsafe partial int SslDecrypt( |
166 | 176 | [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioNewManagedSpan")] |
167 | 177 | internal static partial SafeBioHandle BioNewManagedSpan(); |
168 | 178 |
|
| 179 | + [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioNewSocketReplay")] |
| 180 | + private static unsafe partial SafeBioHandle BioNewSocketReplay(IntPtr fd, byte* prefix, int prefixLen); |
| 181 | + |
| 182 | + internal static unsafe SafeBioHandle BioNewSocketReplay(SafeSocketHandle socket, ReadOnlySpan<byte> prefix) |
| 183 | + { |
| 184 | + fixed (byte* pPrefix = prefix) |
| 185 | + { |
| 186 | + return BioNewSocketReplay(socket.DangerousGetHandle(), pPrefix, prefix.Length); |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + // Reads directly from the BIO's bound fd into its internal peek buffer until a |
| 191 | + // full TLS record is present. Returns: |
| 192 | + // 1 = have full frame; framePtr / frameLen point into the BIO's buffer. |
| 193 | + // 0 = need more data (fd would block); caller polls SelectRead and retries. |
| 194 | + // -1 = error (EOF, oversized record, or recv failure). |
| 195 | + // |
| 196 | + // The returned pointer is valid until the BIO is destroyed or SocketReplayBioRead |
| 197 | + // starts consuming the buffer (i.e. once SSL_do_handshake runs against this BIO). |
| 198 | + // Callers must span-wrap and parse before creating the SSL* that owns the BIO. |
| 199 | + [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioPeekTlsFrame")] |
| 200 | + internal static unsafe partial int BioPeekTlsFrame(SafeBioHandle bio, out byte* framePtr, out int frameLen); |
| 201 | + |
| 202 | + // Returns the socket-replay BIO's retained peek buffer (bytes captured by |
| 203 | + // BioPeekTlsFrame). Valid until the BIO is destroyed, even after OpenSSL has |
| 204 | + // drained it during handshake. |
| 205 | + // 1 = prefix present; prefixPtr / prefixLen wrap the internal buffer. |
| 206 | + // 0 = BIO has no captured prefix. |
| 207 | + // -1 = error (invalid args). |
| 208 | + [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioGetReplayPrefix")] |
| 209 | + internal static unsafe partial int BioGetReplayPrefix(SafeBioHandle bio, out byte* prefixPtr, out int prefixLen); |
| 210 | + |
169 | 211 | [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioGetWriteResult")] |
170 | 212 | internal static partial void BioGetWriteResult(SafeBioHandle bio, out int writtenToWindow, out int spillLen); |
171 | 213 |
|
@@ -231,6 +273,9 @@ internal static SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl) |
231 | 273 | [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetVerifyPeer")] |
232 | 274 | internal static partial void SslSetVerifyPeer(SafeSslHandle ssl, [MarshalAs(UnmanagedType.Bool)] bool failIfNoPeerCert); |
233 | 275 |
|
| 276 | + [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetRetryVerify")] |
| 277 | + internal static partial int SslSetRetryVerify(SafeSslHandle ssl); |
| 278 | + |
234 | 279 | [LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetData")] |
235 | 280 | internal static partial IntPtr SslGetData(IntPtr ssl); |
236 | 281 |
|
@@ -422,6 +467,7 @@ internal enum SslErrorCode |
422 | 467 | SSL_ERROR_WANT_X509_LOOKUP = 4, |
423 | 468 | SSL_ERROR_SYSCALL = 5, |
424 | 469 | SSL_ERROR_ZERO_RETURN = 6, |
| 470 | + SSL_ERROR_WANT_RETRY_VERIFY = 12, |
425 | 471 |
|
426 | 472 | // NOTE: this SslErrorCode value doesn't exist in OpenSSL, but |
427 | 473 | // we use it to distinguish when a renegotiation is pending. |
@@ -450,6 +496,17 @@ internal sealed class SafeSslHandle : SafeDeleteSslContext |
450 | 496 | // we may rethrow it after returning to managed code. |
451 | 497 | public Exception? CertificateValidationException; |
452 | 498 |
|
| 499 | + // OpenSSL 3.0+ retry-verify state (dormant infrastructure). When CertVerifyCallback |
| 500 | + // eventually opts into SSL_set_retry_verify (currently disabled — upstream OpenSSL |
| 501 | + // does not re-enter the peer-cert verify callback on either client or server SSLs), |
| 502 | + // it will set RetryVerifyAttempted = true and, on re-entry, honor |
| 503 | + // ExternalValidationAccepted (posted by TlsSession.PushExternalValidationVerdict- |
| 504 | + // ToPalIfRetryVerify). Both fields are read but never written today, hence CS0649. |
| 505 | +#pragma warning disable CS0649 |
| 506 | + public bool RetryVerifyAttempted; |
| 507 | + public bool ExternalValidationAccepted; |
| 508 | +#pragma warning restore CS0649 |
| 509 | + |
453 | 510 | public bool IsServer |
454 | 511 | { |
455 | 512 | get { return _isServer; } |
@@ -478,37 +535,85 @@ internal void MarkHandshakeCompleted() |
478 | 535 |
|
479 | 536 | public static SafeSslHandle Create(SafeSslContextHandle context, SslAuthenticationOptions options) |
480 | 537 | { |
481 | | - SafeBioHandle readBio = Interop.Ssl.BioNewManagedSpan(); |
482 | | - SafeBioHandle writeBio = Interop.Ssl.BioNewManagedSpan(); |
| 538 | + SafeSocketHandle? socket = options.SocketHandle; |
| 539 | + bool useFd = socket is not null && !socket.IsInvalid; |
| 540 | + SafeBioHandle? preallocatedReadBio = useFd ? options.PreallocatedReadBio : null; |
| 541 | + byte[]? replayPrefix = useFd ? options.ReplayPrefix : null; |
| 542 | + bool usePreallocatedBio = preallocatedReadBio is not null; |
| 543 | + bool useReplayBio = usePreallocatedBio || (useFd && replayPrefix is not null); |
| 544 | + |
| 545 | + SafeBioHandle? readBio = null; |
| 546 | + SafeBioHandle? writeBio = null; |
| 547 | + if (usePreallocatedBio) |
| 548 | + { |
| 549 | + // Deferred-server flow (native pre-fetch): the caller populated a |
| 550 | + // socket-replay BIO via BioPeekTlsFrame; adopt it as the read BIO |
| 551 | + // and create a peer write BIO for OpenSSL's outbound records. |
| 552 | + // Clear the field so ownership transfer happens exactly once. |
| 553 | + readBio = preallocatedReadBio; |
| 554 | + options.PreallocatedReadBio = null; |
| 555 | + writeBio = Interop.Ssl.BioNewSocketReplay(socket!, ReadOnlySpan<byte>.Empty); |
| 556 | + } |
| 557 | + else if (useReplayBio) |
| 558 | + { |
| 559 | + // Legacy deferred-server flow (managed pre-fetch): install a socket- |
| 560 | + // replay BIO seeded with the peeked ClientHello bytes. |
| 561 | + readBio = Interop.Ssl.BioNewSocketReplay(socket!, replayPrefix); |
| 562 | + writeBio = Interop.Ssl.BioNewSocketReplay(socket!, ReadOnlySpan<byte>.Empty); |
| 563 | + } |
| 564 | + else if (!useFd) |
| 565 | + { |
| 566 | + readBio = Interop.Ssl.BioNewManagedSpan(); |
| 567 | + writeBio = Interop.Ssl.BioNewManagedSpan(); |
| 568 | + } |
| 569 | + |
483 | 570 | SafeSslHandle handle = Interop.Ssl.SslCreate(context); |
484 | | - if (readBio.IsInvalid || writeBio.IsInvalid || handle.IsInvalid) |
| 571 | + if (((readBio is not null) && (readBio.IsInvalid || writeBio!.IsInvalid)) || handle.IsInvalid) |
485 | 572 | { |
486 | | - readBio.Dispose(); |
487 | | - writeBio.Dispose(); |
| 573 | + readBio?.Dispose(); |
| 574 | + writeBio?.Dispose(); |
488 | 575 | handle.Dispose(); // will make IsInvalid==true if it's not already |
489 | 576 | return handle; |
490 | 577 | } |
491 | 578 | handle._isServer = options.IsServer; |
492 | 579 | handle._authOptionsHandle = new WeakGCHandle<SslAuthenticationOptions>(options); |
493 | 580 | Interop.Ssl.SslSetData(handle, WeakGCHandle<SslAuthenticationOptions>.ToIntPtr(handle._authOptionsHandle)); |
494 | 581 |
|
495 | | - // SslSetBio will transfer ownership of the BIO handles to the SSL context |
496 | | - try |
| 582 | + // CertVerifyCallback needs the SafeSslHandle to stash a |
| 583 | + // CertificateValidationException; expose it via the options. |
| 584 | + options.SafeSslHandle = handle; |
| 585 | + |
| 586 | + if (useFd && !useReplayBio) |
497 | 587 | { |
498 | | - readBio.TransferOwnershipToParent(handle); |
499 | | - writeBio.TransferOwnershipToParent(handle); |
500 | | - handle._readBio = readBio; |
501 | | - handle._writeBio = writeBio; |
502 | | - Interop.Ssl.SslSetBio(handle, readBio, writeBio); |
| 588 | + if (Interop.Ssl.SslSetFd(handle, socket!) != 1) |
| 589 | + { |
| 590 | + handle.Dispose(); |
| 591 | + throw Interop.OpenSsl.CreateSslException(SR.net_allocate_ssl_context_failed); |
| 592 | + } |
503 | 593 | } |
504 | | - catch (Exception exc) |
| 594 | + else |
505 | 595 | { |
506 | | - // The only way this should be able to happen without thread aborts is if we hit OOMs while |
507 | | - // manipulating the safe handles, in which case we may leak the bio handles. |
508 | | - Debug.Fail("Unexpected exception while transferring SafeBioHandle ownership to SafeSslHandle", exc.ToString()); |
509 | | - throw; |
| 596 | + // SslSetBio will transfer ownership of the BIO handles to the SSL context |
| 597 | + try |
| 598 | + { |
| 599 | + readBio!.TransferOwnershipToParent(handle); |
| 600 | + writeBio!.TransferOwnershipToParent(handle); |
| 601 | + handle._readBio = readBio; |
| 602 | + handle._writeBio = writeBio; |
| 603 | + Interop.Ssl.SslSetBio(handle, readBio, writeBio); |
| 604 | + } |
| 605 | + catch (Exception exc) |
| 606 | + { |
| 607 | + // The only way this should be able to happen without thread aborts is if we hit OOMs while |
| 608 | + // manipulating the safe handles, in which case we may leak the bio handles. |
| 609 | + Debug.Fail("Unexpected exception while transferring SafeBioHandle ownership to SafeSslHandle", exc.ToString()); |
| 610 | + throw; |
| 611 | + } |
510 | 612 | } |
511 | 613 |
|
| 614 | + // Consumed exactly once: the BIO holds its own copy of the prefix bytes. |
| 615 | + options.ReplayPrefix = null; |
| 616 | + |
512 | 617 | if (options.IsServer) |
513 | 618 | { |
514 | 619 | Interop.Ssl.SslSetAcceptState(handle); |
|
0 commit comments