84

自己署名 SSL 証明書を使用する API に接続しようとしています。.NET の HttpWebRequest および HttpWebResponse オブジェクトを使用してそうしています。そして、次の例外が発生します。

基になる接続が閉じられました: SSL/TLS セキュア チャネルの信頼関係を確立できませんでした。

これが何を意味するのか理解しています。そして、 .NET が私に警告して接続を閉じる必要があると感じる理由を理解しています。しかし、この場合はとにかく API に接続したいので、中間者攻撃はやめてください。

では、この自己署名証明書に例外を追加するにはどうすればよいでしょうか? または、証明書をまったく検証しないように HttpWebRequest/Response に指示するアプローチですか? どうすればいいですか?

4

10 に答える 10

97

結局のところ、証明書の検証を完全に無効にしたい場合は、次のように ServicePointManager の ServerCertificateValidationCallback を変更できます。

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

これにより、すべての証明書 (無効、期限切れ、または自己署名のものを含む) が検証されます。

于 2009-02-09T00:07:28.293 に答える
81

@Domster: これは機能しますが、証明書のハッシュが期待するものと一致するかどうかを確認して、セキュリティを強化することをお勧めします。したがって、拡張バージョンは次のようになります (使用しているライブ コードに基づく)。

static readonly byte[] apiCertHash = { 0xZZ, 0xYY, ....};

/// <summary>
/// Somewhere in your application's startup/init sequence...
/// </summary>
void InitPhase()
{
    // Override automatic validation of SSL server certificates.
    ServicePointManager.ServerCertificateValidationCallback =
           ValidateServerCertficate;
}

/// <summary>
/// Validates the SSL server certificate.
/// </summary>
/// <param name="sender">An object that contains state information for this
/// validation.</param>
/// <param name="cert">The certificate used to authenticate the remote party.</param>
/// <param name="chain">The chain of certificate authorities associated with the
/// remote certificate.</param>
/// <param name="sslPolicyErrors">One or more errors associated with the remote
/// certificate.</param>
/// <returns>Returns a boolean value that determines whether the specified
/// certificate is accepted for authentication; true to accept or false to
/// reject.</returns>
private static bool ValidateServerCertficate(
        object sender,
        X509Certificate cert,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
    {
        // Good certificate.
        return true;
    }

    log.DebugFormat("SSL certificate error: {0}", sslPolicyErrors);

    bool certMatch = false; // Assume failure
    byte[] certHash = cert.GetCertHash();
    if (certHash.Length == apiCertHash.Length)
    {
        certMatch = true; // Now assume success.
        for (int idx = 0; idx < certHash.Length; idx++)
        {
            if (certHash[idx] != apiCertHash[idx])
            {
                certMatch = false; // No match
                break;
            }
        }
    }

    // Return true => allow unauthenticated server,
    //        false => disallow unauthenticated server.
    return certMatch;
}
于 2009-02-09T00:51:07.690 に答える
50

.NET 4.5 では、HttpWebRequest 自体ごとに SSL 検証をオーバーライドできることに注意してください (すべての要求に影響するグローバル デリゲート経由ではありません)。

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.servercertificatevalidationcallback.aspx

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.ServerCertificateValidationCallback = delegate { return true; };
于 2013-02-27T20:35:47.057 に答える
46

自己署名証明書をローカル コンピューターの信頼されたルート証明機関に追加します。

MMC を管理者として実行することにより、証明書をインポートできます。

方法: MMC スナップインを使用して証明書を表示する

于 2009-03-08T04:08:47.157 に答える
36

Domsterの回答で使用される検証コールバックの範囲は、デリゲートの送信者パラメーターを使用して特定のリクエストに制限できますServerCertificateValidationCallback。次の単純なスコープクラスは、この手法を使用して、特定の要求オブジェクトに対してのみ実行される検証コールバックを一時的に接続します。

public class ServerCertificateValidationScope : IDisposable
{
    private readonly RemoteCertificateValidationCallback _callback;

    public ServerCertificateValidationScope(object request,
        RemoteCertificateValidationCallback callback)
    {
        var previous = ServicePointManager.ServerCertificateValidationCallback;
        _callback = (sender, certificate, chain, errors) =>
            {
                if (sender == request)
                {
                    return callback(sender, certificate, chain, errors);
                }
                if (previous != null)
                {
                    return previous(sender, certificate, chain, errors);
                }
                return errors == SslPolicyErrors.None;
            };
        ServicePointManager.ServerCertificateValidationCallback += _callback;
    }

    public void Dispose()
    {
        ServicePointManager.ServerCertificateValidationCallback -= _callback;
    }
}

上記のクラスを使用すると、次のように特定の要求のすべての証明書エラーを無視できます。

