Accept self-signed certificates in Xamarin Android - ssl

I got a Xamarin Forms project and inside the MainPage.xaml.cs file i want to perform a request to my server. The server is written in ASP.NET Core 2 and is running with a self-signed certificate.
To buy a certificate isn't a solution for my problem, because customers don't want it and application only running in LAN.
In my MainPage.xaml.cs file the Http-request looks like this:
HttpClient m_Client = new HttpClient();
var uri = new Uri(myURL);
var response = await m_Client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
...
}
So far so good. If I bring the app on Android and try to perform the request, Android throws a SSL Exception for not finding a CA for my certificate.
How can I communicate with my server using a self-signed certificate?
I looked up the problem and find a lot of solutions like:
ServicePointManager
.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
If you add this code to your MainActivity.cs file in your Android project, it should accept all certificates. But that is not working for me. It seems like this method never gets called.
Any suggestions how to make the communication happen?
Regards

One option is to work on the certificate, which has been discussed in the comments above.
However, I think an option to ignore the certificate validation in code is always faster, and you just need this,
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
HttpClient client = new HttpClient(handler);
For some unknown reasons, you cannot use the global event handler of ServicePointManager.ServerCertificateValidationCallback like you discovered, but HttpClient has its own handler.

Related

Xamarin HttpClient adding Client Certificate

I'm trying to send a request to a web api in Xamarin.Forms. The api requires a client certificate. I attempted to add the client certificate in the core project and in the native project as e.g. described here xamarin.android adding client certificate. However, I always get the response "400 No required SSL certificate was sent". If I send the request via e.g. Postman or openSSL, everything works fine. I've tested the request on Android and on iOS, but I always get the 400. Can anyone help?
Note: For Android, I am using the HttpClient implementation 'Android' and the TLS implementation 'Native TLS 1.2+'
The code I am using in the core project:
var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
SslProtocols = System.Security.Authentication.SslProtocols.Tls12,
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
};
//clientCertificateFileName is the location where the certificate is saved
var clientCertificate = new X509Certificate2(clientCertificateFileName, "password");
handler.ClientCertificates.Add(clientCertificate);
client = new HttpClient(handler);
var response = await client.GetAsync(targetUrl);

Having certificate issues when calling Web API from Web App

I am developing a web api and a web app locally. I am having trouble calling the web api from the web app.
When I call it I keep getting the error: "The remote certificate is invalid according to the validation procedure."
Both apps are built with ASP.Net Core and are running on kestrel. The webapp is callable as https://mylibrary.com:5003 and the Web API is callable as https://api.mylibrary.com:5001.
How can I get them working together with valid certificates?
Edit: Come to realise that the issue is that the apps are using localhost certs by default. I want to be able to use my own self signed cert.
If someone can point me to somewhere that explains how to set up two apps to use a self-signed certificate in .net core web projects please do :)
If you need to work around the cert validation using HttpClient, you could do it by creating a HttpClientHandler and passing it to HttpClient as per Rohit Jangid's answer to The SSL connection could not be established
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
HttpClient client = new HttpClient(clientHandler)
Avoid accidentally circumventing certificate validation in production by checking if it is in development environment:
HttpClient httpClient = new HttpClient();
if (env.IsDevelopment())
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, ssl) => { return true; };
httpClient = new HttpClient(clientHandler);
}
Inject information about webhostenvironment by injecting it in the handler/action:
public async Task OnGet([FromServices] IWebHostEnvironment env)
Please try to use RestSharp library to make the webapi request and set the cert validation to true. see here
or you can install the dotnet dev certs by executing dotnet dev-certs https --trust in a command promt or powershell

WCF Could not establish trust relationship for the SSL/TLS secure channel with authority

Scenario:
I've a WCF web service called SERVICEA hosted in Azure. It's uses self signed certificate for HTTPS.
This SERVICEA inspect the incoming request and determines whether to call:
SERVICEB OR
SERVICEC
Both SERVICEB AND SERVICEC also uses self signed cert. for https.
PROBLEM:
When I deploy the SERVICEA and try to call so that it invokes SERVICEB I get the error message below:
*
Could not establish trust relationship for the SSL/TLS secure channel
with authority "SERVICEB..."
*.
Note it says SERVICEB.. on error message.
Anyidea how I can resolve this issue, please?
You need to validate the server certificate if its self signed as shown below:
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, error) => true;
You want to trap the ServerCertificateValidationCallback and make it ignore certificates of your choosing.
Here is a decent article that explains how: http://blog.jameshiggs.com/2008/05/01/c-how-to-accept-an-invalid-ssl-certificate-programmatically/
Rajesh is onto something, but his answer disables certification checks altogether.
Instead I would suggest an event handler like the following should be added to your application:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) =>
{
var request = sender as HttpWebRequest;
if (request != null && request.Address.Host == "<Your domain name goes here>")
return true;
return errors == SslPolicyErrors.None;
};

WCF certificate security with Mono

