HTTPWebRequest Could not create SSL/TLS secure channel - c#

I am trying to call a Web API using HttpWebRequest(Console Application).
To upload the file, I am using the code snippet provided by #Cristian Romanescu ont this question Upload files with HTTPWebrequest (multipart/form-data)
If I set the req.ProtocolVersion as HttpVersion.Version10,I get Bad request when I try to do req.GetResponseStream().
If i set the req.ProtocolVersion as HttpVersion.Version11,I get Could not create SSL/TLS secure channel. when i try to do req.GetResponseStream().
If tried to post the data using POSTMAN, but even Postman says Could not get any response".
If I try to hit the URL using IE-11 I get HTTP 404.[I know i am not posting the actual file], but Chrome displays the custom/appropriate error message.
I tried the solutions already provided on stackoverflow, but unfortunately they do not solve my problem.
Thankyou.

Which solution you have tried? It's worth trying the following if you haven't already - write following before you actually invoke the service:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Two things that I was doing wrong.
The Server wanted date in yyyy-MM-ddTHH:mm:ss, I was providing the date in yyyy-MM-ddTHH:mm:ss.ssss Format(DateTime.UtcNow.ToString("o")). This was the cause of Could not create SSL/TLS secure channel
The server wanted the parameters in request body as well. I had passed the parameters only as query string. This was the cause of HTTP 404
In the process, I had asked a guy outside my team to help. He had asked me to see if there were any SSL related errors. To do this he asked me to add
System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); and define AcceptAllCertifications, which was not the case. So to resolve the issue, I had to take care of the things mentioned above.

Try to create self signed certificate from your server and add it to your client machine.
Create self signed certificate (Server side)
Import self signed certificate (Client side)

Related

Bypass invalid SSL certificate errors .Net / c#

I've got a development system which I'm trying to get to communicate to a third-party secure web service.
The third party have provided me with a certificate which I've imported locally. I've made sure the certificate is added to the 'Trusted Root Certification Authorities' store. It seems to have imported correctly, as if I go Chrome and try to access one of the service urls mentioned in the web service WSDL file I firstly get a popup asking to me to confirm which certificate to use (there's only the one option) and it then lets me through. However, if I then use the same WSDL file to create a service reference in Visual Studio, and make a call to one of the services in my code, I get an error saying 'Could not establish secure channel for SSL/TLS with authority'.
Ideally I would get VS to acknowledge the cert when I'm making the webservice call, but seeing as this is a development system I'm also happy to ignore the SSL errors for the time being.
To this end I've added the following to my code, along with variations on the protocols I'm specifying (e.g. only specifying SSL3, taking out SSL3 etc):
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
But no matter what I do I still get the SSL error when I try to make the service call.
If anyone has any suggestions on how to get VS to accept the certificate is present (as Chrome seems to do) or, alternatively, how to get the code to ignore the SSL error for now, so I can proceed with development, it'd be much appreciated.

Override HTTPS certificate

I am using a URL to connect with a web service using SOAP. Apparently the URL does not have a correct https protocol and if I want to access it via browser, I need to accept the 'risk' this connection has.
My problem starts when I want to access in programmatically. When I try to send a SOAP POST request, the connection is closed and an exception is caught.
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
Apparently this problem was common, and a lot of resources could be found, this and this being the most upvoted.
When i tried this part of code:
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
not only the connection did not work, but now I am given a:
"The remote server returned an error: (500) Internal Server Error."
Now my question is. The code above switches the protocol from https to http?
If not what does this line of code really do?
I don't know if this will be your answer, but as it is not appropriate for a comment...
Do not bypass certificate validation. You probably only need to set the correct version of TLS. You can experiment to find the highest version supported by using one at time instead of OR'ing them together.:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12
If that doesn't work you may need to obtain a certificate, either the one used by the service or one higher in the certificate chain.

C# Enforcing HttpWebRequest to use Tls12 instead of SSLv3

I have App that makes use of some web service and acquire data via JSON, all was working fine for quite long time, up until latest discoveries about SSLv3 being vulnerable to man-in-the-middle attacks and server owners turning off SSLv3 for good. My application started to have problems connecting and returned error "Request was aborted: cannot establish secure SSL/TLS connection". I've tried to look for solution and found information i got to add this code before creating web request:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = delegate{
return true;
};
Unfortunately no luck here, app acts the same as before, and I have no clue if this code does nothing or there is still some problem with server. Error information is pretty vague and i have problem figuring where things go wrong.
Here is my code
...
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = GetRequestContentType();
request.Method = method.ToString();
request.Credentials = GetCredential(url);
request.PreAuthenticate = true;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
...
I want to ask how to set Tls12 to be used as default and ensure that at my end request I make is with desired protocol.
If I confirm that my app at my end works fine, is there way to get more detailed information from server response and pinpoint precise reason of error?
Thanks for all answers and suggestions.
EDIT
Second part of question is solved, I found this tool http://www.telerik.com/download/fiddler it pretty much allows to see what is going on with outgoing and incoming data. There is also thing that this tool allow to decode SSL connections, enabling this option makes that my application starts to work. I assume that this app does something that make communication between my app and destination host possible. But i do still have no idea what it could be. And how to make my app to handle these connections properly by itself.
Being desperate made me to inspect whole source code (part responsible for getting data of the internet was 3rd party and until it worked fine there was no reason to change it) and I discovered that line
request.Credentials = GetCredential(url);
called method that in its body had
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
So all my attempts to change that value before creating httpwebrequest was overwritten. Changing SecurityProtocolType to Tls12 makes it all work now.

