| | | 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.Collections.Generic; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | using System.Diagnostics.CodeAnalysis; |
| | | 8 | | using System.IO; |
| | | 9 | | using System.Net.Sockets; |
| | | 10 | | using System.Security.Authentication; |
| | | 11 | | using System.Security.Authentication.ExtendedProtection; |
| | | 12 | | using System.Security.Cryptography.X509Certificates; |
| | | 13 | | // macOS PAL has two SafeDelete* derivatives (SecureTransport + Network.framework) |
| | | 14 | | // and surfaces the base type in ref parameters. Use the base type for the security-context |
| | | 15 | | // field on macOS so it lines up with the PAL ref signatures; other platforms keep the |
| | | 16 | | // derived SafeDeleteSslContext. |
| | | 17 | | #if TARGET_APPLE |
| | | 18 | | using TlsSecurityContext = System.Net.Security.SafeDeleteContext; |
| | | 19 | | #else |
| | | 20 | | using TlsSecurityContext = System.Net.Security.SafeDeleteSslContext; |
| | | 21 | | #endif |
| | | 22 | | |
| | | 23 | | namespace System.Net.Security |
| | | 24 | | { |
| | | 25 | | /// <summary> |
| | | 26 | | /// Non-blocking TLS state machine that drives handshake and record |
| | | 27 | | /// processing from caller-supplied byte spans. |
| | | 28 | | /// </summary> |
| | | 29 | | /// <remarks> |
| | | 30 | | /// <para> |
| | | 31 | | /// Support is provided by the underlying platform, such as SChannel on Windows |
| | | 32 | | /// and OpenSSL on Linux. |
| | | 33 | | /// </para> |
| | | 34 | | /// <para> |
| | | 35 | | /// The session never performs any I/O. The caller drives ciphertext in/out |
| | | 36 | | /// via byte spans. Any ciphertext the TLS layer needs to send (handshake |
| | | 37 | | /// records, alerts, encrypted application data) is staged in an internal |
| | | 38 | | /// pending-output buffer and drained via <see cref="TlsBufferSession.DrainPendingOutput"/>. |
| | | 39 | | /// </para> |
| | | 40 | | /// <para> |
| | | 41 | | /// Contract: any operation may return <see cref="TlsOperationStatus.DestinationTooSmall"/> |
| | | 42 | | /// to indicate the caller must drain pending output before further progress |
| | | 43 | | /// is possible. The session does not consume new input while pending output |
| | | 44 | | /// is non-empty. |
| | | 45 | | /// </para> |
| | | 46 | | /// </remarks> |
| | | 47 | | [Experimental(Experimentals.LowLevelTlsDiagId, UrlFormat = Experimentals.SharedUrlFormat)] |
| | | 48 | | public abstract partial class TlsSession : IDisposable |
| | | 49 | | { |
| | | 50 | | // Matches StreamSizes.Default on Unix; conservative upper bound for a |
| | | 51 | | // single TLS record's plaintext payload. |
| | | 52 | | internal const int MaxRecordPlaintext = 16354; |
| | | 53 | | |
| | | 54 | | // Nullable until SetContext is called. All operations that depend on a |
| | | 55 | | // configured context validate this at entry. |
| | | 56 | | private TlsContext? _context; |
| | 0 | 57 | | private SslAuthenticationOptions _options = null!; |
| | | 58 | | private bool _ownsOptions; |
| | | 59 | | private bool _hasServerOptions; |
| | | 60 | | private TlsSecurityContext? _securityContext; |
| | | 61 | | |
| | 0 | 62 | | private ArrayBuffer _pendingBuffer = new ArrayBuffer(initialSize: 0, usePool: true); |
| | | 63 | | |
| | | 64 | | // Server-side only: SNI-resolved host name captured from the client's |
| | | 65 | | // ClientHello. Kept session-local so parallel sessions built from a |
| | | 66 | | // deferred TlsContext (SNI-dispatching bootstrap) cannot race on the |
| | | 67 | | // shared _options bag. Empty until the first ClientHello has parsed. |
| | | 68 | | // On client-side sessions the target host lives on _options.TargetHost |
| | | 69 | | // (immutable after SetContext, set by the caller via |
| | | 70 | | // SslClientAuthenticationOptions). |
| | 0 | 71 | | private string _sessionTargetHost = string.Empty; |
| | | 72 | | |
| | | 73 | | private byte[]? _decryptScratch; |
| | | 74 | | |
| | | 75 | | private bool _isHandshakeComplete; |
| | | 76 | | private bool _suppressInternalCertificateValidation; |
| | | 77 | | private bool _externalValidationPending; |
| | | 78 | | private bool _externalValidationResolved; |
| | | 79 | | // Server-side post-handshake client authentication. Set by |
| | | 80 | | // RequestClientCertificate once the renegotiation / TLS 1.3 CertificateRequest |
| | | 81 | | // has been staged; it re-arms the handshake state machine so the caller drives |
| | | 82 | | // the second handshake to completion through Handshake(). Reset once the staged |
| | | 83 | | // request bytes have been fully drained to the caller (so a DestinationTooSmall |
| | | 84 | | // drain-continuation re-enters RequestClientCertificate without re-initiating). |
| | | 85 | | #if !TARGET_APPLE |
| | | 86 | | private bool _postHandshakeAuthActive; |
| | | 87 | | #endif |
| | | 88 | | // Set by SetClientCertificateContext after a WantCredentials suspension; consumed by |
| | | 89 | | // the next ProcessHandshake to allow an empty-input re-entry past the frame guard. |
| | | 90 | | private bool _resumeAfterCredentials; |
| | | 91 | | // Set by SetRemoteCertificateValidationResult when the PAL paused mid-handshake |
| | | 92 | | // pending external certificate validation (SecureTransport on macOS). Consumed by |
| | | 93 | | // the next ProcessHandshake to allow an empty-input re-entry past the frame guard |
| | | 94 | | // so the PAL can produce the next handshake flight (or a fatal alert on reject). |
| | | 95 | | private bool _resumeAfterCertValidation; |
| | | 96 | | // Intermediate certs the peer sent (chain elements minus the leaf). The platform-built |
| | | 97 | | // X509Chain itself is never surfaced to TlsSession callers; AcceptWithDefaultValidation |
| | | 98 | | // rebuilds a fresh chain from this collection at validation time. |
| | | 99 | | private X509Certificate2Collection? _externalRemoteCertificates; |
| | | 100 | | private X509Certificate2? _externalPendingCert; |
| | | 101 | | private Exception? _externalValidationFault; |
| | | 102 | | // Set when the caller explicitly rejected the peer certificate via |
| | | 103 | | // SetRemoteCertificateValidationResult / AcceptWithDefaultValidation. Once set, |
| | | 104 | | // GetRemoteCertificate must not surface the refused cert even though the underlying |
| | | 105 | | // PAL security context may still hold it (SChannel keeps the peer cert on the context). |
| | | 106 | | private bool _remoteCertificateRejected; |
| | | 107 | | private SslClientHelloInfo? _clientHelloInfo; |
| | | 108 | | private byte[]? _clientHelloBytesBuffered; |
| | | 109 | | // Session-local credentials handle. Non-null once SetClientCertificateContext |
| | | 110 | | // has been called; from that point on, this session's PAL calls route through |
| | | 111 | | // ActiveCredentialsRef() and never touch the shared TlsContext.CredentialsHandle. |
| | | 112 | | // Disposed when the session is disposed. |
| | | 113 | | private SafeFreeCredentials? _sessionCredentialsHandle; |
| | | 114 | | // Session-local view of the CertificateContext. Initialized from _options at |
| | | 115 | | // SetContext time and every mutation (SetClientCertificateContext, the |
| | | 116 | | // server-side selector path) routes through SessionCertificateContext so parallel |
| | | 117 | | // sessions built from the same TlsContext template never race on the shared cert |
| | | 118 | | // slot. _ownsSessionCertificateContext tracks whether the session itself built |
| | | 119 | | // this context (only true when constructed via SslStreamCertificateContext.Create |
| | | 120 | | // in the server-cert-selector path); Dispose releases it iff owned. The PAL |
| | | 121 | | // signature still reads _options.CertificateContext, so the setter mirrors the |
| | | 122 | | // new value onto the per-session cloned options bag; that mirror is the single |
| | | 123 | | // point that goes away when the PAL is later reshaped to consume the session |
| | | 124 | | // directly. |
| | | 125 | | private SslStreamCertificateContext? _sessionCertificateContext; |
| | | 126 | | private bool _ownsSessionCertificateContext; |
| | | 127 | | private bool _disposed; |
| | | 128 | | private SslConnectionInfo _connectionInfo; |
| | | 129 | | private X509Certificate2? _remoteCertificate; |
| | | 130 | | private int _headerSize; |
| | | 131 | | private int _trailerSize; |
| | 0 | 132 | | private int _maxDataSize = MaxRecordPlaintext; |
| | | 133 | | |
| | | 134 | | // Socket-bound mode (optional). When set, the session performs its own |
| | | 135 | | // non-blocking I/O via Handshake/Read/Write. The session takes ownership |
| | | 136 | | // of the supplied socket handle and disposes it with the session. |
| | | 137 | | private SafeSocketHandle? _socketHandle; |
| | | 138 | | private Socket? _socket; |
| | 0 | 139 | | private ArrayBuffer _socketInBuffer = new ArrayBuffer(initialSize: 0, usePool: true); |
| | | 140 | | |
| | 0 | 141 | | private protected TlsSession() |
| | 0 | 142 | | { |
| | 0 | 143 | | } |
| | | 144 | | |
| | | 145 | | // Called from TlsSocketSession.OnContextInitialized (right after the base |
| | | 146 | | // InitializeFromContext runs) to bind a socket handle for the socket-bound I/O |
| | | 147 | | // path. Must be called exactly once per session, and only before any |
| | | 148 | | // Handshake / Read / Write / Shutdown call has touched the PAL. The socket is |
| | | 149 | | // taken to ownership and disposed with the session. Platforms with a native |
| | | 150 | | // fd-binding fast path (OpenSSL) take the socket directly; otherwise the |
| | | 151 | | // socket is wrapped in a managed Socket for the buffered I/O path. |
| | | 152 | | private protected void AttachSocket(SafeSocketHandle socket) |
| | 0 | 153 | | { |
| | 0 | 154 | | Debug.Assert(socket != null); |
| | 0 | 155 | | Debug.Assert(!_disposed, "AttachSocket called on a disposed session"); |
| | 0 | 156 | | Debug.Assert(_socketHandle is null, "AttachSocket called twice on the same session"); |
| | 0 | 157 | | Debug.Assert(_socket is null, "AttachSocket called after the managed Socket wrapper was already created"); |
| | 0 | 158 | | Debug.Assert(_securityContext is null, "AttachSocket called after the PAL security context was already alloc |
| | 0 | 159 | | _socketHandle = socket; |
| | | 160 | | |
| | 0 | 161 | | bool nativeBindingEnabled = false; |
| | | 162 | | EnableNativeSocketBinding(socket, ref nativeBindingEnabled); |
| | 0 | 163 | | if (!nativeBindingEnabled) |
| | 0 | 164 | | { |
| | 0 | 165 | | _socket = new Socket(socket); |
| | 0 | 166 | | } |
| | 0 | 167 | | } |
| | | 168 | | |
| | | 169 | | internal SafeSocketHandle? SocketHandle => _socketHandle; |
| | | 170 | | |
| | 0 | 171 | | private SslStreamCertificateContext? SessionCertificateContext => _sessionCertificateContext; |
| | | 172 | | |
| | | 173 | | private void SetSessionCertificateContext(SslStreamCertificateContext? context, bool takeOwnership) |
| | 0 | 174 | | { |
| | 0 | 175 | | if (_ownsSessionCertificateContext && _sessionCertificateContext is not null && !ReferenceEquals(_sessionCer |
| | 0 | 176 | | { |
| | 0 | 177 | | _sessionCertificateContext.ReleaseResources(); |
| | 0 | 178 | | } |
| | | 179 | | |
| | 0 | 180 | | _sessionCertificateContext = context; |
| | 0 | 181 | | _ownsSessionCertificateContext = takeOwnership && context is not null; |
| | | 182 | | |
| | | 183 | | // Mirror onto the per-session cloned options bag so the PAL (which reads |
| | | 184 | | // _options.CertificateContext directly) sees the effective value. Also flip |
| | | 185 | | // the bag's own ownership bit off — session now owns the disposal decision. |
| | 0 | 186 | | _options.CertificateContext = context; |
| | 0 | 187 | | _options.OwnsCertificateContext = false; |
| | 0 | 188 | | } |
| | | 189 | | |
| | | 190 | | private void InitializeFromContext(TlsContext context) |
| | 0 | 191 | | { |
| | 0 | 192 | | Debug.Assert(_context is null); |
| | 0 | 193 | | Debug.Assert(context is not null); |
| | 0 | 194 | | _context = context; |
| | 0 | 195 | | _ownsOptions = !context.ShareOptions; |
| | 0 | 196 | | _options = context.CreateSessionOptions(); |
| | 0 | 197 | | _hasServerOptions = context.TemplateHasServerOptions; |
| | | 198 | | |
| | | 199 | | // Transfer CertificateContext ownership from the per-session options clone |
| | | 200 | | // to the session so subsequent mutations (SetClientCertificateContext, |
| | | 201 | | // server-selector build) live entirely on TlsSession's own fields. The bag |
| | | 202 | | // itself never owns after this point; TlsSession.Dispose is the sole releaser. |
| | 0 | 203 | | _sessionCertificateContext = _options.CertificateContext; |
| | 0 | 204 | | _ownsSessionCertificateContext = _options.OwnsCertificateContext; |
| | 0 | 205 | | _options.OwnsCertificateContext = false; |
| | | 206 | | |
| | 0 | 207 | | OnContextInitialized(); |
| | 0 | 208 | | } |
| | | 209 | | |
| | | 210 | | internal virtual void OnContextInitialized() |
| | 0 | 211 | | { |
| | 0 | 212 | | } |
| | | 213 | | |
| | | 214 | | |
| | | 215 | | // ── State ───────────────────────────────────────────────────────── |
| | | 216 | | |
| | 0 | 217 | | public bool IsHandshakeComplete => _isHandshakeComplete; |
| | | 218 | | |
| | 0 | 219 | | public bool HasPendingOutput => _pendingBuffer.ActiveLength > 0; |
| | | 220 | | |
| | | 221 | | /// <summary> |
| | | 222 | | /// Target host name for this session. On the client this is the value the |
| | | 223 | | /// caller supplied via <see cref="SslClientAuthenticationOptions.TargetHost"/> |
| | | 224 | | /// (used for SNI and hostname validation). On the server this is the SNI value |
| | | 225 | | /// parsed from the peer's ClientHello, or <see langword="null"/> if no |
| | | 226 | | /// ClientHello has been processed yet or the ClientHello carried no SNI |
| | | 227 | | /// extension. Setting the value on either side overrides the current value; |
| | | 228 | | /// setting to <see langword="null"/> clears it. |
| | | 229 | | /// </summary> |
| | | 230 | | public string? TargetHostName |
| | | 231 | | { |
| | | 232 | | get |
| | 0 | 233 | | { |
| | 0 | 234 | | ThrowIfContextNotSet(); |
| | 0 | 235 | | if (_context!.IsServer) |
| | 0 | 236 | | { |
| | 0 | 237 | | return string.IsNullOrEmpty(_sessionTargetHost) ? null : _sessionTargetHost; |
| | | 238 | | } |
| | 0 | 239 | | return string.IsNullOrEmpty(_options.TargetHost) ? null : _options.TargetHost; |
| | 0 | 240 | | } |
| | | 241 | | set |
| | 0 | 242 | | { |
| | 0 | 243 | | ThrowIfContextNotSet(); |
| | 0 | 244 | | if (_context!.IsServer) |
| | 0 | 245 | | { |
| | 0 | 246 | | _sessionTargetHost = value ?? string.Empty; |
| | 0 | 247 | | } |
| | | 248 | | else |
| | 0 | 249 | | { |
| | 0 | 250 | | _options.TargetHost = value ?? string.Empty; |
| | 0 | 251 | | } |
| | 0 | 252 | | } |
| | | 253 | | } |
| | | 254 | | |
| | | 255 | | public SslProtocols NegotiatedProtocol |
| | | 256 | | { |
| | | 257 | | get |
| | 0 | 258 | | { |
| | 0 | 259 | | if (!_isHandshakeComplete || _connectionInfo.Protocol == 0) |
| | 0 | 260 | | { |
| | 0 | 261 | | return SslProtocols.None; |
| | | 262 | | } |
| | | 263 | | |
| | | 264 | | // On Windows (SChannel), the reported protocol value carries |
| | | 265 | | // client/server direction bits (SP_PROT_TLS1_2_CLIENT == 0x800, |
| | | 266 | | // SP_PROT_TLS1_2_SERVER == 0x400, etc.). Canonicalize to the |
| | | 267 | | // managed SslProtocols enum values, matching SslStream. |
| | 0 | 268 | | SslProtocols proto = (SslProtocols)_connectionInfo.Protocol; |
| | 0 | 269 | | SslProtocols ret = SslProtocols.None; |
| | | 270 | | #pragma warning disable 0618 |
| | 0 | 271 | | if ((proto & SslProtocols.Ssl2) != 0) ret |= SslProtocols.Ssl2; |
| | 0 | 272 | | if ((proto & SslProtocols.Ssl3) != 0) ret |= SslProtocols.Ssl3; |
| | | 273 | | #pragma warning restore |
| | | 274 | | #pragma warning disable SYSLIB0039 |
| | 0 | 275 | | if ((proto & SslProtocols.Tls) != 0) ret |= SslProtocols.Tls; |
| | 0 | 276 | | if ((proto & SslProtocols.Tls11) != 0) ret |= SslProtocols.Tls11; |
| | | 277 | | #pragma warning restore SYSLIB0039 |
| | 0 | 278 | | if ((proto & SslProtocols.Tls12) != 0) ret |= SslProtocols.Tls12; |
| | 0 | 279 | | if ((proto & SslProtocols.Tls13) != 0) ret |= SslProtocols.Tls13; |
| | 0 | 280 | | return ret; |
| | 0 | 281 | | } |
| | | 282 | | } |
| | | 283 | | |
| | | 284 | | [System.CLSCompliant(false)] |
| | | 285 | | public TlsCipherSuite NegotiatedCipherSuite => |
| | 0 | 286 | | _isHandshakeComplete ? (TlsCipherSuite)_connectionInfo.TlsCipherSuite : default; |
| | | 287 | | |
| | | 288 | | public SslApplicationProtocol NegotiatedApplicationProtocol |
| | | 289 | | { |
| | | 290 | | get |
| | 0 | 291 | | { |
| | 0 | 292 | | if (!_isHandshakeComplete || _connectionInfo.ApplicationProtocol == null) |
| | 0 | 293 | | { |
| | 0 | 294 | | return default; |
| | | 295 | | } |
| | 0 | 296 | | return new SslApplicationProtocol(_connectionInfo.ApplicationProtocol); |
| | 0 | 297 | | } |
| | | 298 | | } |
| | | 299 | | |
| | | 300 | | public X509Certificate2? GetRemoteCertificate() |
| | 0 | 301 | | { |
| | 0 | 302 | | if (_remoteCertificate is not null) |
| | 0 | 303 | | { |
| | 0 | 304 | | return _remoteCertificate; |
| | | 305 | | } |
| | | 306 | | |
| | 0 | 307 | | if (_externalPendingCert is not null) |
| | 0 | 308 | | { |
| | 0 | 309 | | return _externalPendingCert; |
| | | 310 | | } |
| | | 311 | | |
| | | 312 | | // The caller rejected the peer certificate; do not fall back to the PAL, which would |
| | | 313 | | // re-surface the refused cert still held on the underlying security context (SChannel). |
| | 0 | 314 | | if (_remoteCertificateRejected) |
| | 0 | 315 | | { |
| | 0 | 316 | | return null; |
| | | 317 | | } |
| | | 318 | | |
| | 0 | 319 | | if (_securityContext == null || _securityContext.IsInvalid) |
| | 0 | 320 | | { |
| | 0 | 321 | | return null; |
| | | 322 | | } |
| | 0 | 323 | | return CertificateValidationPal.GetRemoteCertificate(_securityContext); |
| | 0 | 324 | | } |
| | | 325 | | |
| | | 326 | | /// <summary> |
| | | 327 | | /// Returns the intermediate certificates the peer sent alongside its leaf certificate |
| | | 328 | | /// (the leaf itself is available via <see cref="GetRemoteCertificate"/>), or <c>null</c> |
| | | 329 | | /// if no intermediates were received. Only meaningful while the session is awaiting an |
| | | 330 | | /// external validation result (after <see cref="TlsBufferSession.Handshake"/> returned |
| | | 331 | | /// <see cref="TlsOperationStatus.NeedsCertificateValidation"/>). The certificates are |
| | | 332 | | /// owned by the session and disposed when the session is disposed or when the validation |
| | | 333 | | /// result is recorded; callers that need to retain them must clone the instances. |
| | | 334 | | /// </summary> |
| | | 335 | | public X509Certificate2Collection? GetRemoteCertificates() |
| | 0 | 336 | | { |
| | 0 | 337 | | ThrowIfDisposed(); |
| | 0 | 338 | | return _externalRemoteCertificates; |
| | 0 | 339 | | } |
| | | 340 | | |
| | | 341 | | /// <summary> |
| | | 342 | | /// Runs the same validation <see cref="SslStream"/> performs (default chain |
| | | 343 | | /// build plus any user-supplied <see cref="SslClientAuthenticationOptions.RemoteCertificateValidationCallback"/ |
| | | 344 | | /// on the underlying options), records the result on the session, and returns |
| | | 345 | | /// the effective <see cref="SslPolicyErrors"/>. Intended for callers that want |
| | | 346 | | /// <see cref="SslStream"/>-compatible semantics without writing their own |
| | | 347 | | /// validation logic. |
| | | 348 | | /// </summary> |
| | | 349 | | /// <remarks> |
| | | 350 | | /// Must be called only after <see cref="TlsBufferSession.Handshake"/> returned |
| | | 351 | | /// <see cref="TlsOperationStatus.NeedsCertificateValidation"/> and before |
| | | 352 | | /// <see cref="SetRemoteCertificateValidationResult"/> is called. |
| | | 353 | | /// </remarks> |
| | | 354 | | public SslPolicyErrors AcceptWithDefaultValidation() |
| | 0 | 355 | | { |
| | 0 | 356 | | ThrowIfDisposed(); |
| | 0 | 357 | | if (!_externalValidationPending) |
| | 0 | 358 | | { |
| | 0 | 359 | | throw new InvalidOperationException( |
| | 0 | 360 | | SR.Format(SR.net_tlssession_validation_not_pending, nameof(AcceptWithDefaultValidation))); |
| | | 361 | | } |
| | | 362 | | |
| | | 363 | | // Build a fresh X509Chain locally. VerifyRemoteCertificateCore applies the configured |
| | | 364 | | // chain policy before adding the peer-sent intermediates captured by this session. |
| | 0 | 365 | | using X509Chain chain = new X509Chain(); |
| | | 366 | | |
| | 0 | 367 | | ProtocolToken alertToken = default; |
| | 0 | 368 | | SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; |
| | | 369 | | bool ok; |
| | | 370 | | try |
| | 0 | 371 | | { |
| | | 372 | | // Pass _externalPendingCert as the candidate cert and an empty _remoteCertificate slot. |
| | | 373 | | // VerifyRemoteCertificateCore assigns the slot to the candidate on success; the renegotiation |
| | | 374 | | // shortcut at the top of that method would otherwise dispose our cert if the slot were already |
| | | 375 | | // populated with the same instance. |
| | 0 | 376 | | ok = SslStream.VerifyRemoteCertificateCore( |
| | 0 | 377 | | this, |
| | 0 | 378 | | // The external certificate is being (re)validated after the handshake, so the |
| | 0 | 379 | | // resumption shortcut in VerifyRemoteCertificateCore must not apply here. |
| | 0 | 380 | | isInitialHandshake: false, |
| | 0 | 381 | | _options, |
| | 0 | 382 | | _securityContext, |
| | 0 | 383 | | ref _remoteCertificate, |
| | 0 | 384 | | ref _connectionInfo, |
| | 0 | 385 | | _externalPendingCert, |
| | 0 | 386 | | chain, |
| | 0 | 387 | | trust: null, |
| | 0 | 388 | | ref alertToken, |
| | 0 | 389 | | ref sslPolicyErrors, |
| | 0 | 390 | | out _, |
| | 0 | 391 | | out _, |
| | 0 | 392 | | _externalRemoteCertificates, |
| | 0 | 393 | | cloneCertificateChainPolicy: true); |
| | 0 | 394 | | } |
| | | 395 | | finally |
| | 0 | 396 | | { |
| | | 397 | | // Dispose the certificates that chain.Build() populated into ChainElements so |
| | | 398 | | // they don't linger until GC. Mirrors SslStream.VerifyRemoteCertificate's cleanup |
| | | 399 | | // when no user callback is provided. ExtraStore entries were supplied by the caller |
| | | 400 | | // in _externalRemoteCertificates and are intentionally left alone. |
| | 0 | 401 | | int elementsCount = chain.ChainElements.Count; |
| | 0 | 402 | | for (int i = 0; i < elementsCount; i++) |
| | 0 | 403 | | { |
| | 0 | 404 | | chain.ChainElements[i].Certificate.Dispose(); |
| | 0 | 405 | | } |
| | 0 | 406 | | } |
| | | 407 | | |
| | | 408 | | // A user RemoteCertificateValidationCallback can reject an otherwise-clean chain |
| | | 409 | | // by returning false with sslPolicyErrors == None. Synthesize a non-None failure |
| | | 410 | | // so SetRemoteCertificateValidationResult takes the reject branch instead of accepting. |
| | 0 | 411 | | if (!ok && sslPolicyErrors == SslPolicyErrors.None) |
| | 0 | 412 | | { |
| | 0 | 413 | | sslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors; |
| | 0 | 414 | | } |
| | | 415 | | |
| | | 416 | | // On success VerifyRemoteCertificateCore set _remoteCertificate = _externalPendingCert, so |
| | | 417 | | // SetRemoteCertificateValidationResult below leaves it alone. On failure we must dispose the |
| | | 418 | | // pending cert ourselves because no one adopted it. |
| | 0 | 419 | | SetRemoteCertificateValidationResult(ok ? SslPolicyErrors.None : sslPolicyErrors); |
| | 0 | 420 | | return sslPolicyErrors; |
| | 0 | 421 | | } |
| | | 422 | | |
| | | 423 | | /// <summary> |
| | | 424 | | /// Records the caller's external certificate-validation result. |
| | | 425 | | /// <see cref="SslPolicyErrors.None"/> means accept; any other value causes |
| | | 426 | | /// subsequent calls to <see cref="TlsBufferSession.Handshake"/>, <see cref="TlsBufferSession.Write"/>, |
| | | 427 | | /// and <see cref="TlsBufferSession.Read"/> to throw <see cref="AuthenticationException"/>. |
| | | 428 | | /// Must be called exactly once between |
| | | 429 | | /// <see cref="TlsOperationStatus.NeedsCertificateValidation"/> and the next |
| | | 430 | | /// session operation. |
| | | 431 | | /// </summary> |
| | | 432 | | public void SetRemoteCertificateValidationResult(SslPolicyErrors errors) |
| | 0 | 433 | | { |
| | 0 | 434 | | ThrowIfDisposed(); |
| | 0 | 435 | | if (!_externalValidationPending) |
| | 0 | 436 | | { |
| | 0 | 437 | | throw new InvalidOperationException( |
| | 0 | 438 | | SR.Format(SR.net_tlssession_validation_not_pending, nameof(SetRemoteCertificateValidationResult))); |
| | | 439 | | } |
| | | 440 | | |
| | 0 | 441 | | _externalValidationPending = false; |
| | 0 | 442 | | _externalValidationResolved = true; |
| | | 443 | | |
| | | 444 | | // If the PAL paused mid-handshake pending external validation (SecureTransport |
| | | 445 | | // on macOS returns errSSL{Server,Client}AuthCompleted before any handshake |
| | | 446 | | // response bytes are produced), the next ProcessHandshake call must be allowed |
| | | 447 | | // to re-enter the PAL with an empty input to drive the handshake forward |
| | | 448 | | // (produce ClientKeyExchange/Finished on accept, or a fatal alert on reject). |
| | | 449 | | // On OpenSSL and SChannel the suspension only fires after _isHandshakeComplete |
| | | 450 | | // is already true, so this resume flag is a no-op for those PALs. |
| | 0 | 451 | | if (!_isHandshakeComplete) |
| | 0 | 452 | | { |
| | 0 | 453 | | _resumeAfterCertValidation = true; |
| | 0 | 454 | | } |
| | | 455 | | |
| | | 456 | | #if !TARGET_WINDOWS && !SYSNETSECURITY_NO_OPENSSL |
| | | 457 | | // OpenSSL 3.0+ retry-verify path: the handshake paused inside the CertVerifyCallback. |
| | | 458 | | // Push the verdict to the SafeSslHandle so the next SSL_do_handshake call (driven by |
| | | 459 | | // the caller's next ProcessHandshake) re-invokes the callback and either accepts the |
| | | 460 | | // peer cert (Finished is emitted) or rejects it (a fatal alert is emitted). |
| | | 461 | | PushExternalValidationVerdictToPalIfRetryVerify(errors); |
| | | 462 | | #endif |
| | | 463 | | |
| | 0 | 464 | | if (errors == SslPolicyErrors.None) |
| | 0 | 465 | | { |
| | | 466 | | // Caller accepted. Promote the pending cert to the canonical remote-cert slot |
| | | 467 | | // (unless AcceptWithDefaultValidation already did so). |
| | 0 | 468 | | if (_remoteCertificate is null) |
| | 0 | 469 | | { |
| | 0 | 470 | | _remoteCertificate = _externalPendingCert; |
| | 0 | 471 | | _externalPendingCert = null; |
| | 0 | 472 | | } |
| | | 473 | | else |
| | 0 | 474 | | { |
| | | 475 | | // VerifyRemoteCertificateCore adopted the cert into _remoteCertificate. Drop our copy. |
| | 0 | 476 | | _externalPendingCert = null; |
| | 0 | 477 | | } |
| | 0 | 478 | | } |
| | | 479 | | else |
| | 0 | 480 | | { |
| | | 481 | | // The caller refused the peer certificate. Record the rejection so |
| | | 482 | | // GetRemoteCertificate does not later re-surface it from the PAL security context. |
| | 0 | 483 | | _remoteCertificateRejected = true; |
| | | 484 | | |
| | | 485 | | // Post-hoc rejection (handshake already wire-complete on OpenSSL 1.1.x or Schannel): |
| | | 486 | | // surface the fault immediately so subsequent Encrypt/Decrypt throw. For the |
| | | 487 | | // retry-verify path the handshake is still incomplete and the fault is set when |
| | | 488 | | // ProcessHandshake drives SSL_do_handshake to failure (so any pending alert bytes |
| | | 489 | | // are drained to the caller first). |
| | 0 | 490 | | if (_isHandshakeComplete) |
| | 0 | 491 | | { |
| | 0 | 492 | | _externalValidationFault = new AuthenticationException(SR.Format(SR.net_ssl_io_cert_validation, erro |
| | 0 | 493 | | } |
| | 0 | 494 | | else if (_resumeAfterCertValidation) |
| | 0 | 495 | | { |
| | | 496 | | // Mid-handshake rejection. On OpenSSL 1.1.x / SecureTransport (macOS) |
| | | 497 | | // the peer-verify callback took the accept-and-defer path, so the |
| | | 498 | | // handshake will still complete on the wire; the caller's Write / Read |
| | | 499 | | // must throw AuthenticationException afterwards. Set the fault now, but |
| | | 500 | | // do NOT throw it from HandshakeBufferedCore -- let the PAL drive the |
| | | 501 | | // handshake to completion silently so the peer doesn't hang waiting |
| | | 502 | | // for our Finished. Write / Read guard on ThrowIfPendingExternalValidation |
| | | 503 | | // which checks _externalValidationFault. On OpenSSL 3.0+ retry-verify the |
| | | 504 | | // fault will instead be set by the natural token-failed branch when |
| | | 505 | | // SSL_do_handshake emits the fatal alert. |
| | 0 | 506 | | _externalValidationFault = new AuthenticationException(SR.Format(SR.net_ssl_io_cert_validation, erro |
| | 0 | 507 | | } |
| | | 508 | | |
| | | 509 | | // VerifyRemoteCertificateCore assigns _remoteCertificate to the candidate before it |
| | | 510 | | // knows whether the chain validates, so on the reject path the rejected leaf is sitting |
| | | 511 | | // in the canonical slot. Drop it so GetRemoteCertificate cannot surface a cert the caller |
| | | 512 | | // explicitly refused. Either _remoteCertificate or _externalPendingCert owns it, not both. |
| | 0 | 513 | | if (_remoteCertificate is not null && ReferenceEquals(_remoteCertificate, _externalPendingCert)) |
| | 0 | 514 | | { |
| | 0 | 515 | | _remoteCertificate = null; |
| | 0 | 516 | | } |
| | | 517 | | else |
| | 0 | 518 | | { |
| | 0 | 519 | | _remoteCertificate?.Dispose(); |
| | 0 | 520 | | _remoteCertificate = null; |
| | 0 | 521 | | } |
| | 0 | 522 | | _externalPendingCert?.Dispose(); |
| | 0 | 523 | | _externalPendingCert = null; |
| | 0 | 524 | | } |
| | | 525 | | |
| | 0 | 526 | | DisposeExternalRemoteCertificates(); |
| | 0 | 527 | | } |
| | | 528 | | |
| | | 529 | | #if !TARGET_WINDOWS && !SYSNETSECURITY_NO_OPENSSL |
| | | 530 | | // Client-side only path. When CertVerifyCallback paused the handshake via |
| | | 531 | | // SSL_set_retry_verify, RetryVerifyAttempted is set on the SafeSslHandle. Stamp |
| | | 532 | | // the caller's verdict onto the handle so the next SSL_do_handshake (driven by |
| | | 533 | | // the caller's next ProcessHandshake) re-enters the callback and either accepts |
| | | 534 | | // the peer cert or emits a fatal alert. No-op on server sessions and on 1.1.x |
| | | 535 | | // where CertVerifyCallback took the accept-and-defer branch instead of retrying. |
| | | 536 | | private void PushExternalValidationVerdictToPalIfRetryVerify(SslPolicyErrors errors) |
| | | 537 | | { |
| | | 538 | | if (_securityContext is not Microsoft.Win32.SafeHandles.SafeSslHandle sslHandle || |
| | | 539 | | !sslHandle.RetryVerifyAttempted) |
| | | 540 | | { |
| | | 541 | | return; |
| | | 542 | | } |
| | | 543 | | |
| | | 544 | | sslHandle.ExternalValidationAccepted = errors == SslPolicyErrors.None; |
| | | 545 | | } |
| | | 546 | | #endif |
| | | 547 | | |
| | | 548 | | /// <summary> |
| | | 549 | | /// Server-side only. The parsed ClientHello information, populated once the |
| | | 550 | | /// ClientHello has been received and stays populated for the lifetime of the |
| | | 551 | | /// session. Returns <see langword="null"/> before the ClientHello arrives, |
| | | 552 | | /// on client-side sessions, and on server sessions where ClientHello capture |
| | | 553 | | /// was disabled via the <c>System.Net.Security.CaptureClientHello</c> AppContext |
| | | 554 | | /// switch AND options were supplied at <see cref="TlsContext"/> creation time. |
| | | 555 | | /// </summary> |
| | | 556 | | public SslClientHelloInfo? ClientHelloInfo |
| | | 557 | | { |
| | | 558 | | get |
| | 0 | 559 | | { |
| | 0 | 560 | | ThrowIfDisposed(); |
| | 0 | 561 | | return _clientHelloInfo; |
| | 0 | 562 | | } |
| | | 563 | | } |
| | | 564 | | |
| | | 565 | | /// <summary> |
| | | 566 | | /// Server-side only. Returns the number of bytes in the captured raw ClientHello |
| | | 567 | | /// record (5-byte TLS record header plus the ClientHello handshake message), or |
| | | 568 | | /// 0 if unavailable. Callers use this to size a destination buffer for |
| | | 569 | | /// <see cref="TryGetClientHelloBytes"/>. |
| | | 570 | | /// </summary> |
| | | 571 | | /// <remarks> |
| | | 572 | | /// The ClientHello is only captured on server-side sessions and requires the |
| | | 573 | | /// <c>System.Net.Security.CaptureClientHello</c> AppContext switch to be enabled |
| | | 574 | | /// (default true). Returns 0 on client-side sessions, before the ClientHello has |
| | | 575 | | /// been received, or when capture has been disabled. |
| | | 576 | | /// </remarks> |
| | | 577 | | public int GetClientHelloLength() |
| | 0 | 578 | | { |
| | 0 | 579 | | ThrowIfDisposed(); |
| | | 580 | | |
| | 0 | 581 | | ReadOnlySpan<byte> native = default; |
| | | 582 | | TryGetNativeClientHelloBytes(ref native); |
| | 0 | 583 | | if (!native.IsEmpty) |
| | 0 | 584 | | { |
| | 0 | 585 | | return native.Length; |
| | | 586 | | } |
| | | 587 | | |
| | 0 | 588 | | return _clientHelloBytesBuffered?.Length ?? 0; |
| | 0 | 589 | | } |
| | | 590 | | |
| | | 591 | | /// <summary> |
| | | 592 | | /// Server-side only. Copies the captured raw ClientHello record into |
| | | 593 | | /// <paramref name="destination"/>. Returns <see langword="true"/> when the full |
| | | 594 | | /// record was written; <see langword="false"/> if the destination is too small |
| | | 595 | | /// or the ClientHello is not available. |
| | | 596 | | /// </summary> |
| | | 597 | | /// <param name="destination">Buffer that receives the ClientHello bytes.</param> |
| | | 598 | | /// <param name="bytesWritten">Number of bytes copied. Zero when the method returns false.</param> |
| | | 599 | | public bool TryGetClientHelloBytes(Span<byte> destination, out int bytesWritten) |
| | 0 | 600 | | { |
| | 0 | 601 | | ThrowIfDisposed(); |
| | | 602 | | |
| | 0 | 603 | | ReadOnlySpan<byte> source = default; |
| | | 604 | | TryGetNativeClientHelloBytes(ref source); |
| | 0 | 605 | | if (source.IsEmpty) |
| | 0 | 606 | | { |
| | 0 | 607 | | if (_clientHelloBytesBuffered is null) |
| | 0 | 608 | | { |
| | 0 | 609 | | bytesWritten = 0; |
| | 0 | 610 | | return false; |
| | | 611 | | } |
| | 0 | 612 | | source = _clientHelloBytesBuffered; |
| | 0 | 613 | | } |
| | | 614 | | |
| | 0 | 615 | | if (destination.Length < source.Length) |
| | 0 | 616 | | { |
| | 0 | 617 | | bytesWritten = 0; |
| | 0 | 618 | | return false; |
| | | 619 | | } |
| | | 620 | | |
| | 0 | 621 | | source.CopyTo(destination); |
| | 0 | 622 | | bytesWritten = source.Length; |
| | 0 | 623 | | return true; |
| | 0 | 624 | | } |
| | | 625 | | |
| | | 626 | | /// <summary> |
| | | 627 | | /// Assigns a <see cref="TlsContext"/> to this session. Must be called at least |
| | | 628 | | /// once before <see cref="TlsBufferSession.Handshake"/> or its socket-bound |
| | | 629 | | /// equivalent can make forward progress. May also be called on a server-side |
| | | 630 | | /// session that suspended with <see cref="TlsOperationStatus.NeedsTlsContext"/> |
| | | 631 | | /// to steer it onto the resolved per-tenant context. |
| | | 632 | | /// </summary> |
| | | 633 | | /// <param name="context">A fully-configured <see cref="TlsContext"/>.</param> |
| | | 634 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="context"/> is null.</exception> |
| | | 635 | | /// <exception cref="ArgumentException"> |
| | | 636 | | /// Thrown when supplying a resolved context after |
| | | 637 | | /// <see cref="TlsOperationStatus.NeedsTlsContext"/> and the passed context is |
| | | 638 | | /// not server-side. |
| | | 639 | | /// </exception> |
| | | 640 | | /// <exception cref="InvalidOperationException"> |
| | | 641 | | /// Thrown when the session already has a context and is not currently awaiting |
| | | 642 | | /// server options (i.e., the caller tried to swap a context that was already |
| | | 643 | | /// fully configured). |
| | | 644 | | /// </exception> |
| | | 645 | | public void SetContext(TlsContext context) |
| | 0 | 646 | | { |
| | 0 | 647 | | ArgumentNullException.ThrowIfNull(context); |
| | 0 | 648 | | ThrowIfDisposed(); |
| | | 649 | | |
| | 0 | 650 | | if (_context is null) |
| | 0 | 651 | | { |
| | 0 | 652 | | InitializeFromContext(context); |
| | 0 | 653 | | return; |
| | | 654 | | } |
| | | 655 | | |
| | 0 | 656 | | if (!_context!.IsServer) |
| | 0 | 657 | | { |
| | 0 | 658 | | throw new InvalidOperationException(SR.net_tlssession_setcontext_server_only); |
| | | 659 | | } |
| | 0 | 660 | | if (!context.IsServer) |
| | 0 | 661 | | { |
| | 0 | 662 | | throw new ArgumentException(SR.net_tlssession_context_must_be_server, nameof(context)); |
| | | 663 | | } |
| | 0 | 664 | | if (_hasServerOptions) |
| | 0 | 665 | | { |
| | 0 | 666 | | throw new InvalidOperationException(SR.net_tlssession_server_options_already_supplied); |
| | | 667 | | } |
| | 0 | 668 | | if (_clientHelloInfo is null) |
| | 0 | 669 | | { |
| | 0 | 670 | | throw new InvalidOperationException(SR.net_tlssession_setcontext_needs_context_first); |
| | | 671 | | } |
| | | 672 | | |
| | | 673 | | // Ask the supplied context for a session-options bag — this allocates its |
| | | 674 | | // long-lived SSL_CTX (if not already) and stamps PreallocatedSslContext on |
| | | 675 | | // the returned bag. Copy those fields (including PreallocatedSslContext) into |
| | | 676 | | // our session's options so subsequent AllocateSslHandle picks up the passed |
| | | 677 | | // context's SSL_CTX instead of falling back to the per-session cache path. |
| | 0 | 678 | | SslAuthenticationOptions serverOpts = context.CreateSessionOptions(); |
| | 0 | 679 | | _options.CopyFrom(serverOpts); |
| | | 680 | | #if !TARGET_WINDOWS && !SYSNETSECURITY_NO_OPENSSL |
| | | 681 | | _options.PreallocatedSslContext = serverOpts.PreallocatedSslContext; |
| | | 682 | | #endif |
| | | 683 | | |
| | | 684 | | // CopyFrom sets _options.OwnsCertificateContext = false and copies the |
| | | 685 | | // template's CertificateContext reference into the bag. Re-seat our session |
| | | 686 | | // ownership from the freshly-copied serverOpts (the new template may have |
| | | 687 | | // brought its own owned context via ServerCertificate), releasing any prior |
| | | 688 | | // session-owned context. serverOpts itself is a per-session clone that Owns |
| | | 689 | | // = false, so its live-owner is the source TlsContext template that stays |
| | | 690 | | // alive across sessions — hence takeOwnership: false here. |
| | 0 | 691 | | SetSessionCertificateContext(_options.CertificateContext, takeOwnership: false); |
| | | 692 | | |
| | 0 | 693 | | _hasServerOptions = true; |
| | | 694 | | |
| | | 695 | | // The per-tenant options differ from the bootstrap context's template, so |
| | | 696 | | // credentials must be session-local. Otherwise EnsureCredentialsAcquired |
| | | 697 | | // would stamp this session's SChannel cred handle into the shared bootstrap |
| | | 698 | | // TlsContext.CredentialsHandle, and every subsequent session on the same |
| | | 699 | | // bootstrap would inherit those credentials regardless of which tenant it |
| | | 700 | | // resolved to (SChannel-only; OpenSSL routes per-tenant SSL_CTX via |
| | | 701 | | // PreallocatedSslContext on the session-local options bag). Acquire eagerly |
| | | 702 | | // so any AcquireCredentialsHandle failure surfaces from SetContext, |
| | | 703 | | // not from an opaque PAL call downstream. |
| | 0 | 704 | | _sessionCredentialsHandle?.Dispose(); |
| | 0 | 705 | | _sessionCredentialsHandle = SslStreamPal.AcquireCredentialsHandle(_options, false); |
| | | 706 | | |
| | | 707 | | OnServerContextSet(); |
| | 0 | 708 | | } |
| | | 709 | | |
| | | 710 | | /// <summary> |
| | | 711 | | /// Client-side only. Supplies the certificate context the session should send |
| | | 712 | | /// in response to the server's CertificateRequest, or <see langword="null"/> to |
| | | 713 | | /// decline. Intended to resolve a session suspended on |
| | | 714 | | /// <see cref="TlsOperationStatus.CertificateRequested"/>: callers that need to |
| | | 715 | | /// fetch a certificate from an out-of-process source (e.g. a key vault) do so |
| | | 716 | | /// outside the session, then resume the handshake. May also be called before |
| | | 717 | | /// the first handshake call to seed the client credential when the |
| | | 718 | | /// <see cref="TlsContext"/> was created without one. |
| | | 719 | | /// </summary> |
| | | 720 | | /// <exception cref="InvalidOperationException"> |
| | | 721 | | /// Thrown on a server-side session, or before <see cref="SetContext"/> has been |
| | | 722 | | /// called. |
| | | 723 | | /// </exception> |
| | | 724 | | public void SetClientCertificateContext(SslStreamCertificateContext? context) |
| | 0 | 725 | | { |
| | 0 | 726 | | ThrowIfDisposed(); |
| | 0 | 727 | | ThrowIfContextNotSet(); |
| | | 728 | | |
| | 0 | 729 | | if (_context!.IsServer) |
| | 0 | 730 | | { |
| | 0 | 731 | | throw new InvalidOperationException(SR.net_tlssession_setclientcert_client_only); |
| | | 732 | | } |
| | 0 | 733 | | SetSessionCertificateContext(context, takeOwnership: false); |
| | | 734 | | |
| | | 735 | | // Acquire a session-local credentials handle so we don't touch the shared |
| | | 736 | | // TlsContext.CredentialsHandle, which is used by any concurrent session on |
| | | 737 | | // the same context (racing/disposing it can cause handshake failures or |
| | | 738 | | // deliver the wrong certificate on SChannel). ActiveCredentialsRef() will |
| | | 739 | | // return this session-local handle for subsequent PAL calls. Acquire eagerly |
| | | 740 | | // so any AcquireCredentialsHandle failure surfaces here, not from an opaque |
| | | 741 | | // PAL call downstream. |
| | 0 | 742 | | _sessionCredentialsHandle?.Dispose(); |
| | 0 | 743 | | _sessionCredentialsHandle = SslStreamPal.AcquireCredentialsHandle(_options, false); |
| | 0 | 744 | | _resumeAfterCredentials = true; |
| | 0 | 745 | | } |
| | | 746 | | |
| | | 747 | | /// <summary> |
| | | 748 | | /// Client-side only. Returns the distinguished names of the certificate authorities |
| | | 749 | | /// the server listed in its TLS 1.2 <c>CertificateRequest</c> or TLS 1.3 |
| | | 750 | | /// <c>certificate_authorities</c> extension. Intended to be called while the session |
| | | 751 | | /// is suspended on <see cref="TlsOperationStatus.CertificateRequested"/> so the caller can |
| | | 752 | | /// pick a client certificate that chains to one of the listed CAs. Returns |
| | | 753 | | /// <see langword="null"/> when no security context exists yet, when the peer sent no |
| | | 754 | | /// hints, or on a server-side session. |
| | | 755 | | /// </summary> |
| | | 756 | | public IReadOnlyList<string>? GetAcceptableIssuers() |
| | 0 | 757 | | { |
| | 0 | 758 | | ThrowIfDisposed(); |
| | | 759 | | |
| | 0 | 760 | | if (_context is null || _context.IsServer || _securityContext is null) |
| | 0 | 761 | | { |
| | 0 | 762 | | return null; |
| | | 763 | | } |
| | | 764 | | |
| | 0 | 765 | | string[] issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext); |
| | 0 | 766 | | return issuers.Length == 0 ? null : issuers; |
| | 0 | 767 | | } |
| | | 768 | | |
| | | 769 | | private void ThrowIfPendingExternalValidation() |
| | 0 | 770 | | { |
| | 0 | 771 | | if (_externalValidationFault is not null) |
| | 0 | 772 | | { |
| | 0 | 773 | | throw _externalValidationFault; |
| | | 774 | | } |
| | 0 | 775 | | if (_externalValidationPending) |
| | 0 | 776 | | { |
| | 0 | 777 | | throw new InvalidOperationException( |
| | 0 | 778 | | SR.net_tlssession_validation_result_not_recorded); |
| | | 779 | | } |
| | 0 | 780 | | } |
| | | 781 | | |
| | | 782 | | private void DisposeExternalRemoteCertificates() |
| | 0 | 783 | | { |
| | 0 | 784 | | X509Certificate2Collection? certs = _externalRemoteCertificates; |
| | 0 | 785 | | _externalRemoteCertificates = null; |
| | 0 | 786 | | if (certs is null) |
| | 0 | 787 | | { |
| | 0 | 788 | | return; |
| | | 789 | | } |
| | 0 | 790 | | foreach (X509Certificate2 c in certs) |
| | 0 | 791 | | { |
| | 0 | 792 | | c.Dispose(); |
| | 0 | 793 | | } |
| | 0 | 794 | | } |
| | | 795 | | |
| | | 796 | | /// <summary> |
| | | 797 | | /// Returns the local certificate sent to the peer, or <c>null</c> if no |
| | | 798 | | /// local certificate was negotiated. For a server session this is the |
| | | 799 | | /// server certificate; for a client session this is the client |
| | | 800 | | /// certificate selected during handshake (which may be <c>null</c> if |
| | | 801 | | /// the server did not request a client certificate or the client did |
| | | 802 | | /// not supply one). |
| | | 803 | | /// </summary> |
| | | 804 | | public X509Certificate2? LocalCertificate |
| | | 805 | | { |
| | | 806 | | get |
| | 0 | 807 | | { |
| | 0 | 808 | | ThrowIfDisposed(); |
| | 0 | 809 | | if (_context!.IsServer) |
| | 0 | 810 | | { |
| | 0 | 811 | | return SessionCertificateContext?.TargetCertificate; |
| | | 812 | | } |
| | | 813 | | |
| | 0 | 814 | | if (_securityContext == null || _securityContext.IsInvalid) |
| | 0 | 815 | | { |
| | 0 | 816 | | return null; |
| | | 817 | | } |
| | | 818 | | |
| | 0 | 819 | | if (!CertificateValidationPal.IsLocalCertificateUsed(ActiveCredentialsRef(), _securityContext)) |
| | 0 | 820 | | { |
| | 0 | 821 | | return null; |
| | | 822 | | } |
| | | 823 | | |
| | 0 | 824 | | return SessionCertificateContext?.TargetCertificate; |
| | 0 | 825 | | } |
| | | 826 | | } |
| | | 827 | | |
| | | 828 | | /// <summary> |
| | | 829 | | /// Returns a <see cref="ChannelBinding"/> for the requested |
| | | 830 | | /// <paramref name="kind"/> derived from the current TLS session, or |
| | | 831 | | /// <c>null</c> if the binding is unavailable (e.g. handshake not yet |
| | | 832 | | /// complete, or unsupported binding kind). |
| | | 833 | | /// </summary> |
| | | 834 | | public ChannelBinding? GetChannelBinding(ChannelBindingKind kind) |
| | 0 | 835 | | { |
| | 0 | 836 | | ThrowIfDisposed(); |
| | 0 | 837 | | if (_securityContext == null || _securityContext.IsInvalid) |
| | 0 | 838 | | { |
| | 0 | 839 | | return null; |
| | | 840 | | } |
| | 0 | 841 | | return SslStreamPal.QueryContextChannelBinding(_securityContext, kind); |
| | 0 | 842 | | } |
| | | 843 | | |
| | | 844 | | // ── Handshake ───────────────────────────────────────────────────── |
| | | 845 | | |
| | | 846 | | private protected TlsOperationStatus HandshakeBufferedCore( |
| | | 847 | | ReadOnlySpan<byte> input, |
| | | 848 | | Span<byte> output, |
| | | 849 | | out int bytesConsumed, |
| | | 850 | | out int bytesWritten) |
| | 0 | 851 | | { |
| | 0 | 852 | | ThrowIfDisposed(); |
| | 0 | 853 | | ThrowIfContextNotSet(); |
| | 0 | 854 | | bytesConsumed = 0; |
| | 0 | 855 | | bytesWritten = 0; |
| | | 856 | | |
| | 0 | 857 | | if (_externalValidationFault is not null) |
| | 0 | 858 | | { |
| | | 859 | | // Mid-handshake external-validation reject: on OpenSSL 1.1.x and SecureTransport |
| | | 860 | | // the peer-verify callback took the accept-and-defer path (no retry-verify), so |
| | | 861 | | // the wire handshake still needs to complete before the fault surfaces on the |
| | | 862 | | // caller's Write / Read. Suppress the throw here while the handshake is still |
| | | 863 | | // in-flight so the PAL can silently drive it to completion; the fault will still |
| | | 864 | | // fire on Write / Read via ThrowIfPendingExternalValidation. On OpenSSL 3.0+ |
| | | 865 | | // retry-verify the natural PAL failure produces a fatal alert to the peer. |
| | 0 | 866 | | if (_isHandshakeComplete || !_externalValidationResolved) |
| | 0 | 867 | | { |
| | 0 | 868 | | throw _externalValidationFault; |
| | | 869 | | } |
| | 0 | 870 | | } |
| | | 871 | | |
| | 0 | 872 | | if (_externalValidationPending) |
| | 0 | 873 | | { |
| | 0 | 874 | | return TlsOperationStatus.NeedsCertificateValidation; |
| | | 875 | | } |
| | | 876 | | |
| | 0 | 877 | | if (_clientHelloInfo is not null && !_hasServerOptions) |
| | 0 | 878 | | { |
| | | 879 | | // The caller previously saw NeedsServerOptions but hasn't supplied options yet. |
| | 0 | 880 | | return TlsOperationStatus.NeedsTlsContext; |
| | | 881 | | } |
| | | 882 | | |
| | 0 | 883 | | if (_isHandshakeComplete) |
| | 0 | 884 | | { |
| | | 885 | | // Once the caller has resolved external validation, subsequent |
| | | 886 | | // ProcessHandshake calls on an already-complete session are a |
| | | 887 | | // no-op signal that the handshake is done (one-call window). |
| | 0 | 888 | | if (_externalValidationResolved) |
| | 0 | 889 | | { |
| | 0 | 890 | | return TlsOperationStatus.Complete; |
| | | 891 | | } |
| | | 892 | | |
| | 0 | 893 | | throw new InvalidOperationException(SR.net_tlssession_handshake_already_complete); |
| | | 894 | | } |
| | | 895 | | |
| | | 896 | | // Drain pending first; do not consume new input while output is owed. |
| | 0 | 897 | | if (_pendingBuffer.ActiveLength > 0) |
| | 0 | 898 | | { |
| | 0 | 899 | | bytesWritten = DrainTo(output); |
| | 0 | 900 | | return _pendingBuffer.ActiveLength > 0 ? TlsOperationStatus.DestinationTooSmall : TlsOperationStatus.Com |
| | | 901 | | } |
| | | 902 | | |
| | | 903 | | // The PAL state machine — SChannel in particular — must only be handed |
| | | 904 | | // complete TLS records. SChannel's PAL wrapper reports consumed=input.Length |
| | | 905 | | // when it returns SEC_E_INCOMPLETE_MESSAGE, which would silently swallow |
| | | 906 | | // bytes it actually still needs. OpenSSL's BIO accepts partial bytes, but |
| | | 907 | | // pre-checking the frame here costs nothing extra and keeps the state |
| | | 908 | | // machine identical across platforms. |
| | | 909 | | // |
| | | 910 | | // The only call that legitimately runs with empty input is the very first |
| | | 911 | | // client-side ISC, which produces the ClientHello, or a client resume after |
| | | 912 | | // SetClientCertificateContext resolved a prior WantCredentials suspension. |
| | 0 | 913 | | bool isInitialClientCall = !_context!.IsServer && _securityContext is null; |
| | 0 | 914 | | bool isCredentialResume = _resumeAfterCredentials; |
| | 0 | 915 | | _resumeAfterCredentials = false; |
| | 0 | 916 | | bool isCertValidationResume = _resumeAfterCertValidation; |
| | 0 | 917 | | _resumeAfterCertValidation = false; |
| | 0 | 918 | | if (!isInitialClientCall && !isCredentialResume && !isCertValidationResume) |
| | 0 | 919 | | { |
| | 0 | 920 | | if (input.Length < TlsFrameHelper.HeaderSize) |
| | 0 | 921 | | { |
| | 0 | 922 | | return TlsOperationStatus.NeedMoreData; |
| | | 923 | | } |
| | | 924 | | |
| | 0 | 925 | | TlsFrameHeader frameHeader = default; |
| | 0 | 926 | | if (!TlsFrameHelper.TryGetFrameHeader(input, ref frameHeader)) |
| | 0 | 927 | | { |
| | 0 | 928 | | throw new IOException(SR.net_io_decrypt); |
| | | 929 | | } |
| | | 930 | | |
| | 0 | 931 | | if (input.Length < frameHeader.Length) |
| | 0 | 932 | | { |
| | 0 | 933 | | return TlsOperationStatus.NeedMoreData; |
| | | 934 | | } |
| | 0 | 935 | | } |
| | | 936 | | |
| | 0 | 937 | | ProtocolToken token = default; |
| | 0 | 938 | | token.RentBuffer = true; |
| | | 939 | | try |
| | 0 | 940 | | { |
| | 0 | 941 | | if (_context!.IsServer) |
| | 0 | 942 | | { |
| | | 943 | | // Parse and capture the ClientHello managed-side so the ClientHelloInfo / |
| | | 944 | | // TargetHostName / GetClientHelloBytes surface is consistent across paths. |
| | | 945 | | // We check on every call while _clientHelloBytesBuffered is null because the |
| | | 946 | | // first ProcessHandshake call may pass only a partial CH record - OpenSSL will |
| | | 947 | | // allocate _securityContext even on partial input and return WantRead, so we |
| | | 948 | | // can't rely on _securityContext being null as our re-entry gate. |
| | 0 | 949 | | if (_clientHelloBytesBuffered is null) |
| | 0 | 950 | | { |
| | 0 | 951 | | SslClientHelloInfo? parsed = TryParseClientHello(input, out int frameLength); |
| | 0 | 952 | | if (parsed is not null) |
| | 0 | 953 | | { |
| | 0 | 954 | | _clientHelloInfo = parsed; |
| | 0 | 955 | | if (!string.IsNullOrEmpty(parsed.Value.ServerName)) |
| | 0 | 956 | | { |
| | 0 | 957 | | _sessionTargetHost = parsed.Value.ServerName; |
| | 0 | 958 | | } |
| | 0 | 959 | | if (frameLength > 0 && frameLength <= input.Length) |
| | 0 | 960 | | { |
| | 0 | 961 | | _clientHelloBytesBuffered = input.Slice(0, frameLength).ToArray(); |
| | 0 | 962 | | } |
| | | 963 | | // If frameLength is out of range (shouldn't happen after a successful |
| | | 964 | | // parse), silently skip capture; the session continues to work, |
| | | 965 | | // GetClientHelloLength just reports 0. |
| | 0 | 966 | | } |
| | 0 | 967 | | else if (_securityContext is null) |
| | 0 | 968 | | { |
| | | 969 | | // No CH parse-able yet and no PAL context yet - wait for more bytes. |
| | 0 | 970 | | return TlsOperationStatus.NeedMoreData; |
| | | 971 | | } |
| | 0 | 972 | | } |
| | | 973 | | |
| | | 974 | | // On the very first server-side call, inspect the incoming |
| | | 975 | | // ClientHello to surface SNI (TargetHost) and, if the caller |
| | | 976 | | // supplied a ServerCertificateSelectionCallback, resolve the |
| | | 977 | | // server certificate from it before AllocateSslHandle runs. |
| | 0 | 978 | | if (_securityContext is null) |
| | 0 | 979 | | { |
| | 0 | 980 | | if (!_hasServerOptions) |
| | 0 | 981 | | { |
| | | 982 | | // Deferred / SNI-callback flow: caller resolves via SetContext. |
| | | 983 | | // Leave input unconsumed; the caller re-feeds the same bytes on resume. |
| | 0 | 984 | | return TlsOperationStatus.NeedsTlsContext; |
| | | 985 | | } |
| | | 986 | | |
| | 0 | 987 | | bool needsCertResolution = |
| | 0 | 988 | | SessionCertificateContext is null && |
| | 0 | 989 | | _options.ServerCertSelectionDelegate is not null; |
| | | 990 | | |
| | 0 | 991 | | if (needsCertResolution && !ResolveServerCertificateFromClientHello(input)) |
| | 0 | 992 | | { |
| | | 993 | | // Need more bytes to parse the ClientHello (and run the |
| | | 994 | | // ServerCertificateSelectionCallback). |
| | 0 | 995 | | return TlsOperationStatus.NeedMoreData; |
| | | 996 | | } |
| | 0 | 997 | | } |
| | | 998 | | |
| | 0 | 999 | | EnsureCredentialsAcquired(); |
| | | 1000 | | |
| | 0 | 1001 | | token = SslStreamPal.AcceptSecurityContext( |
| | 0 | 1002 | | ref ActiveCredentialsRef(), |
| | 0 | 1003 | | ref _securityContext, |
| | 0 | 1004 | | input, |
| | 0 | 1005 | | out bytesConsumed, |
| | 0 | 1006 | | _options); |
| | 0 | 1007 | | } |
| | | 1008 | | else |
| | 0 | 1009 | | { |
| | 0 | 1010 | | EnsureCredentialsAcquired(); |
| | | 1011 | | |
| | 0 | 1012 | | string hostName = TargetHostNameHelper.NormalizeHostName(_options.TargetHost); |
| | 0 | 1013 | | token = SslStreamPal.InitializeSecurityContext( |
| | 0 | 1014 | | ref ActiveCredentialsRef(), |
| | 0 | 1015 | | ref _securityContext, |
| | 0 | 1016 | | hostName, |
| | 0 | 1017 | | input, |
| | 0 | 1018 | | out bytesConsumed, |
| | 0 | 1019 | | _options); |
| | 0 | 1020 | | } |
| | | 1021 | | |
| | | 1022 | | // Stage any handshake bytes the PAL produced. |
| | 0 | 1023 | | if (token.Size > 0) |
| | 0 | 1024 | | { |
| | 0 | 1025 | | Debug.Assert(token.Payload != null); |
| | 0 | 1026 | | AppendPending(new ReadOnlySpan<byte>(token.Payload, 0, token.Size)); |
| | 0 | 1027 | | } |
| | | 1028 | | |
| | | 1029 | | // Server-side ALPN selection ceremony (SChannel and SecureTransport). |
| | | 1030 | | // After parsing the ClientHello the PAL pauses and asks the caller to |
| | | 1031 | | // pick the application protocol before resuming. We re-enter ASC with |
| | | 1032 | | // an empty input so the PAL can generate the ServerHello carrying the |
| | | 1033 | | // selected ALPN value. |
| | 0 | 1034 | | if (token.Status.ErrorCode == SecurityStatusPalErrorCode.HandshakeStarted) |
| | 0 | 1035 | | { |
| | 0 | 1036 | | ReadOnlySpan<byte> rawAlpn = ReadOnlySpan<byte>.Empty; |
| | 0 | 1037 | | TlsFrameHelper.TlsFrameInfo frameInfo = default; |
| | 0 | 1038 | | if (TlsFrameHelper.TryGetFrameInfo(input, ref frameInfo, |
| | 0 | 1039 | | TlsFrameHelper.ProcessingOptions.ApplicationProtocol | TlsFrameHelper.ProcessingOptions.RawA |
| | 0 | 1040 | | frameInfo.RawApplicationProtocols is byte[] rawAlpnBytes) |
| | 0 | 1041 | | { |
| | 0 | 1042 | | rawAlpn = rawAlpnBytes; |
| | 0 | 1043 | | } |
| | | 1044 | | |
| | 0 | 1045 | | SecurityStatusPal selStatus = SslStreamPal.SelectApplicationProtocol( |
| | 0 | 1046 | | _context!.CredentialsHandle, |
| | 0 | 1047 | | _securityContext!, |
| | 0 | 1048 | | _options, |
| | 0 | 1049 | | rawAlpn); |
| | | 1050 | | |
| | 0 | 1051 | | if (selStatus.ErrorCode != SecurityStatusPalErrorCode.OK) |
| | 0 | 1052 | | { |
| | 0 | 1053 | | throw new AuthenticationException(SR.net_auth_SSPI, selStatus.Exception); |
| | | 1054 | | } |
| | | 1055 | | |
| | 0 | 1056 | | token.ReleasePayload(); |
| | | 1057 | | |
| | 0 | 1058 | | if (_context!.IsServer) |
| | 0 | 1059 | | { |
| | 0 | 1060 | | token = SslStreamPal.AcceptSecurityContext( |
| | 0 | 1061 | | ref ActiveCredentialsRef(), |
| | 0 | 1062 | | ref _securityContext, |
| | 0 | 1063 | | ReadOnlySpan<byte>.Empty, |
| | 0 | 1064 | | out _, |
| | 0 | 1065 | | _options); |
| | 0 | 1066 | | } |
| | | 1067 | | else |
| | 0 | 1068 | | { |
| | 0 | 1069 | | string hostName = TargetHostNameHelper.NormalizeHostName(_options.TargetHost); |
| | 0 | 1070 | | token = SslStreamPal.InitializeSecurityContext( |
| | 0 | 1071 | | ref ActiveCredentialsRef(), |
| | 0 | 1072 | | ref _securityContext, |
| | 0 | 1073 | | hostName, |
| | 0 | 1074 | | ReadOnlySpan<byte>.Empty, |
| | 0 | 1075 | | out _, |
| | 0 | 1076 | | _options); |
| | 0 | 1077 | | } |
| | | 1078 | | |
| | 0 | 1079 | | if (token.Size > 0) |
| | 0 | 1080 | | { |
| | 0 | 1081 | | Debug.Assert(token.Payload != null); |
| | 0 | 1082 | | AppendPending(new ReadOnlySpan<byte>(token.Payload, 0, token.Size)); |
| | 0 | 1083 | | } |
| | 0 | 1084 | | } |
| | | 1085 | | |
| | 0 | 1086 | | if (token.Failed && |
| | 0 | 1087 | | token.Status.ErrorCode != SecurityStatusPalErrorCode.CredentialsNeeded && |
| | 0 | 1088 | | token.Status.ErrorCode != SecurityStatusPalErrorCode.CertValidationNeeded) |
| | 0 | 1089 | | { |
| | 0 | 1090 | | Exception authExc = new AuthenticationException(SR.net_auth_SSPI, token.GetException()); |
| | | 1091 | | |
| | | 1092 | | // OpenSSL queued a TLS alert in the BIO during the failing SSL_do_handshake |
| | | 1093 | | // (e.g. bad_certificate after the client-side retry-verify callback rejected |
| | | 1094 | | // the peer). Drain the alert to the caller's output buffer before throwing so |
| | | 1095 | | // the peer observes an AuthenticationException instead of a connection reset. |
| | | 1096 | | // The fault is re-raised on the next ProcessHandshake call once the queue is |
| | | 1097 | | // empty. Only fires on the client path today; server-side never reaches this |
| | | 1098 | | // branch for external-validation reasons because CertVerifyCallback |
| | | 1099 | | // accepts-and-defers (see gating in Interop.OpenSsl.CertVerifyCallback). |
| | 0 | 1100 | | if (_pendingBuffer.ActiveLength > 0) |
| | 0 | 1101 | | { |
| | 0 | 1102 | | bytesWritten = DrainTo(output); |
| | 0 | 1103 | | _externalValidationFault = authExc; |
| | 0 | 1104 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 1105 | | } |
| | | 1106 | | |
| | 0 | 1107 | | throw authExc; |
| | | 1108 | | } |
| | | 1109 | | |
| | 0 | 1110 | | bool done = token.Status.ErrorCode == SecurityStatusPalErrorCode.OK; |
| | 0 | 1111 | | bool needsCredentials = token.Status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded; |
| | 0 | 1112 | | bool needsCertValidation = token.Status.ErrorCode == SecurityStatusPalErrorCode.CertValidationNeeded; |
| | | 1113 | | |
| | 0 | 1114 | | if (done) |
| | 0 | 1115 | | { |
| | 0 | 1116 | | OnHandshakeCompleted(); |
| | 0 | 1117 | | } |
| | 0 | 1118 | | else if (needsCertValidation) |
| | 0 | 1119 | | { |
| | | 1120 | | // PAL paused mid-handshake awaiting external certificate validation. |
| | | 1121 | | // Capture the peer cert + chain so the caller can validate, then return |
| | | 1122 | | // NeedsCertificateValidation. Not used by the current OpenSSL or SChannel |
| | | 1123 | | // paths but kept as a generic suspension hook. |
| | 0 | 1124 | | CaptureRemoteCertificateForExternalValidation(); |
| | 0 | 1125 | | } |
| | | 1126 | | |
| | 0 | 1127 | | if (_pendingBuffer.ActiveLength > 0) |
| | 0 | 1128 | | { |
| | 0 | 1129 | | bytesWritten = DrainTo(output); |
| | 0 | 1130 | | if (_pendingBuffer.ActiveLength > 0) |
| | 0 | 1131 | | { |
| | 0 | 1132 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 1133 | | } |
| | 0 | 1134 | | } |
| | | 1135 | | |
| | 0 | 1136 | | if (done) |
| | 0 | 1137 | | { |
| | 0 | 1138 | | return _externalValidationPending |
| | 0 | 1139 | | ? TlsOperationStatus.NeedsCertificateValidation |
| | 0 | 1140 | | : TlsOperationStatus.Complete; |
| | | 1141 | | } |
| | | 1142 | | |
| | 0 | 1143 | | if (needsCertValidation) |
| | 0 | 1144 | | { |
| | 0 | 1145 | | return TlsOperationStatus.NeedsCertificateValidation; |
| | | 1146 | | } |
| | | 1147 | | |
| | 0 | 1148 | | if (needsCredentials) |
| | 0 | 1149 | | { |
| | 0 | 1150 | | return TlsOperationStatus.CertificateRequested; |
| | | 1151 | | } |
| | | 1152 | | |
| | | 1153 | | // SChannel consumes one TLS record per AcceptSecurityContext/ |
| | | 1154 | | // InitializeSecurityContext call (OpenSSL typically consumes the |
| | | 1155 | | // whole input via the BIO). When the PAL accepted bytes but the |
| | | 1156 | | // caller still has more buffered, return Complete so the driver |
| | | 1157 | | // re-enters us with the remainder instead of blocking on a network |
| | | 1158 | | // read the peer will never satisfy (e.g. server seeing CKE+CCS+ |
| | | 1159 | | // Finished in one TCP read during a TLS 1.2 handshake). |
| | 0 | 1160 | | if (bytesConsumed > 0 && bytesConsumed < input.Length) |
| | 0 | 1161 | | { |
| | 0 | 1162 | | return TlsOperationStatus.Complete; |
| | | 1163 | | } |
| | | 1164 | | |
| | 0 | 1165 | | return TlsOperationStatus.NeedMoreData; |
| | | 1166 | | } |
| | | 1167 | | finally |
| | 0 | 1168 | | { |
| | 0 | 1169 | | token.ReleasePayload(); |
| | 0 | 1170 | | } |
| | 0 | 1171 | | } |
| | | 1172 | | |
| | | 1173 | | private protected TlsOperationStatus WriteBufferedCore( |
| | | 1174 | | ReadOnlySpan<byte> plaintext, |
| | | 1175 | | Span<byte> ciphertext, |
| | | 1176 | | out int bytesConsumed, |
| | | 1177 | | out int bytesWritten) |
| | 0 | 1178 | | { |
| | 0 | 1179 | | ThrowIfDisposed(); |
| | 0 | 1180 | | ThrowIfPendingExternalValidation(); |
| | 0 | 1181 | | bytesConsumed = 0; |
| | 0 | 1182 | | bytesWritten = 0; |
| | | 1183 | | |
| | 0 | 1184 | | if (!_isHandshakeComplete) |
| | 0 | 1185 | | { |
| | 0 | 1186 | | throw new InvalidOperationException(SR.net_tlssession_handshake_not_complete); |
| | | 1187 | | } |
| | | 1188 | | |
| | 0 | 1189 | | if (_pendingBuffer.ActiveLength > 0) |
| | 0 | 1190 | | { |
| | 0 | 1191 | | bytesWritten = DrainTo(ciphertext); |
| | 0 | 1192 | | return _pendingBuffer.ActiveLength > 0 ? TlsOperationStatus.DestinationTooSmall : TlsOperationStatus.Com |
| | | 1193 | | } |
| | | 1194 | | |
| | 0 | 1195 | | if (plaintext.IsEmpty) |
| | 0 | 1196 | | { |
| | 0 | 1197 | | return TlsOperationStatus.Complete; |
| | | 1198 | | } |
| | | 1199 | | |
| | 0 | 1200 | | int chunk = Math.Min(plaintext.Length, _maxDataSize); |
| | 0 | 1201 | | byte[] rented = ArrayPool<byte>.Shared.Rent(chunk); |
| | | 1202 | | try |
| | 0 | 1203 | | { |
| | 0 | 1204 | | plaintext.Slice(0, chunk).CopyTo(rented); |
| | | 1205 | | |
| | 0 | 1206 | | ProtocolToken token = SslStreamPal.EncryptMessage( |
| | 0 | 1207 | | _securityContext!, |
| | 0 | 1208 | | new ReadOnlyMemory<byte>(rented, 0, chunk), |
| | 0 | 1209 | | _headerSize, |
| | 0 | 1210 | | _trailerSize); |
| | | 1211 | | |
| | | 1212 | | try |
| | 0 | 1213 | | { |
| | 0 | 1214 | | if (token.Status.ErrorCode != SecurityStatusPalErrorCode.OK) |
| | 0 | 1215 | | { |
| | 0 | 1216 | | throw new IOException(SR.net_io_encrypt, SslStreamPal.GetException(token.Status)); |
| | | 1217 | | } |
| | | 1218 | | |
| | 0 | 1219 | | bytesConsumed = chunk; |
| | | 1220 | | |
| | 0 | 1221 | | if (token.Size > 0) |
| | 0 | 1222 | | { |
| | 0 | 1223 | | Debug.Assert(token.Payload != null); |
| | 0 | 1224 | | AppendPending(new ReadOnlySpan<byte>(token.Payload, 0, token.Size)); |
| | 0 | 1225 | | } |
| | 0 | 1226 | | } |
| | | 1227 | | finally |
| | 0 | 1228 | | { |
| | 0 | 1229 | | token.ReleasePayload(); |
| | 0 | 1230 | | } |
| | 0 | 1231 | | } |
| | | 1232 | | finally |
| | 0 | 1233 | | { |
| | 0 | 1234 | | ArrayPool<byte>.Shared.Return(rented); |
| | 0 | 1235 | | } |
| | | 1236 | | |
| | 0 | 1237 | | bytesWritten = DrainTo(ciphertext); |
| | 0 | 1238 | | return _pendingBuffer.ActiveLength > 0 ? TlsOperationStatus.DestinationTooSmall : TlsOperationStatus.Complet |
| | 0 | 1239 | | } |
| | | 1240 | | |
| | | 1241 | | // ── Decrypt ─────────────────────────────────────────────────────── |
| | | 1242 | | |
| | | 1243 | | private protected TlsOperationStatus ReadBufferedCore( |
| | | 1244 | | ReadOnlySpan<byte> ciphertext, |
| | | 1245 | | Span<byte> plaintext, |
| | | 1246 | | out int bytesConsumed, |
| | | 1247 | | out int bytesWritten) |
| | 0 | 1248 | | { |
| | 0 | 1249 | | ThrowIfDisposed(); |
| | 0 | 1250 | | ThrowIfPendingExternalValidation(); |
| | 0 | 1251 | | bytesConsumed = 0; |
| | 0 | 1252 | | bytesWritten = 0; |
| | | 1253 | | |
| | 0 | 1254 | | if (!_isHandshakeComplete) |
| | 0 | 1255 | | { |
| | 0 | 1256 | | throw new InvalidOperationException(SR.net_tlssession_handshake_not_complete); |
| | | 1257 | | } |
| | | 1258 | | |
| | 0 | 1259 | | if (_pendingBuffer.ActiveLength > 0) |
| | 0 | 1260 | | { |
| | | 1261 | | // Caller must drain before we accept new input. |
| | 0 | 1262 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 1263 | | } |
| | | 1264 | | |
| | | 1265 | | // Need at least a frame header. If the caller didn't provide a full frame, the PAL |
| | | 1266 | | // may still have plaintext buffered internally — ciphertext absorbed by OpenSSL's |
| | | 1267 | | // BIO during ProcessHandshake (e.g. the peer coalesced its Finished with the first |
| | | 1268 | | // app-data record into one TCP segment) or a record consumed but not yet decrypted |
| | | 1269 | | // by a prior Decrypt call. On platforms whose PAL maintains such a buffer, probe it |
| | | 1270 | | // with an empty input before asking the caller for more wire bytes; otherwise the |
| | | 1271 | | // session deadlocks waiting on data the peer already sent. |
| | 0 | 1272 | | if (ciphertext.Length < TlsFrameHelper.HeaderSize) |
| | 0 | 1273 | | { |
| | 0 | 1274 | | return TryDrainBufferedPlaintext(plaintext, out bytesWritten); |
| | | 1275 | | } |
| | | 1276 | | |
| | 0 | 1277 | | TlsFrameHeader header = default; |
| | 0 | 1278 | | if (!TlsFrameHelper.TryGetFrameHeader(ciphertext, ref header)) |
| | 0 | 1279 | | { |
| | 0 | 1280 | | throw new IOException(SR.net_io_decrypt); |
| | | 1281 | | } |
| | | 1282 | | |
| | 0 | 1283 | | int frameSize = header.Length; |
| | 0 | 1284 | | if (ciphertext.Length < frameSize) |
| | 0 | 1285 | | { |
| | 0 | 1286 | | return TryDrainBufferedPlaintext(plaintext, out bytesWritten); |
| | | 1287 | | } |
| | | 1288 | | |
| | | 1289 | | // PAL decrypts in place; copy into a writable scratch buffer. |
| | 0 | 1290 | | EnsureDecryptScratch(frameSize); |
| | 0 | 1291 | | ciphertext.Slice(0, frameSize).CopyTo(_decryptScratch); |
| | | 1292 | | |
| | 0 | 1293 | | SecurityStatusPal status = SslStreamPal.DecryptMessage( |
| | 0 | 1294 | | _securityContext!, |
| | 0 | 1295 | | _decryptScratch.AsSpan(0, frameSize), |
| | 0 | 1296 | | plaintext, |
| | 0 | 1297 | | out int decBytesWritten, |
| | 0 | 1298 | | out int decLeftoverOffset, |
| | 0 | 1299 | | out int decLeftoverLength); |
| | | 1300 | | |
| | 0 | 1301 | | switch (status.ErrorCode) |
| | | 1302 | | { |
| | | 1303 | | case SecurityStatusPalErrorCode.OK: |
| | 0 | 1304 | | bytesConsumed = frameSize; |
| | | 1305 | | // Linux/macOS PALs write the plaintext directly into the destination span and |
| | | 1306 | | // (if it didn't fit, or the PAL prefers in-place) leave overflow in the encrypted |
| | | 1307 | | // span at leftoverOffset/leftoverLength. SChannel always decrypts in place and |
| | | 1308 | | // reports bytesWritten = 0 with leftoverOffset/leftoverLength pointing at the |
| | | 1309 | | // plaintext inside the encrypted span. Unify by appending the leftover slice |
| | | 1310 | | // after whatever was written into destination. |
| | 0 | 1311 | | int needed = decBytesWritten + decLeftoverLength; |
| | 0 | 1312 | | if (needed > plaintext.Length) |
| | 0 | 1313 | | { |
| | 0 | 1314 | | throw new InvalidOperationException( |
| | 0 | 1315 | | SR.Format(SR.net_tlssession_plaintext_buffer_too_small, needed, plaintext.Length)); |
| | | 1316 | | } |
| | 0 | 1317 | | if (decLeftoverLength > 0) |
| | 0 | 1318 | | { |
| | 0 | 1319 | | _decryptScratch.AsSpan(decLeftoverOffset, decLeftoverLength) |
| | 0 | 1320 | | .CopyTo(plaintext.Slice(decBytesWritten)); |
| | 0 | 1321 | | } |
| | 0 | 1322 | | bytesWritten = needed; |
| | 0 | 1323 | | return TlsOperationStatus.Complete; |
| | | 1324 | | |
| | | 1325 | | case SecurityStatusPalErrorCode.ContextExpired: |
| | | 1326 | | case SecurityStatusPalErrorCode.ContextExpiredError: |
| | 0 | 1327 | | bytesConsumed = frameSize; |
| | 0 | 1328 | | return TlsOperationStatus.Closed; |
| | | 1329 | | |
| | | 1330 | | case SecurityStatusPalErrorCode.Renegotiate: |
| | | 1331 | | // SChannel surfaces SEC_I_RENEGOTIATE for two distinct cases: |
| | | 1332 | | // - TLS 1.2 peer-initiated renegotiation (HelloRequest). |
| | | 1333 | | // - TLS 1.3 post-handshake messages (NewSessionTicket, |
| | | 1334 | | // KeyUpdate, post-handshake CertificateRequest). |
| | | 1335 | | // In either case the decrypted payload is the inner handshake |
| | | 1336 | | // record that must be fed back into ASC/ISC so SChannel can |
| | | 1337 | | // update its internal state. If we don't, the next DecryptMessage |
| | | 1338 | | // returns SEC_E_CONTEXT_EXPIRED because the context is stuck. |
| | 0 | 1339 | | bytesConsumed = frameSize; |
| | 0 | 1340 | | if (decLeftoverLength > 0) |
| | 0 | 1341 | | { |
| | 0 | 1342 | | ProcessPostHandshakeMessage(_decryptScratch.AsSpan(decLeftoverOffset, decLeftoverLength)); |
| | 0 | 1343 | | } |
| | | 1344 | | // Return Complete (not WantRead): we consumed input bytes but |
| | | 1345 | | // produced no plaintext. The caller's loop should re-enter to |
| | | 1346 | | // process any remaining buffered ciphertext (e.g. application |
| | | 1347 | | // data that arrived in the same TCP segment as the NST). |
| | 0 | 1348 | | return TlsOperationStatus.Complete; |
| | | 1349 | | |
| | | 1350 | | default: |
| | 0 | 1351 | | throw new IOException(SR.net_io_decrypt, SslStreamPal.GetException(status)); |
| | | 1352 | | } |
| | 0 | 1353 | | } |
| | | 1354 | | |
| | | 1355 | | // Empty-input probe used when the caller's buffer doesn't yet hold a complete TLS |
| | | 1356 | | // frame. On OpenSSL the PAL's record layer may still have plaintext queued from a |
| | | 1357 | | // prior call (handshake input that included trailing app-data, or a second record |
| | | 1358 | | // coalesced into the same TCP segment); calling DecryptMessage with an empty span |
| | | 1359 | | // surfaces it. On SChannel / SecureTransport the equivalent buffer does not exist, |
| | | 1360 | | // so the probe is skipped and the caller is asked for more bytes instead. The |
| | | 1361 | | // bytesConsumed out-parameter on the public Decrypt method is necessarily 0 here: |
| | | 1362 | | // no caller bytes were taken. |
| | | 1363 | | private TlsOperationStatus TryDrainBufferedPlaintext(Span<byte> plaintext, out int bytesWritten) |
| | 0 | 1364 | | { |
| | 0 | 1365 | | bytesWritten = 0; |
| | | 1366 | | |
| | 0 | 1367 | | if (!OperatingSystem.IsLinux() && !OperatingSystem.IsFreeBSD() && !OperatingSystem.IsAndroid()) |
| | 0 | 1368 | | { |
| | 0 | 1369 | | return TlsOperationStatus.NeedMoreData; |
| | | 1370 | | } |
| | | 1371 | | |
| | 0 | 1372 | | SecurityStatusPal status = SslStreamPal.DecryptMessage( |
| | 0 | 1373 | | _securityContext!, |
| | 0 | 1374 | | Span<byte>.Empty, |
| | 0 | 1375 | | plaintext, |
| | 0 | 1376 | | out int decBytesWritten, |
| | 0 | 1377 | | out int decLeftoverOffset, |
| | 0 | 1378 | | out int decLeftoverLength); |
| | | 1379 | | |
| | 0 | 1380 | | if (status.ErrorCode != SecurityStatusPalErrorCode.OK) |
| | 0 | 1381 | | { |
| | | 1382 | | // Anything other than success here means there's nothing to drain — the PAL |
| | | 1383 | | // is genuinely waiting on wire bytes. Surface as WantRead; fatal errors will |
| | | 1384 | | // resurface on the next regular Decrypt call with real ciphertext. |
| | 0 | 1385 | | return TlsOperationStatus.NeedMoreData; |
| | | 1386 | | } |
| | | 1387 | | |
| | 0 | 1388 | | int produced = decBytesWritten + decLeftoverLength; |
| | 0 | 1389 | | if (produced == 0) |
| | 0 | 1390 | | { |
| | 0 | 1391 | | return TlsOperationStatus.NeedMoreData; |
| | | 1392 | | } |
| | | 1393 | | |
| | 0 | 1394 | | if (produced > plaintext.Length) |
| | 0 | 1395 | | { |
| | 0 | 1396 | | throw new InvalidOperationException( |
| | 0 | 1397 | | SR.Format(SR.net_tlssession_plaintext_buffer_too_small, produced, plaintext.Length)); |
| | | 1398 | | } |
| | | 1399 | | |
| | 0 | 1400 | | if (decLeftoverLength > 0) |
| | 0 | 1401 | | { |
| | | 1402 | | // PAL stashed overflow in the (empty) input span — impossible here, but mirror |
| | | 1403 | | // the main Decrypt path for symmetry. With Span<byte>.Empty as input, the OpenSSL |
| | | 1404 | | // PAL has nowhere to stash leftover and won't take this path. |
| | 0 | 1405 | | _decryptScratch.AsSpan(decLeftoverOffset, decLeftoverLength) |
| | 0 | 1406 | | .CopyTo(plaintext.Slice(decBytesWritten)); |
| | 0 | 1407 | | } |
| | | 1408 | | |
| | 0 | 1409 | | bytesWritten = produced; |
| | 0 | 1410 | | return TlsOperationStatus.Complete; |
| | 0 | 1411 | | } |
| | | 1412 | | |
| | | 1413 | | // ── Post-handshake auth ────────────────────────────────────────── |
| | | 1414 | | |
| | | 1415 | | /// <summary> |
| | | 1416 | | /// Server-side: requests a client certificate from the peer after the |
| | | 1417 | | /// initial handshake has completed. On TLS 1.3 this issues a |
| | | 1418 | | /// post-handshake authentication CertificateRequest; on TLS 1.2 it |
| | | 1419 | | /// initiates a renegotiation. |
| | | 1420 | | /// </summary> |
| | | 1421 | | /// <remarks> |
| | | 1422 | | /// <para> |
| | | 1423 | | /// The session is created with client certificates optional |
| | | 1424 | | /// (<c>ClientCertificateRequired == false</c>); this method promotes the |
| | | 1425 | | /// requirement for the post-handshake exchange, mirroring |
| | | 1426 | | /// <see cref="SslStream.NegotiateClientCertificateAsync(System.Threading.CancellationToken)"/>. |
| | | 1427 | | /// </para> |
| | | 1428 | | /// <para> |
| | | 1429 | | /// The generated handshake bytes are staged into the pending-output |
| | | 1430 | | /// buffer (drained into <paramref name="ciphertext"/>). The caller must |
| | | 1431 | | /// send them to the peer and then drive the second handshake to |
| | | 1432 | | /// completion via <see cref="TlsBufferSession.Handshake"/>, |
| | | 1433 | | /// exactly like the initial handshake: it re-surfaces |
| | | 1434 | | /// <see cref="TlsOperationStatus.NeedsCertificateValidation"/> (re-running the |
| | | 1435 | | /// remote-certificate validation callback) and finally returns |
| | | 1436 | | /// <see cref="TlsOperationStatus.Complete"/>. Once validation is accepted the |
| | | 1437 | | /// peer certificate becomes observable via <see cref="GetRemoteCertificate"/>. |
| | | 1438 | | /// </para> |
| | | 1439 | | /// </remarks> |
| | | 1440 | | private protected TlsOperationStatus RequestClientCertificateBufferedCore(Span<byte> ciphertext, out int bytesWr |
| | 0 | 1441 | | { |
| | 0 | 1442 | | ThrowIfDisposed(); |
| | 0 | 1443 | | ThrowIfContextNotSet(); |
| | | 1444 | | // Like Read/Write, post-handshake client authentication is a top-level session |
| | | 1445 | | // operation: if the previous handshake surfaced NeedsCertificateValidation the |
| | | 1446 | | // caller must record the result (or observe the recorded fault) before starting it. |
| | 0 | 1447 | | ThrowIfPendingExternalValidation(); |
| | 0 | 1448 | | bytesWritten = 0; |
| | | 1449 | | |
| | | 1450 | | // Post-handshake client authentication is a server-only operation. Enforce the role |
| | | 1451 | | // guard before the Apple platform check so client-session misuse consistently surfaces |
| | | 1452 | | // InvalidOperationException on every platform rather than PlatformNotSupportedException. |
| | 0 | 1453 | | if (!_context!.IsServer) |
| | 0 | 1454 | | { |
| | 0 | 1455 | | throw new InvalidOperationException(SR.net_tlssession_request_client_cert_server_only); |
| | | 1456 | | } |
| | | 1457 | | |
| | | 1458 | | #if TARGET_APPLE |
| | | 1459 | | // SecureTransport does not expose a post-handshake client-authentication |
| | | 1460 | | // path, and Network.framework does not provide renegotiation primitives. |
| | | 1461 | | throw new PlatformNotSupportedException(SR.net_ssl_renegotiate_not_supported); |
| | | 1462 | | #else |
| | 0 | 1463 | | if (!_postHandshakeAuthActive) |
| | 0 | 1464 | | { |
| | 0 | 1465 | | if (!_isHandshakeComplete || _securityContext == null || _securityContext.IsInvalid) |
| | 0 | 1466 | | { |
| | 0 | 1467 | | throw new InvalidOperationException(SR.net_tlssession_handshake_not_complete); |
| | | 1468 | | } |
| | | 1469 | | |
| | | 1470 | | // Match SslStream.RenegotiateAsync: promote the client-certificate |
| | | 1471 | | // requirement for the post-handshake exchange even when the initial |
| | | 1472 | | // handshake was negotiated with RemoteCertRequired == false. This flips |
| | | 1473 | | // the MutualAuth context flag so the TLS 1.2 renegotiation / TLS 1.3 |
| | | 1474 | | // post-handshake CertificateRequest actually asks for the client cert. |
| | 0 | 1475 | | _options.RemoteCertRequired = true; |
| | | 1476 | | |
| | 0 | 1477 | | ProtocolToken token = SslStreamPal.Renegotiate( |
| | 0 | 1478 | | ref ActiveCredentialsRef(), |
| | 0 | 1479 | | ref _securityContext!, |
| | 0 | 1480 | | _options); |
| | 0 | 1481 | | bool staged = false; |
| | | 1482 | | try |
| | 0 | 1483 | | { |
| | | 1484 | | // NoRenegotiation means no request can be made (e.g. a TLS 1.3 client that didn't offer |
| | | 1485 | | // post-handshake authentication, or renegotiation disabled in the OpenSSL configuration), |
| | | 1486 | | // not a failure: nothing is staged, so the session stays in its completed state below. |
| | 0 | 1487 | | bool noRenegotiation = token.Status.ErrorCode == SecurityStatusPalErrorCode.NoRenegotiation; |
| | 0 | 1488 | | if (token.Failed && !noRenegotiation) |
| | 0 | 1489 | | { |
| | 0 | 1490 | | throw new AuthenticationException(SR.net_auth_SSPI, token.GetException()); |
| | | 1491 | | } |
| | | 1492 | | |
| | 0 | 1493 | | if (token.Size > 0 && !noRenegotiation) |
| | 0 | 1494 | | { |
| | 0 | 1495 | | Debug.Assert(token.Payload != null); |
| | 0 | 1496 | | AppendPending(new ReadOnlySpan<byte>(token.Payload, 0, token.Size)); |
| | 0 | 1497 | | staged = true; |
| | 0 | 1498 | | } |
| | 0 | 1499 | | } |
| | | 1500 | | finally |
| | 0 | 1501 | | { |
| | 0 | 1502 | | token.ReleasePayload(); |
| | 0 | 1503 | | } |
| | | 1504 | | |
| | 0 | 1505 | | if (!staged) |
| | 0 | 1506 | | { |
| | | 1507 | | // The PAL produced no renegotiation request (e.g. the peer |
| | | 1508 | | // declined with NoRenegotiation). Leave the session in its |
| | | 1509 | | // completed state; there is nothing for the caller to drive. |
| | 0 | 1510 | | return TlsOperationStatus.Complete; |
| | | 1511 | | } |
| | | 1512 | | |
| | | 1513 | | // Re-arm the handshake state machine so the caller drives the second |
| | | 1514 | | // handshake to completion via Handshake(), exactly like the initial |
| | | 1515 | | // handshake. HandshakeBufferedCore short-circuits to Complete while an |
| | | 1516 | | // already-complete session has resolved external validation, so both |
| | | 1517 | | // flags must be reset here for it to re-enter the PAL and re-surface |
| | | 1518 | | // NeedsCertificateValidation. |
| | 0 | 1519 | | _isHandshakeComplete = false; |
| | 0 | 1520 | | _externalValidationResolved = false; |
| | 0 | 1521 | | _postHandshakeAuthActive = true; |
| | 0 | 1522 | | } |
| | | 1523 | | |
| | 0 | 1524 | | bytesWritten = DrainTo(ciphertext); |
| | 0 | 1525 | | if (_pendingBuffer.ActiveLength > 0) |
| | 0 | 1526 | | { |
| | 0 | 1527 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 1528 | | } |
| | | 1529 | | |
| | | 1530 | | // All staged request bytes handed off; from here the caller drives the |
| | | 1531 | | // second handshake through Handshake(). |
| | 0 | 1532 | | _postHandshakeAuthActive = false; |
| | 0 | 1533 | | return TlsOperationStatus.Complete; |
| | | 1534 | | #endif |
| | 0 | 1535 | | } |
| | | 1536 | | |
| | | 1537 | | // ── Shutdown ────────────────────────────────────────────────────── |
| | | 1538 | | |
| | | 1539 | | private bool _shutdownSent; |
| | | 1540 | | |
| | | 1541 | | /// <summary> |
| | | 1542 | | /// Initiates a TLS close_notify shutdown and stages the resulting alert |
| | | 1543 | | /// record into the pending-output buffer (drained into <paramref name="ciphertext"/>). |
| | | 1544 | | /// Subsequent calls drain any remaining shutdown output. |
| | | 1545 | | /// </summary> |
| | | 1546 | | /// <remarks> |
| | | 1547 | | /// Returns <see cref="TlsOperationStatus.DestinationTooSmall"/> if the caller must |
| | | 1548 | | /// drain more output before the shutdown record is fully written; |
| | | 1549 | | /// otherwise <see cref="TlsOperationStatus.Closed"/> once all bytes have |
| | | 1550 | | /// been handed to the caller. |
| | | 1551 | | /// </remarks> |
| | | 1552 | | private protected TlsOperationStatus ShutdownBufferedCore(Span<byte> ciphertext, out int bytesWritten) |
| | 0 | 1553 | | { |
| | 0 | 1554 | | ThrowIfDisposed(); |
| | 0 | 1555 | | bytesWritten = 0; |
| | | 1556 | | |
| | 0 | 1557 | | if (_securityContext == null || _securityContext.IsInvalid) |
| | 0 | 1558 | | { |
| | 0 | 1559 | | return TlsOperationStatus.Closed; |
| | | 1560 | | } |
| | | 1561 | | |
| | 0 | 1562 | | if (!_shutdownSent) |
| | 0 | 1563 | | { |
| | 0 | 1564 | | _shutdownSent = true; |
| | | 1565 | | |
| | 0 | 1566 | | SecurityStatusPal status = SslStreamPal.ApplyShutdownToken(_securityContext); |
| | 0 | 1567 | | if (status.ErrorCode != SecurityStatusPalErrorCode.OK) |
| | 0 | 1568 | | { |
| | 0 | 1569 | | throw new IOException(SR.net_io_encrypt, SslStreamPal.GetException(status)); |
| | | 1570 | | } |
| | | 1571 | | |
| | | 1572 | | // Drive one step to extract the close_notify bytes the PAL queued |
| | | 1573 | | // into the underlying BIO. Input is empty; we only care about |
| | | 1574 | | // any output the PAL produces. |
| | 0 | 1575 | | ProtocolToken token = default; |
| | 0 | 1576 | | token.RentBuffer = true; |
| | | 1577 | | try |
| | 0 | 1578 | | { |
| | 0 | 1579 | | if (_context!.IsServer) |
| | 0 | 1580 | | { |
| | 0 | 1581 | | token = SslStreamPal.AcceptSecurityContext( |
| | 0 | 1582 | | ref ActiveCredentialsRef(), |
| | 0 | 1583 | | ref _securityContext, |
| | 0 | 1584 | | ReadOnlySpan<byte>.Empty, |
| | 0 | 1585 | | out _, |
| | 0 | 1586 | | _options); |
| | 0 | 1587 | | } |
| | | 1588 | | else |
| | 0 | 1589 | | { |
| | 0 | 1590 | | string hostName = TargetHostNameHelper.NormalizeHostName(_options.TargetHost); |
| | 0 | 1591 | | token = SslStreamPal.InitializeSecurityContext( |
| | 0 | 1592 | | ref ActiveCredentialsRef(), |
| | 0 | 1593 | | ref _securityContext, |
| | 0 | 1594 | | hostName, |
| | 0 | 1595 | | ReadOnlySpan<byte>.Empty, |
| | 0 | 1596 | | out _, |
| | 0 | 1597 | | _options); |
| | 0 | 1598 | | } |
| | | 1599 | | |
| | 0 | 1600 | | if (token.Size > 0) |
| | 0 | 1601 | | { |
| | 0 | 1602 | | Debug.Assert(token.Payload != null); |
| | 0 | 1603 | | AppendPending(new ReadOnlySpan<byte>(token.Payload, 0, token.Size)); |
| | 0 | 1604 | | } |
| | 0 | 1605 | | } |
| | | 1606 | | finally |
| | 0 | 1607 | | { |
| | 0 | 1608 | | token.ReleasePayload(); |
| | 0 | 1609 | | } |
| | 0 | 1610 | | } |
| | | 1611 | | |
| | 0 | 1612 | | bytesWritten = DrainTo(ciphertext); |
| | 0 | 1613 | | return _pendingBuffer.ActiveLength > 0 ? TlsOperationStatus.DestinationTooSmall : TlsOperationStatus.Closed; |
| | 0 | 1614 | | } |
| | | 1615 | | |
| | | 1616 | | // ── Pending output ──────────────────────────────────────────────── |
| | | 1617 | | |
| | | 1618 | | private protected TlsOperationStatus DrainPendingOutputCore(Span<byte> ciphertext, out int bytesWritten) |
| | 0 | 1619 | | { |
| | 0 | 1620 | | ThrowIfDisposed(); |
| | 0 | 1621 | | bytesWritten = DrainTo(ciphertext); |
| | 0 | 1622 | | return _pendingBuffer.ActiveLength > 0 ? TlsOperationStatus.DestinationTooSmall : TlsOperationStatus.Complet |
| | 0 | 1623 | | } |
| | | 1624 | | |
| | | 1625 | | // ── Internals ───────────────────────────────────────────────────── |
| | | 1626 | | |
| | | 1627 | | private void AppendPending(ReadOnlySpan<byte> data) |
| | 0 | 1628 | | { |
| | 0 | 1629 | | if (data.IsEmpty) |
| | 0 | 1630 | | { |
| | 0 | 1631 | | return; |
| | | 1632 | | } |
| | | 1633 | | |
| | 0 | 1634 | | _pendingBuffer.EnsureAvailableSpace(data.Length); |
| | 0 | 1635 | | data.CopyTo(_pendingBuffer.AvailableSpan); |
| | 0 | 1636 | | _pendingBuffer.Commit(data.Length); |
| | 0 | 1637 | | } |
| | | 1638 | | |
| | | 1639 | | private int DrainTo(Span<byte> output) |
| | 0 | 1640 | | { |
| | 0 | 1641 | | int n = Math.Min(output.Length, _pendingBuffer.ActiveLength); |
| | 0 | 1642 | | if (n == 0) |
| | 0 | 1643 | | { |
| | 0 | 1644 | | return 0; |
| | | 1645 | | } |
| | | 1646 | | |
| | 0 | 1647 | | _pendingBuffer.ActiveSpan.Slice(0, n).CopyTo(output); |
| | 0 | 1648 | | _pendingBuffer.Discard(n); |
| | 0 | 1649 | | return n; |
| | 0 | 1650 | | } |
| | | 1651 | | |
| | | 1652 | | private void EnsureDecryptScratch(int size) |
| | 0 | 1653 | | { |
| | 0 | 1654 | | if (_decryptScratch == null || _decryptScratch.Length < size) |
| | 0 | 1655 | | { |
| | 0 | 1656 | | if (_decryptScratch != null) |
| | 0 | 1657 | | { |
| | 0 | 1658 | | ArrayPool<byte>.Shared.Return(_decryptScratch); |
| | 0 | 1659 | | } |
| | 0 | 1660 | | _decryptScratch = ArrayPool<byte>.Shared.Rent(size); |
| | 0 | 1661 | | } |
| | 0 | 1662 | | } |
| | | 1663 | | |
| | 0 | 1664 | | private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 1665 | | |
| | | 1666 | | private void ThrowIfContextNotSet() |
| | 0 | 1667 | | { |
| | 0 | 1668 | | if (_context is null) |
| | 0 | 1669 | | { |
| | 0 | 1670 | | throw new InvalidOperationException(SR.net_ssl_tlssession_context_not_set); |
| | | 1671 | | } |
| | 0 | 1672 | | } |
| | | 1673 | | |
| | | 1674 | | // Server-side: parses the ClientHello and returns a populated |
| | | 1675 | | // SslClientHelloInfo (SNI + supported versions), or null if more bytes |
| | | 1676 | | // are needed or the record is not a ClientHello. Used by the |
| | | 1677 | | // deferred-options path; does not mutate session state. |
| | | 1678 | | private static SslClientHelloInfo? TryParseClientHello(ReadOnlySpan<byte> input, out int frameLength) |
| | 0 | 1679 | | { |
| | 0 | 1680 | | frameLength = 0; |
| | 0 | 1681 | | TlsFrameHelper.TlsFrameInfo frameInfo = default; |
| | 0 | 1682 | | if (!TlsFrameHelper.TryGetFrameInfo(input, ref frameInfo)) |
| | 0 | 1683 | | { |
| | 0 | 1684 | | return null; |
| | | 1685 | | } |
| | | 1686 | | |
| | 0 | 1687 | | if (frameInfo.HandshakeType != TlsHandshakeType.ClientHello) |
| | 0 | 1688 | | { |
| | 0 | 1689 | | return null; |
| | | 1690 | | } |
| | | 1691 | | |
| | 0 | 1692 | | frameLength = frameInfo.Header.Length; |
| | 0 | 1693 | | return new SslClientHelloInfo(frameInfo.TargetName ?? string.Empty, frameInfo.SupportedVersions); |
| | 0 | 1694 | | } |
| | | 1695 | | |
| | | 1696 | | // Server-side SNI + certificate selection. Parses the ClientHello to |
| | | 1697 | | // extract the server_name extension (SNI) and, if a |
| | | 1698 | | // ServerCertificateSelectionCallback was supplied and no static |
| | | 1699 | | // CertificateContext has been resolved yet, invokes the callback to |
| | | 1700 | | // pick the cert. Mirrors the path SslStream takes in |
| | | 1701 | | // ReceiveBlobAsync/AcquireServerCredentials. |
| | | 1702 | | private bool ResolveServerCertificateFromClientHello(ReadOnlySpan<byte> input) |
| | 0 | 1703 | | { |
| | 0 | 1704 | | TlsFrameHelper.TlsFrameInfo frameInfo = default; |
| | 0 | 1705 | | if (!TlsFrameHelper.TryGetFrameInfo(input, ref frameInfo)) |
| | 0 | 1706 | | { |
| | 0 | 1707 | | return false; |
| | | 1708 | | } |
| | | 1709 | | |
| | 0 | 1710 | | if (frameInfo.HandshakeType != TlsHandshakeType.ClientHello) |
| | 0 | 1711 | | { |
| | 0 | 1712 | | return true; |
| | | 1713 | | } |
| | | 1714 | | |
| | 0 | 1715 | | if (!string.IsNullOrEmpty(frameInfo.TargetName)) |
| | 0 | 1716 | | { |
| | 0 | 1717 | | _sessionTargetHost = frameInfo.TargetName; |
| | 0 | 1718 | | } |
| | | 1719 | | |
| | 0 | 1720 | | ServerCertificateSelectionCallback? selector = _options.ServerCertSelectionDelegate; |
| | 0 | 1721 | | if (selector is null || SessionCertificateContext is not null) |
| | 0 | 1722 | | { |
| | 0 | 1723 | | return true; |
| | | 1724 | | } |
| | | 1725 | | |
| | 0 | 1726 | | X509Certificate? selected = selector(this, _sessionTargetHost); |
| | 0 | 1727 | | if (selected is null) |
| | 0 | 1728 | | { |
| | 0 | 1729 | | throw new AuthenticationException(SR.net_ssl_io_no_server_cert); |
| | | 1730 | | } |
| | | 1731 | | |
| | 0 | 1732 | | X509Certificate2? withKey = SslStream.FindCertificateWithPrivateKey(this, isServer: true, selected); |
| | 0 | 1733 | | if (withKey is null) |
| | 0 | 1734 | | { |
| | 0 | 1735 | | throw new AuthenticationException(SR.net_ssl_io_no_server_cert); |
| | | 1736 | | } |
| | | 1737 | | |
| | 0 | 1738 | | SetSessionCertificateContext( |
| | 0 | 1739 | | SslStreamCertificateContext.Create(withKey, additionalCertificates: null, offline: false, trust: null, n |
| | 0 | 1740 | | takeOwnership: true); |
| | 0 | 1741 | | return true; |
| | 0 | 1742 | | } |
| | | 1743 | | |
| | | 1744 | | // ── Internal surface for the SslStream wedge (Linux/FreeBSD only) ─ |
| | | 1745 | | |
| | | 1746 | | // Direct accessors used by SslStream to mirror state into its own fields after |
| | | 1747 | | // each handshake step. Both handles are owned by this TlsSession; SslStream |
| | | 1748 | | // observes them via the mirror but does not dispose them. |
| | | 1749 | | // Set by the SslStream wedge: SslStream owns the validation flow and will |
| | | 1750 | | // invoke the user callback itself with the SslStream as the sender. Skipping |
| | | 1751 | | // here avoids invoking the callback twice and avoids handing TlsSession to |
| | | 1752 | | // user code that expects SslStream. |
| | | 1753 | | internal bool SuppressInternalCertificateValidation |
| | | 1754 | | { |
| | | 1755 | | get => _suppressInternalCertificateValidation; |
| | 0 | 1756 | | set => _suppressInternalCertificateValidation = value; |
| | | 1757 | | } |
| | | 1758 | | |
| | 0 | 1759 | | internal TlsSecurityContext? SecurityContext => _securityContext; |
| | | 1760 | | internal TlsContext Context => _context!; |
| | | 1761 | | internal SafeFreeCredentials? CredentialsHandle |
| | | 1762 | | { |
| | 0 | 1763 | | get => ActiveCredentialsRef(); |
| | | 1764 | | set |
| | 0 | 1765 | | { |
| | 0 | 1766 | | if (_sessionCredentialsHandle is not null) |
| | 0 | 1767 | | { |
| | 0 | 1768 | | _sessionCredentialsHandle = value; |
| | 0 | 1769 | | } |
| | | 1770 | | else |
| | 0 | 1771 | | { |
| | 0 | 1772 | | _context!.CredentialsHandle = value; |
| | 0 | 1773 | | } |
| | 0 | 1774 | | } |
| | | 1775 | | } |
| | | 1776 | | |
| | | 1777 | | // Returns a ref to the credentials handle this session should use for its next |
| | | 1778 | | // PAL call. When _sessionCredentialsHandle is set (via SetClientCertificateContext), |
| | | 1779 | | // it takes precedence; otherwise the shared TlsContext.CredentialsHandle is used. |
| | | 1780 | | // Class instance refs have unrestricted lifetime, no [UnscopedRef] needed. |
| | | 1781 | | private ref SafeFreeCredentials? ActiveCredentialsRef() |
| | 0 | 1782 | | => ref (_sessionCredentialsHandle is not null |
| | 0 | 1783 | | ? ref _sessionCredentialsHandle |
| | 0 | 1784 | | : ref _context!.CredentialsHandle); |
| | | 1785 | | |
| | | 1786 | | // SslStream's GenerateToken replacement. Drives one ASC/ISC step via PAL and |
| | | 1787 | | // updates internal handshake-complete state. Returns the raw PAL token so the |
| | | 1788 | | // caller can preserve existing ProtocolToken-based plumbing (alerts, error |
| | | 1789 | | // mapping, NetEventSource). |
| | | 1790 | | internal ProtocolToken HandshakeStepForSslStream(ReadOnlySpan<byte> input, out int bytesConsumed) |
| | 0 | 1791 | | { |
| | 0 | 1792 | | ThrowIfDisposed(); |
| | | 1793 | | |
| | | 1794 | | ProtocolToken token; |
| | 0 | 1795 | | if (_context!.IsServer) |
| | 0 | 1796 | | { |
| | 0 | 1797 | | token = SslStreamPal.AcceptSecurityContext( |
| | 0 | 1798 | | ref ActiveCredentialsRef(), |
| | 0 | 1799 | | ref _securityContext, |
| | 0 | 1800 | | input, |
| | 0 | 1801 | | out bytesConsumed, |
| | 0 | 1802 | | _options); |
| | 0 | 1803 | | } |
| | | 1804 | | else |
| | 0 | 1805 | | { |
| | 0 | 1806 | | string hostName = TargetHostNameHelper.NormalizeHostName(_options.TargetHost); |
| | 0 | 1807 | | token = SslStreamPal.InitializeSecurityContext( |
| | 0 | 1808 | | ref ActiveCredentialsRef(), |
| | 0 | 1809 | | ref _securityContext, |
| | 0 | 1810 | | hostName, |
| | 0 | 1811 | | input, |
| | 0 | 1812 | | out bytesConsumed, |
| | 0 | 1813 | | _options); |
| | 0 | 1814 | | } |
| | | 1815 | | |
| | 0 | 1816 | | if (token.Status.ErrorCode == SecurityStatusPalErrorCode.OK) |
| | 0 | 1817 | | { |
| | 0 | 1818 | | OnHandshakeCompleted(); |
| | 0 | 1819 | | } |
| | | 1820 | | |
| | 0 | 1821 | | return token; |
| | 0 | 1822 | | } |
| | | 1823 | | |
| | | 1824 | | private void OnHandshakeCompleted() |
| | 0 | 1825 | | { |
| | 0 | 1826 | | _isHandshakeComplete = true; |
| | 0 | 1827 | | SslStreamPal.QueryContextConnectionInfo(_securityContext!, ref _connectionInfo); |
| | 0 | 1828 | | SslStreamPal.QueryContextStreamSizes(_securityContext!, out StreamSizes streamSizes); |
| | 0 | 1829 | | _headerSize = streamSizes.Header; |
| | 0 | 1830 | | _trailerSize = streamSizes.Trailer; |
| | 0 | 1831 | | if (streamSizes.MaximumMessage > 0) |
| | 0 | 1832 | | { |
| | 0 | 1833 | | _maxDataSize = Math.Min(streamSizes.MaximumMessage, MaxRecordPlaintext); |
| | 0 | 1834 | | } |
| | | 1835 | | |
| | | 1836 | | // Invoke remote-certificate validation callback (mirrors SslStream). |
| | | 1837 | | // Client: always validate the server cert. |
| | | 1838 | | // Server: always suspend so the caller's RemoteCertificateValidationCallback runs |
| | | 1839 | | // (it must see optional client certs and the no-cert case alike — only the |
| | | 1840 | | // RemoteCertificateNotAvailable error is suppressed in VerifyRemoteCertificateCore |
| | | 1841 | | // when there is no user callback and RemoteCertRequired is false). |
| | 0 | 1842 | | if (_suppressInternalCertificateValidation) |
| | 0 | 1843 | | { |
| | 0 | 1844 | | return; |
| | | 1845 | | } |
| | | 1846 | | |
| | | 1847 | | // If the caller already resolved validation via a prior suspension |
| | | 1848 | | // (defensive — current OpenSSL/SChannel paths only suspend once via |
| | | 1849 | | // the post-handshake hook below), don't re-suspend here. |
| | 0 | 1850 | | if (_externalValidationResolved) |
| | 0 | 1851 | | { |
| | 0 | 1852 | | return; |
| | | 1853 | | } |
| | | 1854 | | |
| | 0 | 1855 | | CaptureRemoteCertificateForExternalValidation(); |
| | 0 | 1856 | | } |
| | | 1857 | | |
| | | 1858 | | // Capture the peer certificate and chain so the caller can perform validation |
| | | 1859 | | // out of band. Keeps the cert in _externalPendingCert (not _remoteCertificate) |
| | | 1860 | | // so VerifyRemoteCertificateCore's renegotiation shortcut doesn't dispose it |
| | | 1861 | | // when AcceptWithDefaultValidation runs. |
| | | 1862 | | private void CaptureRemoteCertificateForExternalValidation() |
| | 0 | 1863 | | { |
| | 0 | 1864 | | X509ChainPolicy? chainPolicy = _options.CertificateChainPolicy?.Clone(); |
| | 0 | 1865 | | int preexistingExtraCertsCount = chainPolicy?.ExtraStore.Count ?? 0; |
| | 0 | 1866 | | X509Chain? chain = null; |
| | 0 | 1867 | | X509Certificate2Collection? intermediates = null; |
| | | 1868 | | |
| | | 1869 | | try |
| | 0 | 1870 | | { |
| | 0 | 1871 | | _externalPendingCert = CertificateValidationPal.GetRemoteCertificate( |
| | 0 | 1872 | | _securityContext, ref chain, chainPolicy); |
| | | 1873 | | |
| | 0 | 1874 | | if (chain is not null) |
| | 0 | 1875 | | { |
| | 0 | 1876 | | X509Certificate2Collection extraStore = chain.ChainPolicy.ExtraStore; |
| | 0 | 1877 | | while (extraStore.Count > preexistingExtraCertsCount) |
| | 0 | 1878 | | { |
| | 0 | 1879 | | X509Certificate2 certificate = extraStore[preexistingExtraCertsCount]; |
| | 0 | 1880 | | extraStore.RemoveAt(preexistingExtraCertsCount); |
| | | 1881 | | |
| | 0 | 1882 | | bool transferred = false; |
| | | 1883 | | try |
| | 0 | 1884 | | { |
| | 0 | 1885 | | if (_externalPendingCert is null || |
| | 0 | 1886 | | !certificate.RawDataMemory.Span.SequenceEqual(_externalPendingCert.RawDataMemory.Span)) |
| | 0 | 1887 | | { |
| | 0 | 1888 | | (intermediates ??= new X509Certificate2Collection()).Add(certificate); |
| | 0 | 1889 | | transferred = true; |
| | 0 | 1890 | | } |
| | 0 | 1891 | | } |
| | | 1892 | | finally |
| | 0 | 1893 | | { |
| | 0 | 1894 | | if (!transferred) |
| | 0 | 1895 | | { |
| | 0 | 1896 | | certificate.Dispose(); |
| | 0 | 1897 | | } |
| | 0 | 1898 | | } |
| | 0 | 1899 | | } |
| | 0 | 1900 | | } |
| | | 1901 | | |
| | 0 | 1902 | | _externalRemoteCertificates = intermediates; |
| | 0 | 1903 | | intermediates = null; |
| | 0 | 1904 | | } |
| | | 1905 | | finally |
| | 0 | 1906 | | { |
| | 0 | 1907 | | if (intermediates is not null) |
| | 0 | 1908 | | { |
| | 0 | 1909 | | foreach (X509Certificate2 certificate in intermediates) |
| | 0 | 1910 | | { |
| | 0 | 1911 | | certificate.Dispose(); |
| | 0 | 1912 | | } |
| | 0 | 1913 | | } |
| | | 1914 | | |
| | 0 | 1915 | | if (chain is not null) |
| | 0 | 1916 | | { |
| | 0 | 1917 | | X509Certificate2Collection extraStore = chain.ChainPolicy.ExtraStore; |
| | 0 | 1918 | | while (extraStore.Count > preexistingExtraCertsCount) |
| | 0 | 1919 | | { |
| | 0 | 1920 | | X509Certificate2 certificate = extraStore[preexistingExtraCertsCount]; |
| | 0 | 1921 | | extraStore.RemoveAt(preexistingExtraCertsCount); |
| | 0 | 1922 | | certificate.Dispose(); |
| | 0 | 1923 | | } |
| | | 1924 | | |
| | 0 | 1925 | | chain.Dispose(); |
| | 0 | 1926 | | } |
| | 0 | 1927 | | } |
| | | 1928 | | |
| | 0 | 1929 | | _externalValidationPending = true; |
| | 0 | 1930 | | } |
| | | 1931 | | |
| | | 1932 | | // Acquire the SafeFreeCredentials the PAL needs for the first ASC/ISC |
| | | 1933 | | // call. OpenSSL handles credential acquisition lazily inside the PAL, |
| | | 1934 | | // but SChannel rejects ASC/ISC with a null credentials handle. |
| | | 1935 | | // |
| | | 1936 | | // Server requires a pre-set CertificateContext (or one resolved via |
| | | 1937 | | // ServerCertSelectionDelegate above); the client connects anonymously. |
| | | 1938 | | // SslSessionsCache, the legacy CertSelectionDelegate, and client |
| | | 1939 | | // certificate selection are not yet integrated. |
| | | 1940 | | private void EnsureCredentialsAcquired() |
| | 0 | 1941 | | { |
| | | 1942 | | // If SetContext or SetClientCertificateContext already produced a |
| | | 1943 | | // session-local handle, ActiveCredentialsRef() will route the PAL |
| | | 1944 | | // through it. Skip touching the shared TlsContext.CredentialsHandle |
| | | 1945 | | // to avoid racing with concurrent sessions on the same context. |
| | 0 | 1946 | | if (_sessionCredentialsHandle is not null) |
| | 0 | 1947 | | { |
| | 0 | 1948 | | return; |
| | | 1949 | | } |
| | | 1950 | | |
| | 0 | 1951 | | if (_context!.CredentialsHandle is not null) |
| | 0 | 1952 | | { |
| | 0 | 1953 | | return; |
| | | 1954 | | } |
| | | 1955 | | |
| | | 1956 | | // Multiple sessions on the same TlsContext can call EnsureCredentialsAcquired |
| | | 1957 | | // concurrently and each see CredentialsHandle == null. Atomically install |
| | | 1958 | | // ours; if another session beat us to it, dispose the loser to avoid a leak. |
| | | 1959 | | // Non-Windows PALs return null here (OpenSSL has no cred handle concept); the |
| | | 1960 | | // CompareExchange is a no-op in that case. |
| | 0 | 1961 | | SafeFreeCredentials? acquired = SslStreamPal.AcquireCredentialsHandle(_options, false); |
| | 0 | 1962 | | if (System.Threading.Interlocked.CompareExchange(ref _context!.CredentialsHandle, acquired, null) is not nul |
| | 0 | 1963 | | { |
| | 0 | 1964 | | acquired?.Dispose(); |
| | 0 | 1965 | | } |
| | 0 | 1966 | | } |
| | | 1967 | | |
| | | 1968 | | // Feed a decrypted post-handshake message (e.g. TLS 1.3 NewSessionTicket |
| | | 1969 | | // or KeyUpdate) back through ASC/ISC so SChannel updates its internal |
| | | 1970 | | // state. The PAL may or may not produce a reply token; if it does, stage |
| | | 1971 | | // it for the caller to send on the next drain. |
| | | 1972 | | private void ProcessPostHandshakeMessage(ReadOnlySpan<byte> data) |
| | 0 | 1973 | | { |
| | 0 | 1974 | | if (data.IsEmpty) |
| | 0 | 1975 | | { |
| | 0 | 1976 | | return; |
| | | 1977 | | } |
| | | 1978 | | |
| | 0 | 1979 | | ProtocolToken token = default; |
| | 0 | 1980 | | token.RentBuffer = true; |
| | | 1981 | | try |
| | 0 | 1982 | | { |
| | 0 | 1983 | | if (_context!.IsServer) |
| | 0 | 1984 | | { |
| | 0 | 1985 | | token = SslStreamPal.AcceptSecurityContext( |
| | 0 | 1986 | | ref ActiveCredentialsRef(), |
| | 0 | 1987 | | ref _securityContext, |
| | 0 | 1988 | | data, |
| | 0 | 1989 | | out _, |
| | 0 | 1990 | | _options); |
| | 0 | 1991 | | } |
| | | 1992 | | else |
| | 0 | 1993 | | { |
| | 0 | 1994 | | string hostName = TargetHostNameHelper.NormalizeHostName(_options.TargetHost); |
| | 0 | 1995 | | token = SslStreamPal.InitializeSecurityContext( |
| | 0 | 1996 | | ref ActiveCredentialsRef(), |
| | 0 | 1997 | | ref _securityContext, |
| | 0 | 1998 | | hostName, |
| | 0 | 1999 | | data, |
| | 0 | 2000 | | out _, |
| | 0 | 2001 | | _options); |
| | 0 | 2002 | | } |
| | | 2003 | | |
| | 0 | 2004 | | if (token.Size > 0) |
| | 0 | 2005 | | { |
| | 0 | 2006 | | Debug.Assert(token.Payload != null); |
| | 0 | 2007 | | AppendPending(new ReadOnlySpan<byte>(token.Payload, 0, token.Size)); |
| | 0 | 2008 | | } |
| | 0 | 2009 | | } |
| | | 2010 | | finally |
| | 0 | 2011 | | { |
| | 0 | 2012 | | token.ReleasePayload(); |
| | 0 | 2013 | | } |
| | 0 | 2014 | | } |
| | | 2015 | | |
| | | 2016 | | // ── Socket-bound I/O ───────────────────────────────────────────── |
| | | 2017 | | // |
| | | 2018 | | // These methods are only valid when the session was created via |
| | | 2019 | | // Create(TlsContext, SafeSocketHandle). They drive ciphertext on the |
| | | 2020 | | // bound non-blocking socket and translate WouldBlock into WantRead/ |
| | | 2021 | | // WantWrite back to the caller so a select/epoll/IOCP-like loop can |
| | | 2022 | | // schedule the next attempt. |
| | | 2023 | | |
| | | 2024 | | private const int SocketScratchSize = MaxRecordPlaintext + 256; |
| | | 2025 | | |
| | | 2026 | | private void ThrowIfNotSocketBound() |
| | 0 | 2027 | | { |
| | 0 | 2028 | | if (_socketHandle is null) |
| | 0 | 2029 | | { |
| | 0 | 2030 | | throw new InvalidOperationException(SR.net_tlssession_not_socket_bound); |
| | | 2031 | | } |
| | 0 | 2032 | | } |
| | | 2033 | | |
| | | 2034 | | // Drains any TLS bytes that we previously failed to fully send into the |
| | | 2035 | | // socket. Returns true if pending output is now empty, false if the |
| | | 2036 | | // socket would block (WantWrite should be surfaced). |
| | | 2037 | | private bool TryDrainPendingToSocket(out SocketError lastError) |
| | 0 | 2038 | | { |
| | 0 | 2039 | | lastError = SocketError.Success; |
| | 0 | 2040 | | while (_pendingBuffer.ActiveLength > 0) |
| | 0 | 2041 | | { |
| | 0 | 2042 | | int sent = _socket!.Send( |
| | 0 | 2043 | | _pendingBuffer.ActiveReadOnlySpan, |
| | 0 | 2044 | | SocketFlags.None, |
| | 0 | 2045 | | out SocketError err); |
| | 0 | 2046 | | lastError = err; |
| | 0 | 2047 | | if (sent > 0) |
| | 0 | 2048 | | { |
| | 0 | 2049 | | _pendingBuffer.Discard(sent); |
| | 0 | 2050 | | if (_pendingBuffer.ActiveLength == 0) |
| | 0 | 2051 | | { |
| | 0 | 2052 | | return true; |
| | | 2053 | | } |
| | 0 | 2054 | | continue; |
| | | 2055 | | } |
| | 0 | 2056 | | return false; |
| | | 2057 | | } |
| | 0 | 2058 | | return true; |
| | 0 | 2059 | | } |
| | | 2060 | | |
| | | 2061 | | private protected TlsOperationStatus HandshakeSocketCore() |
| | 0 | 2062 | | { |
| | 0 | 2063 | | ThrowIfDisposed(); |
| | 0 | 2064 | | ThrowIfContextNotSet(); |
| | 0 | 2065 | | ThrowIfNotSocketBound(); |
| | | 2066 | | |
| | 0 | 2067 | | if (_isHandshakeComplete && !_externalValidationPending && !_externalValidationResolved) |
| | 0 | 2068 | | { |
| | 0 | 2069 | | return TlsOperationStatus.Complete; |
| | | 2070 | | } |
| | | 2071 | | |
| | 0 | 2072 | | TlsOperationStatus? fast = null; |
| | | 2073 | | TryFastHandshake(ref fast); |
| | 0 | 2074 | | if (fast.HasValue) |
| | 0 | 2075 | | { |
| | 0 | 2076 | | return fast.Value; |
| | | 2077 | | } |
| | | 2078 | | |
| | | 2079 | | TryPeekClientHello(ref fast); |
| | 0 | 2080 | | if (fast.HasValue) |
| | 0 | 2081 | | { |
| | 0 | 2082 | | return fast.Value; |
| | | 2083 | | } |
| | | 2084 | | |
| | 0 | 2085 | | _socketInBuffer.EnsureAvailableSpace(SocketScratchSize); |
| | 0 | 2086 | | byte[] scratch = ArrayPool<byte>.Shared.Rent(SocketScratchSize); |
| | | 2087 | | try |
| | 0 | 2088 | | { |
| | 0 | 2089 | | while (true) |
| | 0 | 2090 | | { |
| | 0 | 2091 | | if (_pendingBuffer.ActiveLength > 0) |
| | 0 | 2092 | | { |
| | 0 | 2093 | | if (!TryDrainPendingToSocket(out SocketError drainErr)) |
| | 0 | 2094 | | { |
| | 0 | 2095 | | if (drainErr == SocketError.WouldBlock) |
| | 0 | 2096 | | { |
| | 0 | 2097 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 2098 | | } |
| | 0 | 2099 | | throw new SocketException((int)drainErr); |
| | | 2100 | | } |
| | 0 | 2101 | | } |
| | | 2102 | | |
| | 0 | 2103 | | TlsOperationStatus status = HandshakeBufferedCore( |
| | 0 | 2104 | | _socketInBuffer.ActiveReadOnlySpan, |
| | 0 | 2105 | | scratch, |
| | 0 | 2106 | | out int consumed, |
| | 0 | 2107 | | out int produced); |
| | | 2108 | | |
| | 0 | 2109 | | if (consumed > 0) |
| | 0 | 2110 | | { |
| | 0 | 2111 | | _socketInBuffer.Discard(consumed); |
| | 0 | 2112 | | } |
| | | 2113 | | |
| | 0 | 2114 | | if (produced > 0) |
| | 0 | 2115 | | { |
| | 0 | 2116 | | int offset = 0; |
| | 0 | 2117 | | while (offset < produced) |
| | 0 | 2118 | | { |
| | 0 | 2119 | | int sent = _socket!.Send( |
| | 0 | 2120 | | new ReadOnlySpan<byte>(scratch, offset, produced - offset), |
| | 0 | 2121 | | SocketFlags.None, |
| | 0 | 2122 | | out SocketError sendErr); |
| | 0 | 2123 | | if (sent > 0) |
| | 0 | 2124 | | { |
| | 0 | 2125 | | offset += sent; |
| | 0 | 2126 | | continue; |
| | | 2127 | | } |
| | 0 | 2128 | | if (sendErr == SocketError.WouldBlock) |
| | 0 | 2129 | | { |
| | | 2130 | | // Stash the unsent tail so the next call resumes the drain. |
| | 0 | 2131 | | AppendPending(new ReadOnlySpan<byte>(scratch, offset, produced - offset)); |
| | 0 | 2132 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 2133 | | } |
| | 0 | 2134 | | throw new SocketException((int)sendErr); |
| | | 2135 | | } |
| | 0 | 2136 | | } |
| | | 2137 | | |
| | 0 | 2138 | | switch (status) |
| | | 2139 | | { |
| | | 2140 | | case TlsOperationStatus.Complete: |
| | 0 | 2141 | | return TlsOperationStatus.Complete; |
| | | 2142 | | |
| | | 2143 | | case TlsOperationStatus.NeedMoreData: |
| | | 2144 | | // Should not happen with conservative scratch sizing, but guard. |
| | 0 | 2145 | | _socketInBuffer.EnsureAvailableSpace(1); |
| | 0 | 2146 | | int received = _socket!.Receive( |
| | 0 | 2147 | | _socketInBuffer.AvailableSpan, |
| | 0 | 2148 | | SocketFlags.None, |
| | 0 | 2149 | | out SocketError recvErr); |
| | 0 | 2150 | | if (received > 0) |
| | 0 | 2151 | | { |
| | 0 | 2152 | | _socketInBuffer.Commit(received); |
| | 0 | 2153 | | continue; |
| | | 2154 | | } |
| | 0 | 2155 | | if (recvErr == SocketError.WouldBlock) |
| | 0 | 2156 | | { |
| | 0 | 2157 | | return TlsOperationStatus.NeedMoreData; |
| | | 2158 | | } |
| | 0 | 2159 | | if (received == 0) |
| | 0 | 2160 | | { |
| | 0 | 2161 | | return TlsOperationStatus.Closed; |
| | | 2162 | | } |
| | 0 | 2163 | | throw new SocketException((int)recvErr); |
| | | 2164 | | |
| | | 2165 | | case TlsOperationStatus.DestinationTooSmall: |
| | | 2166 | | // Output is staged; loop drains it on next iteration. |
| | 0 | 2167 | | continue; |
| | | 2168 | | |
| | | 2169 | | default: |
| | 0 | 2170 | | return status; |
| | | 2171 | | } |
| | | 2172 | | } |
| | | 2173 | | } |
| | | 2174 | | finally |
| | 0 | 2175 | | { |
| | 0 | 2176 | | ArrayPool<byte>.Shared.Return(scratch); |
| | 0 | 2177 | | } |
| | 0 | 2178 | | } |
| | | 2179 | | |
| | | 2180 | | private protected TlsOperationStatus ReadSocketCore(Span<byte> buffer, out int bytesRead) |
| | 0 | 2181 | | { |
| | 0 | 2182 | | ThrowIfDisposed(); |
| | 0 | 2183 | | ThrowIfNotSocketBound(); |
| | | 2184 | | // A prior handshake may have surfaced NeedsCertificateValidation whose result the |
| | | 2185 | | // caller has not recorded yet. The buffered Read core gates on this, but the socket |
| | | 2186 | | // core can return NeedMoreData off a non-blocking recv before ever reaching it, so |
| | | 2187 | | // apply the guard here to stay consistent with the buffered path and socket Write. |
| | 0 | 2188 | | ThrowIfPendingExternalValidation(); |
| | 0 | 2189 | | bytesRead = 0; |
| | | 2190 | | |
| | 0 | 2191 | | if (!_isHandshakeComplete) |
| | 0 | 2192 | | { |
| | 0 | 2193 | | throw new InvalidOperationException(SR.net_tlssession_handshake_not_complete); |
| | | 2194 | | } |
| | | 2195 | | |
| | 0 | 2196 | | TlsOperationStatus? fast = null; |
| | | 2197 | | TryFastRead(buffer, ref bytesRead, ref fast); |
| | 0 | 2198 | | if (fast.HasValue) |
| | 0 | 2199 | | { |
| | 0 | 2200 | | return fast.Value; |
| | | 2201 | | } |
| | | 2202 | | |
| | 0 | 2203 | | _socketInBuffer.EnsureAvailableSpace(SocketScratchSize); |
| | | 2204 | | |
| | 0 | 2205 | | while (true) |
| | 0 | 2206 | | { |
| | 0 | 2207 | | if (_socketInBuffer.ActiveLength > 0) |
| | 0 | 2208 | | { |
| | 0 | 2209 | | TlsOperationStatus status = ReadBufferedCore( |
| | 0 | 2210 | | _socketInBuffer.ActiveReadOnlySpan, |
| | 0 | 2211 | | buffer, |
| | 0 | 2212 | | out int consumed, |
| | 0 | 2213 | | out int produced); |
| | | 2214 | | |
| | 0 | 2215 | | if (consumed > 0) |
| | 0 | 2216 | | { |
| | 0 | 2217 | | _socketInBuffer.Discard(consumed); |
| | 0 | 2218 | | } |
| | | 2219 | | |
| | 0 | 2220 | | bytesRead = produced; |
| | | 2221 | | |
| | 0 | 2222 | | if (status == TlsOperationStatus.Complete && produced > 0) |
| | 0 | 2223 | | { |
| | 0 | 2224 | | return TlsOperationStatus.Complete; |
| | | 2225 | | } |
| | 0 | 2226 | | if (status == TlsOperationStatus.Closed) |
| | 0 | 2227 | | { |
| | 0 | 2228 | | return TlsOperationStatus.Closed; |
| | | 2229 | | } |
| | 0 | 2230 | | if (status == TlsOperationStatus.Complete && produced == 0) |
| | 0 | 2231 | | { |
| | | 2232 | | // Post-handshake message consumed; loop to try more. |
| | 0 | 2233 | | continue; |
| | | 2234 | | } |
| | 0 | 2235 | | if (status != TlsOperationStatus.NeedMoreData) |
| | 0 | 2236 | | { |
| | 0 | 2237 | | return status; |
| | | 2238 | | } |
| | | 2239 | | // WantRead: fall through to socket recv. |
| | 0 | 2240 | | } |
| | | 2241 | | |
| | 0 | 2242 | | _socketInBuffer.EnsureAvailableSpace(1); |
| | 0 | 2243 | | int received = _socket!.Receive( |
| | 0 | 2244 | | _socketInBuffer.AvailableSpan, |
| | 0 | 2245 | | SocketFlags.None, |
| | 0 | 2246 | | out SocketError recvErr); |
| | 0 | 2247 | | if (received > 0) |
| | 0 | 2248 | | { |
| | 0 | 2249 | | _socketInBuffer.Commit(received); |
| | 0 | 2250 | | continue; |
| | | 2251 | | } |
| | 0 | 2252 | | if (recvErr == SocketError.WouldBlock) |
| | 0 | 2253 | | { |
| | 0 | 2254 | | return TlsOperationStatus.NeedMoreData; |
| | | 2255 | | } |
| | 0 | 2256 | | if (received == 0) |
| | 0 | 2257 | | { |
| | 0 | 2258 | | return TlsOperationStatus.Closed; |
| | | 2259 | | } |
| | 0 | 2260 | | throw new SocketException((int)recvErr); |
| | | 2261 | | } |
| | 0 | 2262 | | } |
| | | 2263 | | |
| | | 2264 | | private protected TlsOperationStatus WriteSocketCore(ReadOnlySpan<byte> buffer, out int bytesWritten) |
| | 0 | 2265 | | { |
| | 0 | 2266 | | ThrowIfDisposed(); |
| | 0 | 2267 | | ThrowIfNotSocketBound(); |
| | | 2268 | | // Empty-buffer writes short-circuit before reaching WriteBufferedCore's guard, so |
| | | 2269 | | // gate on any unrecorded external-validation result here too, matching socket Read. |
| | 0 | 2270 | | ThrowIfPendingExternalValidation(); |
| | 0 | 2271 | | bytesWritten = 0; |
| | | 2272 | | |
| | 0 | 2273 | | if (!_isHandshakeComplete) |
| | 0 | 2274 | | { |
| | 0 | 2275 | | throw new InvalidOperationException(SR.net_tlssession_handshake_not_complete); |
| | | 2276 | | } |
| | | 2277 | | |
| | 0 | 2278 | | TlsOperationStatus? fast = null; |
| | | 2279 | | TryFastWrite(buffer, ref bytesWritten, ref fast); |
| | 0 | 2280 | | if (fast.HasValue) |
| | 0 | 2281 | | { |
| | 0 | 2282 | | return fast.Value; |
| | | 2283 | | } |
| | | 2284 | | |
| | | 2285 | | // Drain any previously stashed ciphertext first. |
| | 0 | 2286 | | if (_pendingBuffer.ActiveLength > 0) |
| | 0 | 2287 | | { |
| | 0 | 2288 | | if (!TryDrainPendingToSocket(out SocketError drainErr)) |
| | 0 | 2289 | | { |
| | 0 | 2290 | | if (drainErr == SocketError.WouldBlock) |
| | 0 | 2291 | | { |
| | 0 | 2292 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 2293 | | } |
| | 0 | 2294 | | throw new SocketException((int)drainErr); |
| | | 2295 | | } |
| | 0 | 2296 | | } |
| | | 2297 | | |
| | 0 | 2298 | | if (buffer.IsEmpty) |
| | 0 | 2299 | | { |
| | 0 | 2300 | | return TlsOperationStatus.Complete; |
| | | 2301 | | } |
| | | 2302 | | |
| | 0 | 2303 | | byte[] scratch = ArrayPool<byte>.Shared.Rent(SocketScratchSize); |
| | | 2304 | | try |
| | 0 | 2305 | | { |
| | 0 | 2306 | | int totalConsumed = 0; |
| | 0 | 2307 | | while (totalConsumed < buffer.Length) |
| | 0 | 2308 | | { |
| | 0 | 2309 | | TlsOperationStatus encStatus = WriteBufferedCore( |
| | 0 | 2310 | | buffer.Slice(totalConsumed), |
| | 0 | 2311 | | scratch, |
| | 0 | 2312 | | out int consumed, |
| | 0 | 2313 | | out int produced); |
| | | 2314 | | |
| | 0 | 2315 | | totalConsumed += consumed; |
| | | 2316 | | |
| | 0 | 2317 | | if (produced > 0) |
| | 0 | 2318 | | { |
| | 0 | 2319 | | int offset = 0; |
| | 0 | 2320 | | while (offset < produced) |
| | 0 | 2321 | | { |
| | 0 | 2322 | | int sent = _socket!.Send( |
| | 0 | 2323 | | new ReadOnlySpan<byte>(scratch, offset, produced - offset), |
| | 0 | 2324 | | SocketFlags.None, |
| | 0 | 2325 | | out SocketError sendErr); |
| | 0 | 2326 | | if (sent > 0) |
| | 0 | 2327 | | { |
| | 0 | 2328 | | offset += sent; |
| | 0 | 2329 | | continue; |
| | | 2330 | | } |
| | 0 | 2331 | | if (sendErr == SocketError.WouldBlock) |
| | 0 | 2332 | | { |
| | 0 | 2333 | | AppendPending(new ReadOnlySpan<byte>(scratch, offset, produced - offset)); |
| | 0 | 2334 | | bytesWritten = totalConsumed; |
| | 0 | 2335 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 2336 | | } |
| | 0 | 2337 | | throw new SocketException((int)sendErr); |
| | | 2338 | | } |
| | 0 | 2339 | | } |
| | | 2340 | | |
| | 0 | 2341 | | if (encStatus == TlsOperationStatus.DestinationTooSmall) |
| | 0 | 2342 | | { |
| | | 2343 | | // Pending output owed; resume next call. |
| | 0 | 2344 | | bytesWritten = totalConsumed; |
| | 0 | 2345 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 2346 | | } |
| | 0 | 2347 | | if (encStatus != TlsOperationStatus.Complete) |
| | 0 | 2348 | | { |
| | 0 | 2349 | | bytesWritten = totalConsumed; |
| | 0 | 2350 | | return encStatus; |
| | | 2351 | | } |
| | 0 | 2352 | | if (consumed == 0) |
| | 0 | 2353 | | { |
| | | 2354 | | // Nothing more to do (shouldn't happen with non-empty buffer). |
| | 0 | 2355 | | break; |
| | | 2356 | | } |
| | 0 | 2357 | | } |
| | | 2358 | | |
| | 0 | 2359 | | bytesWritten = totalConsumed; |
| | 0 | 2360 | | return TlsOperationStatus.Complete; |
| | | 2361 | | } |
| | | 2362 | | finally |
| | 0 | 2363 | | { |
| | 0 | 2364 | | ArrayPool<byte>.Shared.Return(scratch); |
| | 0 | 2365 | | } |
| | 0 | 2366 | | } |
| | | 2367 | | |
| | | 2368 | | // Simple driver that runs a buffered "output-only" op (Shutdown / |
| | | 2369 | | // RequestClientCertificate) and drains its staged ciphertext to the socket. |
| | | 2370 | | private TlsOperationStatus DriveBufferedOpOverSocket(Func<Span<byte>, (TlsOperationStatus status, int written)> |
| | 0 | 2371 | | { |
| | 0 | 2372 | | ThrowIfDisposed(); |
| | 0 | 2373 | | ThrowIfNotSocketBound(); |
| | | 2374 | | |
| | | 2375 | | // Drain any leftover pending output before staging new bytes. |
| | 0 | 2376 | | if (_pendingBuffer.ActiveLength > 0) |
| | 0 | 2377 | | { |
| | 0 | 2378 | | if (!TryDrainPendingToSocket(out SocketError leftoverErr)) |
| | 0 | 2379 | | { |
| | 0 | 2380 | | if (leftoverErr == SocketError.WouldBlock) |
| | 0 | 2381 | | { |
| | 0 | 2382 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 2383 | | } |
| | 0 | 2384 | | throw new SocketException((int)leftoverErr); |
| | | 2385 | | } |
| | 0 | 2386 | | } |
| | | 2387 | | |
| | 0 | 2388 | | byte[] scratch = ArrayPool<byte>.Shared.Rent(SocketScratchSize); |
| | | 2389 | | try |
| | 0 | 2390 | | { |
| | 0 | 2391 | | (TlsOperationStatus status, int written) = op(scratch); |
| | 0 | 2392 | | if (written > 0) |
| | 0 | 2393 | | { |
| | 0 | 2394 | | int offset = 0; |
| | 0 | 2395 | | while (offset < written) |
| | 0 | 2396 | | { |
| | 0 | 2397 | | int sent = _socket!.Send( |
| | 0 | 2398 | | new ReadOnlySpan<byte>(scratch, offset, written - offset), |
| | 0 | 2399 | | SocketFlags.None, |
| | 0 | 2400 | | out SocketError sendErr); |
| | 0 | 2401 | | if (sent > 0) |
| | 0 | 2402 | | { |
| | 0 | 2403 | | offset += sent; |
| | 0 | 2404 | | continue; |
| | | 2405 | | } |
| | 0 | 2406 | | if (sendErr == SocketError.WouldBlock) |
| | 0 | 2407 | | { |
| | 0 | 2408 | | AppendPending(new ReadOnlySpan<byte>(scratch, offset, written - offset)); |
| | 0 | 2409 | | return TlsOperationStatus.DestinationTooSmall; |
| | | 2410 | | } |
| | 0 | 2411 | | throw new SocketException((int)sendErr); |
| | | 2412 | | } |
| | 0 | 2413 | | } |
| | 0 | 2414 | | return status; |
| | | 2415 | | } |
| | | 2416 | | finally |
| | 0 | 2417 | | { |
| | 0 | 2418 | | ArrayPool<byte>.Shared.Return(scratch); |
| | 0 | 2419 | | } |
| | 0 | 2420 | | } |
| | | 2421 | | |
| | | 2422 | | private protected TlsOperationStatus ShutdownSocketCore() |
| | 0 | 2423 | | => DriveBufferedOpOverSocket(dest => |
| | 0 | 2424 | | { |
| | 0 | 2425 | | TlsOperationStatus s = ShutdownBufferedCore(dest, out int w); |
| | 0 | 2426 | | return (s, w); |
| | 0 | 2427 | | }); |
| | | 2428 | | |
| | | 2429 | | private protected TlsOperationStatus RequestClientCertificateSocketCore() |
| | 0 | 2430 | | { |
| | 0 | 2431 | | ThrowIfDisposed(); |
| | 0 | 2432 | | ThrowIfNotSocketBound(); |
| | | 2433 | | // The fd fast path below bypasses the buffered core, so apply the external-validation |
| | | 2434 | | // guard here as well, matching the other socket-bound operations. |
| | 0 | 2435 | | ThrowIfPendingExternalValidation(); |
| | | 2436 | | |
| | 0 | 2437 | | TlsOperationStatus? fast = null; |
| | | 2438 | | TryFastRequestClientCertificate(ref fast); |
| | 0 | 2439 | | if (fast.HasValue) |
| | 0 | 2440 | | { |
| | 0 | 2441 | | return fast.Value; |
| | | 2442 | | } |
| | | 2443 | | |
| | 0 | 2444 | | return DriveBufferedOpOverSocket(dest => |
| | 0 | 2445 | | { |
| | 0 | 2446 | | TlsOperationStatus s = RequestClientCertificateBufferedCore(dest, out int w); |
| | 0 | 2447 | | return (s, w); |
| | 0 | 2448 | | }); |
| | 0 | 2449 | | } |
| | | 2450 | | |
| | | 2451 | | // Platform hooks. Implemented by the OpenSSL partial (TlsSession.OpenSsl.cs) |
| | | 2452 | | // to bind the socket fd directly to the SSL object and drive ciphertext |
| | | 2453 | | // through OpenSSL. On Windows (SChannel) these are no-ops and the buffered |
| | | 2454 | | // ProcessHandshake/Encrypt/Decrypt path above is used unchanged. |
| | | 2455 | | partial void EnableNativeSocketBinding(SafeSocketHandle socket, ref bool nativeBindingEnabled); |
| | | 2456 | | partial void TryFastHandshake(ref TlsOperationStatus? result); |
| | | 2457 | | partial void TryFastRequestClientCertificate(ref TlsOperationStatus? result); |
| | | 2458 | | partial void TryPeekClientHello(ref TlsOperationStatus? result); |
| | | 2459 | | partial void TryFastRead(Span<byte> buffer, ref int bytesRead, ref TlsOperationStatus? result); |
| | | 2460 | | partial void TryFastWrite(ReadOnlySpan<byte> buffer, ref int bytesWritten, ref TlsOperationStatus? result); |
| | | 2461 | | |
| | | 2462 | | // Fires at the end of SetContext. Platforms with a deferred-server |
| | | 2463 | | // fast path (OpenSSL socket-bound sessions) use this hook to activate |
| | | 2464 | | // native binding now that server options are known. |
| | | 2465 | | partial void OnServerContextSet(); |
| | | 2466 | | |
| | | 2467 | | // Fires from Dispose so the OpenSSL partial can release the peek BIO if the |
| | | 2468 | | // session is disposed before its ownership is transferred to an SSL* handle. |
| | | 2469 | | partial void OnDispose(); |
| | | 2470 | | |
| | | 2471 | | // Fires from GetClientHelloBytes so the OpenSSL partial can return a span |
| | | 2472 | | // over the socket-replay BIO's retained peek buffer. No-op on the buffered |
| | | 2473 | | // path; the getter falls back to the managed byte[] copy. |
| | | 2474 | | partial void TryGetNativeClientHelloBytes(ref ReadOnlySpan<byte> bytes); |
| | | 2475 | | |
| | | 2476 | | public void Dispose() |
| | 0 | 2477 | | { |
| | 0 | 2478 | | if (_disposed) |
| | 0 | 2479 | | { |
| | 0 | 2480 | | return; |
| | | 2481 | | } |
| | 0 | 2482 | | _disposed = true; |
| | | 2483 | | |
| | 0 | 2484 | | DisposeExternalRemoteCertificates(); |
| | 0 | 2485 | | _externalPendingCert?.Dispose(); |
| | 0 | 2486 | | _externalPendingCert = null; |
| | | 2487 | | |
| | 0 | 2488 | | _securityContext?.Dispose(); |
| | 0 | 2489 | | _securityContext = null; |
| | | 2490 | | |
| | | 2491 | | // Disposes the underlying SafeSocketHandle as well (ownership transferred at Create). |
| | 0 | 2492 | | if (_socket is not null) |
| | 0 | 2493 | | { |
| | 0 | 2494 | | _socket.Dispose(); |
| | 0 | 2495 | | _socket = null; |
| | 0 | 2496 | | } |
| | | 2497 | | else |
| | 0 | 2498 | | { |
| | 0 | 2499 | | _socketHandle?.Dispose(); |
| | 0 | 2500 | | } |
| | 0 | 2501 | | _socketHandle = null; |
| | | 2502 | | |
| | 0 | 2503 | | if (_ownsOptions) |
| | 0 | 2504 | | { |
| | 0 | 2505 | | _options.Dispose(); |
| | 0 | 2506 | | } |
| | | 2507 | | |
| | 0 | 2508 | | _pendingBuffer.Dispose(); |
| | 0 | 2509 | | if (_decryptScratch != null) |
| | 0 | 2510 | | { |
| | 0 | 2511 | | ArrayPool<byte>.Shared.Return(_decryptScratch); |
| | 0 | 2512 | | _decryptScratch = null; |
| | 0 | 2513 | | } |
| | 0 | 2514 | | _socketInBuffer.Dispose(); |
| | | 2515 | | |
| | | 2516 | | // Release the session-local credentials handle acquired by |
| | | 2517 | | // SetContext / SetClientCertificateContext. The shared handle on |
| | | 2518 | | // _context is owned by TlsContext and released with it. |
| | 0 | 2519 | | _sessionCredentialsHandle?.Dispose(); |
| | 0 | 2520 | | _sessionCredentialsHandle = null; |
| | | 2521 | | |
| | | 2522 | | // Release the session-owned CertificateContext (only true when we built |
| | | 2523 | | // one via the server-cert-selector path). Caller-provided contexts and the |
| | | 2524 | | // template context inherited from TlsContext are not disposed here. |
| | 0 | 2525 | | if (_ownsSessionCertificateContext && _sessionCertificateContext is not null) |
| | 0 | 2526 | | { |
| | 0 | 2527 | | _sessionCertificateContext.ReleaseResources(); |
| | 0 | 2528 | | } |
| | 0 | 2529 | | _sessionCertificateContext = null; |
| | 0 | 2530 | | _ownsSessionCertificateContext = false; |
| | | 2531 | | |
| | | 2532 | | OnDispose(); |
| | 0 | 2533 | | } |
| | | 2534 | | } |
| | | 2535 | | } |
| | | 2536 | | |