2011-05-23 72 views
6

我的程序包含2个我认识并信任的root证书。 我必须验证所有源自这两个根证书的信任中心颁发的信任中心证书和“用户”证书。如何在不导入root证书的情况下验证X509证书?

我使用X509Chain类进行验证,但只有在根证书位于Windows证书存储区时才有效。

我正在寻找一种方法来验证证书,而不导入这些根证书 - 以某种方式告诉X509Chain类,我信任这个根证书,它应该只检查链中的证书,而不是其他任何东西。

实际代码:

 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); 

编辑:这是一个.NET 2.0 WinForms应用程序。

回答

1

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

如果你在此通过细分System.IdentityModel.Selectors.X509CertificateValidator并指定自定义验证的serviceBehavior对象在web.config中做了WCF背景:

<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(); 
     } 
    } 
} 
+0

我编辑了这个问题,它是一个.NET 2.0 Winforms应用程序。 – RainerM 2011-05-23 14:54:23

1

如果你知道哪些证书可以是根证书和中间证书的证书来检查,你可以加载根和中间的公共密钥ChainPolicy.ExtraStoreX509Chain对象集合

我的任务是编写一个Windows Forms应用程序来安装证书,只要它是依赖于我国政府已知的“国家根证书”发布的。是允许颁发证书来验证与国家Web服务的连接的有限数量的CA,所以我拥有了一个有限的一组证书可能在链中,并且可能在目标机器上丢失。我收集了CA和政府根证书的所有公钥,并将其存储在应用的子目录“cert”中: chain certificates

在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 Update中,但理论上也可能丢失),我将友好名称和指纹与公布的值进行比较:

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 Forms应用程序的操作员非常确定可以访问要安装的有效证书。该软件的目标是过滤证书列表,以帮助他在计算机的机器存储区中只安装正确的证书(该软件还安装中间证书和根证书的公钥,以确保证书的运行时行为Web服务客户端是正确的)。

3

我发现这个解决方案不依赖于构建方法的结果,而是检查ChainStatus属性。 (没有测试.NET 2.0,但是这是我找到了这个常见问题的唯一解决方案)

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 is valid, thus cert signed by root certificate 
    // and we expect that root is untrusted which the status flag tells us 
} 
else 
{ 
    // not valid for one or more reasons 
} 

也有人通过实验发现,设置

ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; 

将允许构建方法返回即使您没有将证书添加到ExtraStore中也是如此,这完全破坏了检查的目的。我不建议因任何原因使用此标志。

+0

即使用于签署最终实体证书的根目录不同,这似乎也会返回“不可信根”。不是很想要的行为。 – 2016-05-16 14:31:30

+0

我同意你对AllowUnknownCertificateAuthority的评论,我自己也得出了同样的结论,同时将我自己的CA证书添加到ExtraStore – tul 2017-01-19 15:44:41

0

我刚刚扩展了@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 
}