HttpListenerRequest is not returning a client certificate

I'm using an HttpListener to create a very basic web server. I've got it setup to use SSL using the httpcfg tool to bind to the appropriate port and certificate. This seems to be working fine. I'd now like to use client certificate authentication. So I added a call to GetClientCertificate on the HttpListenerRequest object but it is always coming back with null. My test client is very simple:
HttpWebRequest webReq = (HttpWebRequest) WebRequest.Create("https://127.0.0.1:8080/ssltest/");
webReq.ClientCertificates.Add(new X509Certificate2("ssltest.pfx", "ssltest"));
webReq.GetResponse();
I noticed that the httpcfg tool has a flag that indicates if client certificates should be negotiated so I tried specifying that flag (-f 2) but I'm still not getting the client cert. I also came across this Microsoft support issue which seems pretty relevant but I'm using the latest .NET 2.0 service pack and I've also tried the httpcfg flag both of which should avoid the issue.
I am assuming I am missing something obvious here. Any ideas?
Edit: I just found this question which seems very relevant (maybe even a duplicate?). Unfortunately there is no accepted answer for that question either. The suggested answer makes a suggestion for something I already tried (httpcfg tool with the appropriate flag).
According to http://support.microsoft.com/kb/895971/en-us the HttpWebRequest.ClientCertificates.Add performs validation already so the cert fails validation on the client-side and never gets sent.
The above link contains code to relax the validation... NEVER use that in production!!!

c# file downloading problem

I am using this code to download file from server and parse data from JSON notation:
WebClient wcl = new WebClient();
Uri url = new Uri(tickurl);
string srlz = wcl.DownloadString(url);
var dict = (new JavaScriptSerializer()).Deserialize<Dictionary<string, dynamic>>(srlz);
When I use it with http://deepbit.net/api/ + my token (URI returns JSON data) it works well.
But with https://mtgox.com/code/data/ticker.php it stucks on 3rd line of the function(data downloading).
What am i doing wrong? Both URLs return same JSON formatted data.
[add] it's not issue with https, this code works well enough with other https services. i am wondering if this could be a problem with SSL cert.
SOLVED: turned off SSL certificate validation. thanks
I suspect it's failing due to a security problem. When I fetch with wget, I get:
ERROR: certificate common name www.mtgox.com' doesn't match requested host namemtgox.com'
It's fine when I fetch with wget using the --no-check-certificate flag.
I don't know whether you can persuade WebClient not to check certificates... but a better option would obviously be to get the certificate fixed.
Alternatively, try this URL instead: https://www.mtgox.com/code/data/ticker.php - note the www at the front. That fetches in wget without any issues.
The Url: https://mtgox.com/code/data/ticker.php doesn't even open up in browser. It starts downloading the 'ticker.php' file. Your server is misconfigured. The code is fine. Most probably the server is not properly configured to process .php files as scripts.
it is a certificate error like Jon Skeet said.
Have a look here to find a easy solution
WebClient + HTTPS Issues
you shouldn't use this for all request, only for debugging

Categories