Xamarin HttpClient adding Client Certificate - ssl

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);

Related

I'm getting an error when using RestSharp DigestAuthenticator

So I have a .net core API that's trying to use RestSharp(which I'm fairly new to) to call another API. This other API apparently requires Digest based authentication to access, so I went ahead and tried using the DigestAuthenticator class provided by RestSharp. However, the result was an error saying Header not found : Digest Realm. Image of error below.
RestSharp DigestAuthenticator Error
So, I'm assuming that I would need to add a header for digest auth in my request. But, how would I go about doing that?
Below is what I've done so far,
RestClient client = new RestClient();
RestRequest request = new RestRequest();
client.BaseUrl = new System.Uri("http://ip_address:port/otherApi");
client.Authenticator = new DigestAuthenticator("myusername", "mypassword");
request.Method = Method.POST;
//not sure how to add header for digest auth
//request.AddHeader("")
request.AddParameter("application/xml", xmlString, ParameterType.RequestBody);
client.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
IRestResponse response = client.Execute(request);
return Ok(response.Content);

How to send intermediate cert (in addition to leaf cert) from http client to the server in .net (core) 5?

I was not able to make http client code in .net 5 to send both intermediate and leaf certificates (in 3 certificate hierarchy) to the server. However I was able to send the leaf certificate from client to the server successfully. Here is my setup:
I have 3 certificates on my windows box:
TestRoot.pem
TestIntermediate.pem
TestLeaf.pem (without private key for server - windows box)
TestLeaf.pfx (with private key for client - windows box)
The none of the above certificates were NOT added to windows certificate manager as I would like to be able to run the same code on non-windows machines eventually. For my testing, I am running following client and server code on the same windows box.
On my windows box, I have following simple client side code using .net 5:
HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
X509Certificate2 leafCert = new X509Certificate2(File.ReadAllBytes(#"C:\Temp\TestLeaf.pfx"), "<password>");
handler.ClientCertificates.Add(leafCert);
HttpClient httpClient = new HttpClient(handler);
StringContent content = new StringContent("{}"); //Test json string
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(MediaTypeNames.Application.Json);
//With local.TestServer.com resolving to localhost in the host file
HttpResponseMessage response = httpClient.PostAsync("https://local.TestServer.com/...", content).Result;
if (response.IsSuccessStatusCode)
{
var responseString = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseString);
}
else
{
Console.WriteLine(x.StatusCode);
Console.WriteLine(x.ReasonPhrase);
}
On same window box, I have following example snippet of server side code using kestrel in .net 5:
services.Configure<KestrelServerOptions>(options =>
{
// Keep track of what certs belong to each port
var certsGroupedByPort = ...;
var certsPerDistinctSslPortMap = ...;
// Listen to each distinct ssl port a cert specifies
foreach (var certsPerDistinctSslPort in certsPerDistinctSslPortMap)
{
options.Listen(IPAddress.Any, certsPerDistinctSslPort.Key, listenOptions =>
{
var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions();
httpsConnectionAdapterOptions.ClientCertificateValidation = (clientCertificate, chain, sslPolicyErrors) =>
{
bool trusted = false;
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors)
{
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
X509Certificate2 certRoot = new X509Certificate2(#"C:\Temp\TestRoot.pem");
X509Certificate2 certIntermdiate = new X509Certificate2(#"C:\Temp\TestIntermediate.pem");
chain.ChainPolicy.CustomTrustStore.Add(certRoot);
chain.ChainPolicy.ExtraStore.Add(certIntermdiate);
trusted = chain.Build(clientCertificate);
}
return trusted;
};
httpsConnectionAdapterOptions.ServerCertificateSelector = (connectionContext, sniName) =>
{
var defaultCert = //Get default cert
return defaultCert;
};
httpsConnectionAdapterOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
httpsConnectionAdapterOptions.SslProtocols = SslProtocols.Tls12;
listenOptions.UseHttps(httpsConnectionAdapterOptions);
});
}
options.Listen(IPAddress.Any, listeningPort);
});
The above code works as expected because the client code sends the leaf certificate to the server and the server code has access to both intermediate as well as root certificates. The server code can successfully rebuild the certificate hierarchy with received leaf certificate and its configured intermediate and root certs for the leaf certificate.
My following attempt to send the intermediate certificate (along with leaf certificate) to the server (so that it can only use the root certificate and incoming leaf and intermediate certificates in the request to build the certificate hierarchy) failed.
Tried to add the intermediate certificate by doing following in my client code:
X509Certificate2 leafCert = new X509Certificate2(File.ReadAllBytes(#"C:\Temp\TestLeaf.pfx"), "");
X509Certificate2(Convert.FromBase64String(File.ReadAllText(#"C:\Temp\TestIntermediate.pem"));
handler.ClientCertificates.Add(leafCert);
handler.ClientCertificates.Add(intermediateCert);
This did not send the intermediate certificate to the server. I verified this with the code block for httpsConnectionAdapterOptions.ClientCertificateValidation on the server side.
Question:
Is there a way to ensure that intermediate certificate is sent by the client (in addition to the leaf cert) to the server?

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

Accept self-signed certificates in Xamarin Android

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.

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.