5

I'm using an HttpWebRequest object to access a web service via an HTTP POST. Part of the requirement is that I:

  1. Verify that the URL in the certificate matches the URL I'm posting to
  2. Verify that the certificate is valid and trusted
  3. Verify that the certificate has not expired

Does HttpWebRequest automatically handle that for me? I'd assume that if any of these conditions came up, I'd get the standard "could not establish trust relationship for the SSL/TLS secure channel" exception.

Kevin Pang
  • 41,172
  • 38
  • 121
  • 173

2 Answers2

3

Yes, HttpWebRequest automatically handles these:

  1. Verify that the URL in the certificate matches the URL you're posting to
  2. Verify that the certificate is valid and trusted
  3. Verify that the certificate has not expired

You have to use code like this if you want to disable this functionality.

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
David
  • 34,223
  • 3
  • 62
  • 80
0

Not really. You still have to check if a sslpolicyerror is returned using a callback function. Make sure to test your implementation against url like this https://rootkit.com/ which is using a self-singed cert.

    void InitPhase()
{
    // Override automatic validation of SSL server certificates.
    ServicePointManager.ServerCertificateValidationCallback =
           ValidateServerCertficate;
}
private static bool ValidateServerCertficate(
        object sender,
        X509Certificate cert,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
    {
        // Good certificate.
        return true;
    }

    log.DebugFormat("SSL certificate error: {0}", sslPolicyErrors);

    bool certMatch = false; // Assume failure
    byte[] certHash = cert.GetCertHash();
    if (certHash.Length == apiCertHash.Length)
    {
        certMatch = true; // Now assume success.
        for (int idx = 0; idx < certHash.Length; idx++)
        {
            if (certHash[idx] != apiCertHash[idx])
            {
                certMatch = false; // No match
                break;
            }
        }
    }

    // Return true => allow unauthenticated server,
    //        false => disallow unauthenticated server.
    return certMatch;
}
rook
  • 66,304
  • 38
  • 162
  • 239
  • What is the 'apiCertHash'? – Oskar Berggren Jun 10 '15 at 13:24
  • @Oskar Berggren used in cert pinning. – rook Jun 16 '15 at 04:20
  • Well, yes, but I don't understand what you mean by "Not really" in response to the question. I believe the SSL policy will verify and fail the connection if any of the three rules stated in the question are broken, even without a callback. The callback would in fact be used to accept the connection despite any of those checks failing. – Oskar Berggren Jun 16 '15 at 08:54