Search code examples
c#.netsslsystem.net.httpwebrequest

Establishing SSL\TLS connection (X509Chain.Build()) takes too long


I found that when I use HttpWebRequest to establish SSL\TLS connection, it takes near 30s when calling

  request.GetRequestStream()

when I've enabled tracing with stacktrace enabled, I found that 2s goes to find poxy, so I've disabled it in app.config:

<system.net>
 <defaultProxy enabled="false" useDefaultCredentials="false">
  <proxy/>
  <bypasslist/>
  <module/>
 </defaultProxy>
</system.net>

Next point that takes near 28s was in

   at System.Net.Security.SecureChannel.AcquireClientCredentials(Byte[]& thumbPrint)

After examinig method body I found call to X509Chain.Build() and it took near 25s to build certificate chain.

Interesting thing that when you constructs new HttpWebReqest and tries again (without app restart), it took several ms to perform request.

Could anyone suggest what to do? Caching request is not an option, it should be fast from app run.

Update:

I found call that takes 30s in the X509Chain.BuildChain(), it is:

if (!CAPISafe.CertGetCertificateChain(hChainEngine, pCertContext, ref pTime, invalidHandle, ref cert_chain_para, dwFlags, IntPtr.Zero, ref ppChainContext))

The method declared in CAPISafe as:

[DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool CertGetCertificateChain([In] IntPtr hChainEngine, [In] SafeCertContextHandle pCertContext, [In] ref System.Runtime.InteropServices.ComTypes.FILETIME pTime, [In] SafeCertStoreHandle hAdditionalStore, [In] ref CAPIBase.CERT_CHAIN_PARA pChainPara, [In] uint dwFlags, [In] IntPtr pvReserved, [In, Out] ref SafeCertChainHandle ppChainContext);

So, it is Crypto API function CertGetCertificateChain Still have no idea, what to do next...

Update:

I have tried to disable CRL and OCSP checks, still no effect:

  1. Add to App.config

    <runtime>
      <generatePublisherEvidence enabled="false"/>
    </runtime>
    
  2. Machine-wide: Control Panel -> Internet Options -> Advanced -> Under security, uncheck the Check for publisher's certificate revocation option

  3. In registry:

    [HKEY_USERS\S-1-5-20\Software\Microsoft\Windows\CurrentVersion\WinTrust\Trust Providers\Software Publishing] "State"=dword:00023e00


Solution

  • Finally I found the roots of the issue. I enabled CAPI2 logging in Event Log and found NetworkTimeoutException when trying to download Certificate Trust List from:

    http://www.download.windowsupdate.com/msdownload/update/v3/static/trustedr/en/authrootstl.cab

    So, that was Firewall issue. You can read blogpost about investigation process and techniques used.