I'm using the following code to accept bad server certificates:
ServicePointManager.ServerCertificateValidationCallback = delegate(object s,
X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
Debug.WriteLine("Returned certificate valid");
return true;
}
And this code to make a request:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://localhost/test");
req.Timeout = 5000;
try {
Debug.WriteLine("Checking...");
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Debug.WriteLine("Done");
}
catch
{
Debug.WriteLine("Error");
//error
}
The first time I run this request it waits 5 seconds and then throws a timeout exception. The validation callback is executed successfully right before the timeout, and I can see that the correct (invalid) certificate is passed in.
If I increase the timeout to 15 seconds, it takes 15 seconds for the callback to be executed and then the request times out.
Subsequent requests (without restarting the program) have a success rate of about 90%. (10% of them timeout; the others return almost instantly.) What is going on here?
EDIT: If I unplug my network connection all the requests return successfully which makes me think it must be trying to contact a CA or something... Why does it timeout instead of throwing a security exception and how can I stop this?
EDIT 2: I commented out the timeout @ScottSmith's suggestion and all the requests now succeed! Sometimes they succeed before the old timeout period which is really confusing me. Is there any way I can get .net to stop trying to validate the certificate behind the scenes?
EDIT 3: I found a forum post that I think explains my problem. Look at the final post on this page: http://www.pcreview.co.uk/forums/ie-going-very-slow-if-certificate-isnt-valid-t735059.html I used wireshark and once the request is issued, 3 DNS queries for www.download.windowsupdate.com are made. Once they fail (since the computer is not connected to the internet) the certificate validation callback is finally called and the request completes. If anyone can come up with a way to disable this behavior that would be amazing.