为什么服务允许客户使用错误(但可信)的证书?

Why does service allow clients with wrong (but trusted) certificates?

我将预期的客户端证书设置为 "A":

        host.Credentials.ClientCertificate.SetCertificate("A", ...);
        host.Credentials.ServiceCertificate.SetCertificate("B", ...);

绑定:

new NetTcpBinding
                    {
                        Security =
                        {
                            Mode = SecurityMode.TransportWithMessageCredential,
                            Transport = { ProtectionLevel = ProtectionLevel.EncryptAndSign },
                            Message = { ClientCredentialType = MessageCredentialType.Certificate }
                        }
                    }

我希望服务器只允许具有证书 "A" 的客户端。但它也允许其他受信任的证书。我已将客户端 app.config 更改为使用 "B" 而不是 "A",它仍然有效!

我的设置有什么问题?

host.Credentials.ClientCertificate.SetCertificate("A", ...);

并不意味着只允许证书A的客户端连接。

如果您只想允许某些类型的证书,则需要检查服务器端的 CertificateValidator。

看看: https://msdn.microsoft.com/en-us/library/aa354512%28v=vs.110%29.aspx

如果您有更多问题,请随时问我

编辑:

public class CustomX509CertificateValidator : X509CertificateValidator
{
  public override void Validate ( X509Certificate2 certificate )
  {
   // Only accept self-issued certificates for example
   if (certificate.Subject != certificate.Issuer)
     throw new Exception("Certificate is not self-issued");
   }
}

然后:

serviceHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
serviceHost.Credentials.ClientCertificate.Authentication.CustomCertificateValidator = new CustomX509CertificateValidator();