21

My program contains 2 root certs I know and trust. I have to verify certs of trustcenters and "user" certs issued by the trustcenters which all originate from these 2 root certs.

I use X509Chain class to verify but that only works if the root cert is in the windows certificate store.

I'm looking for a way to verify the certs without importing theeses root certs - somehow tell the X509Chain class that I do trust this root certs and it should check just the certs in the chain and nothing else.

Actual code:

        X509Chain chain = new X509Chain();
        chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
        chain.ChainPolicy.ExtraStore.Add(root); // i do trust this
        chain.ChainPolicy.ExtraStore.Add(trust);
        chain.Build(cert);

Edit: It's a .NET 2.0 Winforms application.

4

5 回答 5

14

我在 dotnet/corefx 上打开了一个问题,他们回复如下:

如果 AllowUnknownCertificateAuthority 是唯一设置的标志,那么 chain.Build()如果

  • 链在自签名证书中正确终止(通过 ExtraStore,或搜索的持久存储)

  • 根据请求的吊销政策,没有任何证书无效

  • 所有证书在(可选)ApplicationPolicy 或 CertificatePolicy 值下均有效

  • 所有证书的 NotBefore 值都在 VerificationTime 之前或之前,并且所有证书的 NotAfter 值在 VerificationTime 之后(在或之前)。

如果未指定该标志,则添加附加约束:

自签名证书必须在系统上注册为受信任的(例如在 LM\Root 存储中)。

所以,Build() 返回 true,你知道存在一个时间有效的非撤销链。此时要做的事情是阅读 chain.ChainElements[chain.ChainElements.Count - 1].Certificate并确定它是否是您信任的证书。我建议与 您在上下文中作为根信任chainRoot.RawDatabyte[]证书进行比较(即逐字节比较,而不是使用指纹值)。

(如果设置了其他标志,则其他约束也会放宽)

所以你应该这样做:

X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.ExtraStore.Add(root);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
var isValid = chain.Build(cert);

var chainRoot = chain.ChainElements[chain.ChainElements.Count - 1].Certificate;
isValid = isValid && chainRoot.RawData.SequenceEqual(root.RawData);
于 2018-06-11T22:57:34.090 回答
9

编辑

多年来,我们发现我在此处发布的原始 X509Chain 解决方案存在几个问题,因为 X509Chain 在某些边缘情况下执行不正确的行为。因此我不再推荐使用 X509Chain 来解决这个问题。此后,我们的产品开始使用 Bouncy Castle 来进行我们所有的证书链验证,它经受住了我们所有的测试并且始终按预期工作。

可以在这里找到我们新解决方案的基础:在 C# 中的 BouncyCastle 中构建证书链

我已经删除了原始答案,所以没有人使用糟糕的安全解决方案。

于 2015-09-30T17:20:02.907 回答
1

获得它的方法是编写自定义验证。

如果您在 WCF 上下文中,则可以通过System.IdentityModel.Selectors.X509CertificateValidator在 web.config 中对 serviceBehavior 对象进行子类化并指定自定义验证来完成:

<serviceBehaviors>
    <behavior name="IdentityService">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceCredentials>
        <clientCertificate>
          <authentication customCertificateValidatorType="SSOUtilities.MatchInstalledCertificateCertificateValidator, SSOUtilities"
            certificateValidationMode="Custom" />
        </clientCertificate>
        <serviceCertificate findValue="CN=SSO ApplicationManagement"
          storeLocation="LocalMachine" storeName="My" />
      </serviceCredentials>
    </behavior>

但是,如果您只是在寻找一种从其他主机接受 SSL 证书的方法,您可以修改 web.config 文件中的 system.net 设置:

