C# Ignore certificate errors?
Asked Answered
D

12

214

I am getting the following error during a web service request to a remote web service:

Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

Is there anyway to ignore this error, and continue?

It seems the remote certificate is not signed.

The site I connect to is www.czebox.cz - so feel free to visit the site, and notice even browsers throw security exceptions.

Dicotyledon answered 20/4, 2010 at 12:42 Comment(0)
S
426

Add a certificate validation handler. Returning true will allow ignoring the validation error:

ServicePointManager
    .ServerCertificateValidationCallback += 
    (sender, cert, chain, sslPolicyErrors) => true;
Schilt answered 20/4, 2010 at 12:48 Comment(13)
This is even more useful than it may at first appear. I ran into the OP's problem while using Managed Exchanged Web Services (EWS). I thought that I could not use this answer since I didn't have access to the low-level SOAP calls that were being made by that managed library. But when I took another look at it, I realized ServicePointManager stands on its own. So,I added the above callback before initializing the ExchangeService and it worked like a charm.Gilmer
@PeterLillevold I had a self signed SSL for internal testing, as far i see this ignores errors, just was very hard to find without guidance!Marginal
@Marginal - yes, a self-signed certificate (since it inherently is not a trusted certificate) will not pass certificate validation. Returning true in the callback will ignore the validation errors, thus allowing calls to the site using the untrusted certificate to complete.Schilt
Here is an example of how to apply the bypass globally. For all of us into bad practices. (Sometimes you have no choice) jasig.275507.n4.nabble.com/…Great
I am having this problem but in .net core. ServicePointManager is not supported in .net coreJacquard
@RamonCruz they have actually implemented the ServerCertificateCustomValidationCallback in the 4.1 revision (see the last 2-3 comments on the issue github.com/dotnet/corefx/issues/4476)Schilt
a big thank you this solves the problem temporarily. Add this code in Startup.cs in Web ApiEighteen
@MarkMeuer was almost going to give up on this solution for my EWS API problem, but then I saw your comment.Salute
Can someone post the complete code snippet of using ServicePointManger code to make a request?Ochlophobia
@Ochlophobia you're not using ServicePointManager directly to make the request, you use client APIs like HttpClient or HttpWebRequest for that. There are plenty of samples on those out there.Schilt
@MiguelVeloso you are free to downvote ofcourse, but keep in mind, neither the question nor the answer discuss the security side of this. The topic is explicitly "how to ignore the validation error", not "why should we do/not do this", which is a different topic alltogether. Going into a discussion on why the OP shouldn't do it would only muddy the waters, as commenters have pointed out there are reasonable cases where you actually would do this. So we stick to the topic and solve the problem.Schilt
Suddenly had an AWS Lambda Function refusing to connect to a remote endpoint overnight. This fixed it for me, thank you! I've put the code within an if statement, triggered by an Environment Variable in the AWS Configuration .. f I can figure out why it failed, or if it resolves, then I can easily disable this code block.Connote
I had to upgrade to .NET 4.5 and switch to Tls12 for this to work.Taliesin
R
85

Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.

.NET Core:

using (var httpClientHandler = new HttpClientHandler())
{
    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) =>
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;   //Is valid
        }

        if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
        {
            return true;
        }
        return false;
    };

    using (var httpClient = new HttpClient(httpClientHandler))
    {
        var httpResponse = httpClient.GetAsync("https://example.com").Result;
    }
}

.NET Framework:

System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate (
    object sender,
    X509Certificate cert,
    X509Chain chain,
    SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
    {
        return true;   //Is valid
    }

    if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
    {
        return true;
    }

    return false;
};

Update:

How to get cert.GetCertHashString() value in Chrome:

Click on Secure or Not Secure in the address bar.

Then click on Certificate -> Details -> Thumbprint and copy the value. Remember to do cert.GetCertHashString().ToLower().

Rodenhouse answered 23/5, 2017 at 16:37 Comment(5)
@MiguelVeloso Completely agree. This allows to skip the checking on (hopefully) one or two certificates without compromising security completely.Patricia
HOw can I get Hash String from a cert?Brownlee
@Brownlee Either debug the code and run cert.GetCertHashString() from Immediate window or check cert Thumbprint in your browser or MMC if it is installed locally.Rodenhouse
The server is in our control, is it still safe to use @Ogglas's code on production? Using TLS/SSL, can attack like man-in-the-middle be stopped?Beet
the .net core part, which class should put it in @Ogglas?Mullion
M
33