I'm trying to migrate an existing application to Mono (v2.10.2).
Therefore I created a test WCF service with BasicHttpBinding and message security. The client works perfectly with .NET, but when running with Mono it fails.
The client factory is instantiated as follows:
//var certificate = CertificateUtil.GetCertificate(StoreLocation.LocalMachine,
// StoreName.My, X509FindType.FindBySubjectDistinguishedName, CertName, true);
var certificate = new X509Certificate2("certificate.pfx", "password");
var binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Message;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
var epa = new EndpointAddress(
new Uri("http://localhost:53076/Service1.svc"),
new X509CertificateEndpointIdentity(certificate));
var factory = new ChannelFactory<IService1>(binding, epa);
factory.Credentials.ServiceCertificate.DefaultCertificate = certificate;
factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
factory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
factory.Credentials.ClientCertificate.Certificate = certificate;
var client = factory.CreateChannel();
In Mono the application fails within CreateChannel throwing the exception:
System.InvalidOperationException: The binding does not support any of the channel types that the contract 'IService1' allows.
I debugged into the Mono source code and found out that the problem is that AsymmetricSecurityBindingElement.InitiatorTokenParameter == null.
I'm new to Mono, maybe you could point me to a documentation/tutorial which covers this topic.
UPDATE:
With the aid of konrad.kruczynski the certificate object has a private key now. The exception is still the same. So this is not a certificate store issue.
Yes, certificates created on Windows usually does not contain private key. They can be found in some kind of cache. You should be able to create certificate with private key using this instruction. X509Certificate2 should consume the file without problems. You can also try procedure described here. In case of any problems just write.
It is also worth adding, that certificates created such way on Linux works perfectly on Windows too.
Update:
I'm not sure whether I understood your comment correctly. You can load PFX certificate using code like that:
var myCert = new X509Certificate2("filename.pfx", "password");
Given certficate contained key, it worked for me.

WCF, REST, SSL, Client, custom certificate validation

I have a specific problem that I can't solve. Let me explain in detail. I'm new to this technology so I might be using some wrong terms. Please correct and explain or ask for explanation if you don't understand.
I am creating a self hosted WCF REST server, hosted in WPF application. It uses https, SLL with WebHttpSecurityMode.Transport. I am using my own generated certificate.
I would like to create a WinForms client that would use this service. The format of the response form the server is JSON.
I would like to validate the certificate on the client with my custom validator inherited from X509CertificateValidator.
This is my server side code. I'm using a custom username validator that works fine. I have configured the certificate in the IIS Manager on my machine for the Default Website > Bindings, where I have generated the certificate (Windows 7).
WebServiceHost sh = new WebServiceHost(typeof(ReachService));
string uri = "https://localhost:9000/Service";
WebHttpBinding wb = new WebHttpBinding();
wb.Security.Mode = WebHttpSecurityMode.Transport;
wb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
sh.AddServiceEndpoint(typeof(IReachService), wb, uri);
sh.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator();
sh.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
sh.Open();
and this is my client code
Uri uri = new Uri("https://localhost:9000/Service");
WebChannelFactory<ReachService> cf = new WebChannelFactory<IReachService>(uri);
WebHttpBinding wb = cf.Endpoint.Binding as WebHttpBinding;
wb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
wb.Security.Mode = WebHttpSecurityMode.Transport;
cf.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;
cf.Credentials.ServiceCertificate.Authentication.CustomCertificateValidator = new CustomCertificateValidator("PL2"); // this is the name that issued the certificate
cf.Credentials.UserName.UserName = "user1";
cf.Credentials.UserName.Password = "user1";
IReachService service = cf.CreateChannel();
try
{
CustomersList auth = service.GetCustomers();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
on calling service.GetCustomers() I get:
Could not establish trust relationship for the SSL/TLS secure channel with authority
'localhost:9000'.
InnerException Message:
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
InnerException Message:
The remote certificate is invalid according to the validation procedure.
The server is working fine when I test in the browser.
But the client code is wrong cause it doesn't go to the custom cert validator class. And this class is the same as in the MSDN example on http://msdn.microsoft.com/en-us/library/system.identitymodel.selectors.x509certificatevalidator.aspx.
Can anyone please tell me where am I going wrong with this approach?
If you need more info please ask.
Thank you
It looks like the issue occurs because certificate was issued for some other hostname. You can check this (and customize if necessary) by providing custom ServicePointManager.ServerCertificateValidationCallback.
//don't use HttpWebRequest --you lose all of the strongly-typed method and data contracts!
//the code to create the channel and call a method:
SetCertPolicy();
var cf1 = new WebChannelFactory<TService>(new Uri(remoteServiceAddressSecure));
var service = cf1.CreateChannel();
sevice.DoMethod();
protected static void SetCertPolicy()
{
ServicePointManager.ServerCertificateValidationCallback += RemoteCertValidate;
}
private static bool RemoteCertValidate(object sender, X509Certificate cert, X509Chain chain,
SslPolicyErrors error)
{
// trust any cert!!!
return true;
}
If you want to use WCF on the client, then don't use WebHttpBinding, stick with the SOAP stuff it will work much better.
However, if you want to use a standard HTTP client like, WebClient or HttpWebRequest or HttpClient V.prototype or HttpClient V.Next then stick with the webHttpBinding.
Sorry for not addressing your direct question but you are likely to run into more problems because you are using a binding that was intended to make WCF services accessible to non-WCF platforms but then using WCF to try and access it.