diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs index 97ffc38aaf841a..9b5825ac70df0d 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs @@ -35,13 +35,24 @@ internal static SslPolicyErrors VerifyCertificateProperties( X509Certificate2? result = null; - SafeX509ChainHandle chainHandle = securityContext switch + SafeX509ChainHandle? chainHandle = securityContext switch { - SafeDeleteNwContext nwContext => nwContext.PeerX509ChainHandle!, + SafeDeleteNwContext nwContext => nwContext.PeerX509ChainHandle, SafeDeleteSslContext sslContext => Interop.AppleCrypto.SslCopyCertChain(sslContext.SslContext), _ => throw new ArgumentException("Invalid context type", nameof(securityContext)) }; + if (chainHandle is null || chainHandle.IsInvalid) + { + if (securityContext is SafeDeleteSslContext) + { + chainHandle?.Dispose(); + } + + if (NetEventSource.Log.IsEnabled()) NetEventSource.Log.RemoteCertificate(result); + return result; + } + try { long chainSize = Interop.AppleCrypto.X509ChainGetChainSize(chainHandle);