Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I encounter RemoteCertificateNameMismatch every time?

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?

like image 702
Eric Avatar asked Dec 25 '22 06:12

Eric


1 Answers

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

like image 155
cynic Avatar answered Feb 13 '23 22:02

cynic