21

私のプログラムには、私が知っていて信頼している 2 つのルート証明書が含まれています。トラストセンターの証明書と、トラストセンターによって発行された「ユーザー」証明書を確認する必要があります。これらはすべて、これら 2 つのルート証明書に由来します。

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 アプリケーションです。

4

5 に答える 5

9

編集

何年にもわたって、私がここに投稿した元の X509Chain ソリューションには、特定のエッジ ケースで X509Chain が正しくない動作を実行するという問題がいくつか見つかりました。したがって、この問題に X509Chain を使用することはお勧めできません。それ以来、私たちの製品はすべての証明書チェーンの検証を行うために Bouncy Castle を使用するようになり、すべてのテストに耐え、常に期待どおりに動作します。

私たちの新しいソリューションの基礎はここにあります: Build certificate chain in BouncyCastle in C#

元の回答を削除したので、誰も悪いセキュリティ ソリューションを使用していません。

于 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 設定を変更できます。

以下は、クライアント証明書が LocalMachine/Personal ストアに存在するかどうかをテストする X509CertificateValidator の例です。(これは必要なものではありませんが、例として役立つ場合があります。

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ます。

私の仕事は、私の国の政府の既知の "National Root certificate" に依存して発行された場合にのみ、証明書をインストールするための Windows Forms アプリケーションを作成することでもありました。国内の Web サービスへの接続を認証するための証明書を発行できる CA の数も限られているため、チェーンに含めることができ、ターゲット マシンで欠落している可能性がある証明書のセットは限られていました。CA のすべての公開鍵と政府のルート証明書を、アプリケーションのサブディレクトリ「cert」に集めました。 チェーン証明書

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 フォーム アプリケーションのオペレーターは、インストールされる有効な証明書にアクセスできることを確信しています。ソフトウェアの目的は、証明書リストをフィルタリングして、コンピュータのマシン ストアに正しい証明書のみをインストールできるようにすることです (ソフトウェアは、中間証明書とルート証明書の公開鍵もインストールして、 Web サービス クライアントが正しい)。

于 2013-03-29T06:53:28.300 に答える
1

ルート証明書が ExtraStore に追加された証明書の 1 つであることを確認して、@Tristanのコードを拡張しました。

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 に答える