var request = WebRequest.Create(uri);
using (new ServerCertificateValidationScope(request, delegate { return true; }))
{
    request.GetResponse();
}
于 2012-08-15T07:59:16.323 に答える
3

件名と発行者を含めるためにdevstuffからの回答に基づいて構築するだけです...コメントを歓迎します...

public class SelfSignedCertificateValidator
{
    private class CertificateAttributes
    {
        public string Subject { get; private set; }
        public string Issuer { get; private set; }
        public string Thumbprint { get; private set; }

        public CertificateAttributes(string subject, string issuer, string thumbprint)
        {
            Subject = subject;
            Issuer = issuer;                
            Thumbprint = thumbprint.Trim(
                new char[] { '\u200e', '\u200f' } // strip any lrt and rlt markers from copy/paste
                ); 
        }

        public bool IsMatch(X509Certificate cert)
        {
            bool subjectMatches = Subject.Replace(" ", "").Equals(cert.Subject.Replace(" ", ""), StringComparison.InvariantCulture);
            bool issuerMatches = Issuer.Replace(" ", "").Equals(cert.Issuer.Replace(" ", ""), StringComparison.InvariantCulture);
            bool thumbprintMatches = Thumbprint == String.Join(" ", cert.GetCertHash().Select(h => h.ToString("x2")));
            return subjectMatches && issuerMatches && thumbprintMatches; 
        }
    }

    private readonly List<CertificateAttributes> __knownSelfSignedCertificates = new List<CertificateAttributes> {
        new CertificateAttributes(  // can paste values from "view cert" dialog
            "CN = subject.company.int", 
            "CN = issuer.company.int", 
            "f6 23 16 3d 5a d8 e5 1e 13 58 85 0a 34 9f d6 d3 c8 23 a8 f4") 
    };       

    private static bool __createdSingleton = false;

    public SelfSignedCertificateValidator()
    {
        lock (this)
        {
            if (__createdSingleton)
                throw new Exception("Only a single instance can be instanciated.");

            // Hook in validation of SSL server certificates.  
            ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertficate;

            __createdSingleton = true;
        }
    }

    /// <summary>
    /// Validates the SSL server certificate.
    /// </summary>
    /// <param name="sender">An object that contains state information for this
    /// validation.</param>
    /// <param name="cert">The certificate used to authenticate the remote party.</param>
    /// <param name="chain">The chain of certificate authorities associated with the
    /// remote certificate.</param>
    /// <param name="sslPolicyErrors">One or more errors associated with the remote
    /// certificate.</param>
    /// <returns>Returns a boolean value that determines whether the specified
    /// certificate is accepted for authentication; true to accept or false to
    /// reject.</returns>
    private bool ValidateServerCertficate(
        object sender,
        X509Certificate cert,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;   // Good certificate.

        Dbg.WriteLine("SSL certificate error: {0}", sslPolicyErrors);
        return __knownSelfSignedCertificates.Any(c => c.IsMatch(cert));            
    }
}
于 2012-12-14T18:12:04.217 に答える
3

他の誰かに可能なヘルプとして追加するには... ユーザーに自己署名証明書をインストールするように促したい場合は、このコードを使用できます (上記から変更)。

管理者権限を必要とせず、ローカル ユーザーの信頼できるプロファイルにインストールします。

    private static bool ValidateServerCertficate(
        object sender,
        X509Certificate cert,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            // Good certificate.
            return true;
        }

        Common.Helpers.Logger.Log.Error(string.Format("SSL certificate error: {0}", sslPolicyErrors));
        try
        {
            using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                store.Open(OpenFlags.ReadWrite);
                store.Add(new X509Certificate2(cert));
                store.Close();
            }
            return true;
        }
        catch (Exception ex)
        {
            Common.Helpers.Logger.Log.Error(string.Format("SSL certificate add Error: {0}", ex.Message));
        }

        return false;
    }

これは私たちのアプリケーションではうまくいくようです。ユーザーが「いいえ」を押すと、通信は機能しません。

更新: 2015-12-11 - StoreName.Root を StoreName.My に変更 - My はルートではなくローカル ユーザー ストアにインストールされます。「管理者として実行」しても、一部のシステムでは root が機能しません。

于 2015-09-03T04:45:04.263 に答える
1

注意すべきことの 1 つは、ServicePointManager.ServerCertificateValidationCallback を使用しても、CRL チェックとサーバー名の検証が行われていないことを意味するようには見えず、その結果をオーバーライドする手段を提供するだけであるということです。そのため、サービスが CRL を取得するのにまだしばらく時間がかかる場合があります。後になって初めて、いくつかのチェックに失敗したことがわかります。

于 2013-11-06T12:31:11.513 に答える