IgnoreBadCertificates Method:

//I use a method to ignore bad certs caused by misc errors
IgnoreBadCertificates();

// after the Ignore call i can do what ever i want...
HttpWebRequest request_data = System.Net.WebRequest.Create(urlquerystring) as HttpWebRequest;

/*
and below the Methods we are using...
*/

/// <summary>
/// Together with the AcceptAllCertifications method right
/// below this causes to bypass errors caused by SLL-Errors.
/// </summary>
public static void IgnoreBadCertificates()
{
    System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
}  

/// <summary>
/// In Short: the Method solves the Problem of broken Certificates.
/// Sometime when requesting Data and the sending Webserverconnection
/// is based on a SSL Connection, an Error is caused by Servers whoes
/// Certificate(s) have Errors. Like when the Cert is out of date
/// and much more... So at this point when calling the method,
/// this behaviour is prevented
/// </summary>
/// <param name="sender"></param>
/// <param name="certification"></param>
/// <param name="chain"></param>
/// <param name="sslPolicyErrors"></param>
/// <returns>true</returns>
private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
} 
Mamelon answered 7/3, 2013 at 6:17 Comment(1)
I had to add one more line to get this to work with my code (I'm using websocket4net). System.Net.ServicePointManager.CheckCertificateRevocationList = false; Right after setting the server cert validation callback.Laguna
C
26

The reason it's failing is not because it isn't signed but because the root certificate isn't trusted by your client. Rather than switch off SSL validation, an alternative approach would be to add the root CA cert to the list of CAs your app trusts.

This is the root CA cert that your app currently doesn't trust:

-----BEGIN CERTIFICATE-----
MIIFnDCCBISgAwIBAgIBZDANBgkqhkiG9w0BAQsFADBbMQswCQYDVQQGEwJDWjEs
MCoGA1UECgwjxIxlc2vDoSBwb8WhdGEsIHMucC4gW0nEjCA0NzExNDk4M10xHjAc
BgNVBAMTFVBvc3RT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lIHdhcyBpc3N1ZWQgYWNjb3Jk
aW5nIHRvIExhdyBObyAyMjcvMjAwMENvbGwuIGFuZCByZWxhdGVkIHJlZ3VsYXRp
b25zMBIGA1UdEwEB/wQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQW
BBQVKYzFRWmruLPD6v5LuDHY3PDndjCBgwYDVR0jBHwweoAUFSmMxUVpq7izw+r+
S7gx2Nzw53ahX6RdMFsxCzAJBgNVBAYTAkNaMSwwKgYDVQQKDCPEjGVza8OhIHBv
xaF0YSwgcy5wLiBbScSMIDQ3MTE0OTgzXTEeMBwGA1UEAxMVUG9zdFNpZ251bSBS
b290IFFDQSAyggFkMA0GCSqGSIb3DQEBCwUAA4IBAQBeKtoLQKFqWJEgLNxPbQNN
5OTjbpOTEEkq2jFI0tUhtRx//6zwuqJCzfO/KqggUrHBca+GV/qXcNzNAlytyM71
fMv/VwgL9gBHTN/IFIw100JbciI23yFQTdF/UoEfK/m+IFfirxSRi8LRERdXHTEb
vwxMXIzZVXloWvX64UwWtf4Tvw5bAoPj0O1Z2ly4aMTAT2a+y+z184UhuZ/oGyMw
eIakmFM7M7RrNki507jiSLTzuaFMCpyWOX7ULIhzY6xKdm5iQLjTvExn2JTvVChF
Y+jUu/G0zAdLyeU4vaXdQm1A8AEiJPTd0Z9LAxL6Sq2iraLNN36+NyEK/ts3mPLL

-----END CERTIFICATE-----

You can decode and view this certificate using

this certificate decoder or another certificate decoder

Carrnan answered 20/4, 2010 at 19:7 Comment(1)
Yes! This is my case , but how can I add the certificate on Azure, without a VM? Can I just use the X509Store API? I'm going to try that tomorrow but any info is welcome hereTalyah
S
17

Bypass SSL Certificate....

HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

// Pass the handler to httpclient(from you are calling api)
var client = new HttpClient(clientHandler)
Shults answered 5/6, 2019 at 12:3 Comment(1)
This is a cut-down version of this answer and doesn't add anything new.Sharma
P
8

To disable ssl cert validation in client configuration.

<behaviors>
   <endpointBehaviors>
      <behavior name="DisableSSLCertificateValidation">
         <clientCredentials>
             <serviceCertificate>
                <sslCertificateAuthentication certificateValidationMode="None" />
              </serviceCertificate>
           </clientCredentials>
        </behavior>
Presidio answered 13/4, 2016 at 10:39 Comment(1)
Is this web.config? Any alternatives for ASP.NET Core?Greensboro
O
7

This code worked for me. I had to add TLS2 because that's what the URL I am interested in was using.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback +=
    (sender, cert, chain, sslPolicyErrors) => { return true; };
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(UserDataUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new
      MediaTypeWithQualityHeaderValue("application/json"));
    Task<string> response = client.GetStringAsync(UserDataUrl);
    response.Wait();

    if (response.Exception != null)
    {
         return null;
    }

    return JsonConvert.DeserializeObject<UserData>(response.Result);
}
Ochlophobia answered 9/10, 2017 at 13:42 Comment(0)
C
7