下面是一个 X509CertificateValidator 示例,用于测试客户端证书是否存在于 LocalMachine/Personal 存储中。(这不是您需要的,但作为示例可能有用。

using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Security.Cryptography.X509Certificates;

/// <summary>
/// This class can be injected into the WCF validation 
/// mechanism to create more strict certificate validation
/// based on the certificates common name. 
/// </summary>
public class MatchInstalledCertificateCertificateValidator
    : System.IdentityModel.Selectors.X509CertificateValidator
{
    /// <summary>
    /// Initializes a new instance of the MatchInstalledCertificateCertificateValidator class.
    /// </summary>
    public MatchInstalledCertificateCertificateValidator()
    {
    }

    /// <summary>
    /// Validates the certificate. Throws SecurityException if the certificate
    /// does not validate correctly.
    /// </summary>
    /// <param name="certificateToValidate">Certificate to validate</param>
    public override void Validate(X509Certificate2 certificateToValidate)
    {
        var log = SSOLog.GetLogger(this.GetType());
        log.Debug("Validating certificate: "
            + certificateToValidate.SubjectName.Name
            + " (" + certificateToValidate.Thumbprint + ")");

        if (!GetAcceptedCertificates().Where(cert => certificateToValidate.Thumbprint == cert.Thumbprint).Any())
        {
            log.Info(string.Format("Rejecting certificate: {0}, ({1})", certificateToValidate.SubjectName.Name, certificateToValidate.Thumbprint));
            throw new SecurityException("The certificate " + certificateToValidate
                + " with thumprint " + certificateToValidate.Thumbprint
                + " was not found in the certificate store");
        }

        log.Info(string.Format("Accepting certificate: {0}, ({1})", certificateToValidate.SubjectName.Name, certificateToValidate.Thumbprint));
    }

    /// <summary>
    /// Returns all accepted certificates which is the certificates present in 
    /// the LocalMachine/Personal store.
    /// </summary>
    /// <returns>A set of certificates considered valid by the validator</returns>
    private IEnumerable<X509Certificate2> GetAcceptedCertificates()
    {
        X509Store k = new X509Store(StoreName.My, StoreLocation.LocalMachine);

        try
        {
            k.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
            foreach (var cert in k.Certificates)
            {
                yield return cert;
            }
        }
        finally
        {
            k.Close();
        }
    }
}
于 2011-05-23T13:26:24.587 回答
1

如果您知道哪些证书可以是要检查的证书的根证书和中间证书,则可以在对象ChainPolicy.ExtraStore集合中加载根证书和中间证书的公钥。X509Chain

我的任务也是编写一个 Windows 窗体应用程序来安装证书,前提是它是根据我国政府已知的“国家根证书”颁发的。还有数量有限的 CA 被允许颁发证书以验证与国家 Web 服务的连接,所以我有一组有限的证书,它们可以在链中并且可能在目标机器上丢失。我在应用程序的子目录“cert”中收集了 CA 的所有公钥和政府根证书: 链式证书

在 Visual Studio 中,我将目录 cert 添加到解决方案中,并将该目录中的所有文件标记为嵌入式资源。这使我能够在我的 c# 库代码中枚举“受信任”证书的集合,以构建一个链来检查证书,即使未安装颁发者证书也是如此。为此,我为 X509Chain 制作了一个包装类:

private class X509TestChain : X509Chain, IDisposable
{
  public X509TestChain(X509Certificate2 oCert)
    : base(false)
  {
    try
    {
      ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
      ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
      if (!Build(oCert) || (ChainElements.Count <= 1))
      {
        Trace.WriteLine("X509Chain.Build failed with installed certificates.");
        Assembly asmExe = System.Reflection.Assembly.GetEntryAssembly();
        if (asmExe != null)
        {
          string[] asResources = asmExe.GetManifestResourceNames();
          foreach (string sResource in asResources)
          {
            if (sResource.IndexOf(".cert.") >= 0)
            {
              try
              {
                using (Stream str = asmExe.GetManifestResourceStream(sResource))
                using (BinaryReader br = new BinaryReader(str))
                {
                  byte[] abResCert = new byte[str.Length];
                  br.Read(abResCert, 0, abResCert.Length);
                  X509Certificate2 oResCert = new X509Certificate2(abResCert);
                  Trace.WriteLine("Adding extra certificate: " + oResCert.Subject);
                  ChainPolicy.ExtraStore.Add(oResCert);
                }
              }
              catch (Exception ex)
              {
                Trace.Write(ex);
              }
            }
          }
        }
        if (Build(oCert) && (ChainElements.Count > 1))
          Trace.WriteLine("X509Chain.Build succeeded with extra certificates.");
        else
          Trace.WriteLine("X509Chain.Build still fails with extra certificates.");
      }
    }
    catch (Exception ex)
    {
      Trace.Write(ex);
    }
  }

  public void Dispose()
  {
    try
    {
      Trace.WriteLine(string.Format("Dispose: remove {0} extra certificates.", ChainPolicy.ExtraStore.Count));
      ChainPolicy.ExtraStore.Clear();
    }
    catch (Exception ex)
    {
      Trace.Write(ex);
    }
  }
}

在调用函数中,我现在可以成功检查未知证书是否源自国家根证书:

    bool bChainOK = false;
    using (X509TestChain oChain = new X509TestChain(oCert))
    {
      if ((oChain.ChainElements.Count > 0)
        && IsPKIOverheidRootCert(oChain.ChainElements[oChain.ChainElements.Count - 1].Certificate))
        bChainOK = true;
      if (!bChainOK)
      {
        TraceChain(oChain);
        sMessage = "Root certificate not present or not PKI Overheid (Staat der Nederlanden)";
        return false;
      }
    }
    return true;

完成图片:检查根证书(通常已安装,因为它包含在 Windows 更新中,但理论上也可能丢失),我将友好名称和指纹与发布的值进行比较:

private static bool IsPKIOverheidRootCert(X509Certificate2 oCert)
{
  if (oCert != null)
  {
    string sFriendlyName = oCert.FriendlyName;
    if ((sFriendlyName.IndexOf("Staat der Nederlanden") >= 0)
      && (sFriendlyName.IndexOf(" Root CA") >= 0))
    {
      switch (oCert.Thumbprint)
      {
        case "101DFA3FD50BCBBB9BB5600C1955A41AF4733A04": // Staat der Nederlanden Root CA - G1
        case "59AF82799186C7B47507CBCF035746EB04DDB716": // Staat der Nederlanden Root CA - G2
        case "76E27EC14FDB82C1C0A675B505BE3D29B4EDDBBB": // Staat der Nederlanden EV Root CA
          return true;
      }
    }
  }
  return false;
}

我不确定此检查是否安全,但在我的情况下,Windows 窗体应用程序的操作员非常确定可以访问要安装的有效证书。该软件的目标只是过滤证书列表,帮助他在计算机的机器存储中只安装正确的证书(该软件还安装了中间证书和根证书的公钥,以确保证书的运行时行为Web 服务客户端是正确的)。

于 2013-03-29T06:53:28.300 回答
1

我刚刚扩展了@Tristan的代码,并检查了根证书是否是添加到 ExtraStore 的证书之一。

X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.ExtraStore.Add(root);
chain.Build(cert);
if (chain.ChainStatus.Length == 1 &&
    chain.ChainStatus.First().Status == X509ChainStatusFlags.UntrustedRoot &&
    chain.ChainPolicy.ExtraStore.Contains(chain.ChainElements[chain.ChainElements.Count - 1].Certificate))
{
    // chain is valid, thus cert signed by root certificate 
    // and we expect that root is untrusted which the status flag tells us
    // but we check that it is a known certificate
}
else
{
    // not valid for one or more reasons
}
于 2016-12-16T10:06:32.540 回答