Why do I encounter RemoteCertificateNameMismatch every time?

11,016

You need to pass "google.com" to AuthenticateAsClient - it expects the server name as a parameter, not your client name.

Share:
11,016
Eric
Author by

Eric

Clear, concise, effective, fun, flexible, articulate: I deliver results without supervision.

Updated on June 27, 2022

Comments

  • Eric
    Eric almost 2 years

    Consider the following complete program:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace RemoteCertNameMismatchDiagnosis
    {
    class Program
    {
        private static bool AcceptAllCertificates(object sender, X509Certificate certificate,
                                                                                            X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            Console.WriteLine(sslPolicyErrors.ToString());
            return true;
        }
    
        static void Main(string[] args)
        {
            TcpClient client;
            SslStream sslStream;
    
            bool acceptAnyCert = false;
    
            client = new TcpClient("google.com", 443);
            if (acceptAnyCert)
                sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(AcceptAllCertificates), null);
            else
                sslStream = new SslStream(client.GetStream(), false);
    
            try
            {
                sslStream.AuthenticateAsClient("test client");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.ReadLine();
        }
      }
    }
    

    It reports this exception

    System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

    every time. By changing acceptAnyCert to true on line 26, I can have it output this

    RemoteCertificateNameMismatch

    , leading me to believe it's unhappy with the name on the cert.

    This behavior persists whether I point at google.com, amazon.com, or anywhere else on line 28. I don't think google, microsoft, and amazon all have defective certificates. What am I doing wrong?