Old, but still helps...

Another great way of achieving the same behavior is through configuration file (web.config)

 <system.net>
    <settings>
      <servicePointManager checkCertificateName="false" checkCertificateRevocationList="false" />
    </settings>
  </system.net>

NOTE: tested on .net full.

Carny answered 14/8, 2020 at 21:51 Comment(1)
This worked for me. Also It helps for QA/Dev teams to tests while allowing for production configurations to be secure. Thanks :)Tichon
S
4

This works for .Net Core. Call on your Soap client:

client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
                new X509ServiceCertificateAuthentication()
                {
                    CertificateValidationMode = X509CertificateValidationMode.None,
                    RevocationMode = X509RevocationMode.NoCheck
                };  
Stealer answered 1/10, 2019 at 11:36 Comment(0)
T
2

If you are using sockets directly and are authenticating as the client, then the Service Point Manager callback method won't work. Here's what did work for me. PLEASE USE FOR TESTING PURPOSES ONLY.

var activeStream = new SslStream(networkStream, false, (a, b, c, d) => { return true; });
await activeStream.AuthenticateAsClientAsync("computer.local");

The key here, is to provide the remote certificate validation callback right in the constructor of the SSL stream.

Toilette answered 5/5, 2016 at 4:32 Comment(0)
T
1

To further expand on BIGNUM's post - Ideally you want a solution that will simulate the conditions you will see in production and modifying your code won't do that and could be dangerous if you forget to take the code out before you deploy it.

You will need a self-signed certificate of some sort. If you know what you're doing you can use the binary BIGNUM posted, but if not you can go hunting for the certificate. If you're using IIS Express you will have one of these already, you'll just have to find it. Open Firefox or whatever browser you like and go to your dev website. You should be able to view the certificate information from the URL bar and depending on your browser you should be able to export the certificate to a file.

Next, open MMC.exe, and add the Certificate snap-in. Import your certificate file into the Trusted Root Certificate Authorities store and that's all you should need. It's important to make sure it goes into that store and not some other store like 'Personal'. If you're unfamiliar with MMC or certificates, there are numerous websites with information how to do this.

Now, your computer as a whole will implicitly trust any certificates that it has generated itself and you won't need to add code to handle this specially. When you move to production it will continue to work provided you have a proper valid certificate installed there. Don't do this on a production server - that would be bad and it won't work for any other clients other than those on the server itself.

Taraxacum answered 12/4, 2016 at 2:24 Comment(0)
H
0
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
                if (System.Net.ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls))
                    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Holoblastic answered 28/2, 2023 at 9:35 Comment(1)
Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?Wiring

© 2022 - 2024 — McMap. All rights reserved.