Unity WebClient SSL Timeout - unity3d

I'm working on a Unity project that is reliyng on fetching data from a web API I set up on a public webserver. The server is currently set to self-signed ssl and requires the client to send certification to be able to read the data, if the client fails to send the cert the website returns with "403 forbidden".
I've tested this in the browser and postman and everything works fine.
I've also tested the exact same function in a pure visual studio project and it worked like a charm.
However, when I try this function in Unity I am met with the WebException "The request timed out
".
The way I'm currently doing it is via a WebClient, with an overrided method of WebRequest:
private void Connect()
{
ServicePointManager.CheckCertificateRevocationList = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback += ignoreCertCallback;
ServicePointManager.Expect100Continue = true;
using (var wc = new CertificateWebClient())
{
try
{
var responseBytes = wc.DownloadString(url);
Debug.Log(responseBytes);
Debug.Log(wc.ResponseHeaders);
}
catch (WebException e)
{
Debug.Log(e.ToString());
}
}
}
Override of WebRequest:
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
X509Certificate2 certificate = new X509Certificate2(#"C:\temp\ClientCert.pfx", "password");
request.ServerCertificateValidationCallback = delegate (System.Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{
return true;
};
Debug.Log(request.RequestUri);
(request as HttpWebRequest).ClientCertificates.Add(certificate);
request.Timeout = 2000;
return request;
}
Important to note is that I've tried the exact same functions inside of Unity with the "client.badssl.com" and their cert, and that also worked like a charm, returning the correct error codes when no cert is sent and everything and If I turn off client certification on my website, everything also works like charm...
From What I understand, It might be Mono that might be the problem as the certification is self-signed and not from a verified CA... But i've not been able to find a workaround... so any help would be great

What are your BG settings? I mean: is it on AWS? Express/NodeJS? WebGL? I am facing the same issue but when testing locally it works like a charm
I would suggest: to check if it is an infrastructure problem you might want to create a certificate for your domain (eg 'goodboy.mytest.io") that is certified from some free SSL providers (I can say LetsEncrypt just for testing) and launch a local server that's using that certificate, then go in your "hosts" file (depending on OS that you are currently running) and mock your localhost as "goodboy.mytest.io", so you can check if connecting to that domain everything goes fine without additional layers (usually placed between connection "bouncing" on web)
I'm following up this too

Related

If WebClient adds a cert to request.ClientCertificates will the cert be found at context.Request.ClientCertificate in the web app?

My client-side code uses WebClient and appends a certificate to ClientCertificates:
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
var x509 = GetMyCert(); // see note
request.ClientCertificates.Add( x509 );
return request;
}
NOTE: I've checked in the debugger and variable x509 does indeed contain a valid certificate object at this point in the code.
Is that not the right way to add the cert to the HttpWebRequest so that it is available to the web app?
Server-side, the certificate isn't showing up in the ProcessRequest method of the IHttpHandler:
context.Response.Clear();
// set some Response caching parameters here <snip>
HttpClientCertificate cert = context.Request.ClientCertificate;
if (cert.IsPresent)
{
Hooray();
}
else
{
BooHoo(); // we are here
}
The web.config is set to accept a client certificate:
<system.webServer>
<security>
<access sslFlags="Ssl, SslNegotiateCert" />
</security>
</system.webServer>
Is the web app configuration incomplete?
P.S. If I add the callback to the overridden GetWebRequest method:
System.Net.ServicePointManager.ServerCertificateValidationCallback =
delegate (Object obj, X509Certificate X509certificate, X509Chain chain,
System.Net.Security.SslPolicyErrors errors)
{
return (errors == SslPolicyErrors.None);
};
errors is SslPolicyErrors.None and the callback returns true. But I have not created any policy on the server, to my knowledge, unless there's a default of some kind.
The reason why the certificate is not showing up in the HttpContext is the certificate authentication hasn’t been established yet between the client-side and the server-side.
Simply speaking, when the web application is hosted in IIS, we disable other authentication modes in IIS and enable the IIS client certificate mapping authentication. the server requires a client certificate when the client tries to access the website/service.
Subsequently, the below function method will have a returned value.
public ActionResult About()
{
var result = System.Web.HttpContext.Current.Request.ClientCertificate;
ViewBag.Message = result.Subject+result.ServerSubject;
return View();
}
Please refer to the documentation for what is IIS Client Certificate Mapping Authentication and how to implement it in IIS.
https://learn.microsoft.com/en-us/iis/configuration/system.webserver/security/authentication/iisclientcertificatemappingauthentication/
https://learn.microsoft.com/en-us/troubleshoot/iis/configure-many-to-one-client-mappings
https://learn.microsoft.com/en-us/iis/manage/configuring-security/configuring-one-to-one-client-certificate-mappings
Feel free to let me know if there is anything I can help with.

Call to TLS 1.2 server with RestSharp works in console app, not in Xamarin Forms

I am communicating with a server that uses mutual TLS v1.2. I have been able to make this request in a c# console application, but when I copy this exact code to Xamarin forms, my RestClient gives me an exception: "Connection reset by peer" after a few seconds.
The code:
var client = new RestClient("https://api-sandbox.rabobank.nl/openapi/sandbox/payments/account-information/ais/v3/accounts");
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
client.ClientCertificates = new X509CertificateCollection() { certificate };
client.Proxy = new WebProxy();
var request = new RestRequest(Method.GET);
var response = client.Execute(request);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Content);
I am unable to share my API keys and such, for obvious reasons. These are added through headers and are removed from the code snippet.
Things I have tried:
I checked if the projects are set to use TLS 1.2, both iOS and Android are.
I tried this in simulators and on real devices
I tried using this library, but whenever I try to add the certificate to the clientcertificate list of the handler, I get a NotImplementedException thrown.

Liferay 7 MailService.sendMail from a custom portlet doesn't work only on HOST SERVER

I have a strange problem with a custom portlet on Liferay 7 to solve:
MailService.sendMail is working from MY COMPUTER with google smtp and a personal account: this means that the code is working...
On my HOST SERVER sending emails with the final-smtp works correctly: I tried both root and liferay user with telnet final-smtp port.
On the Liferay server on HOST SERVER, send e-mails works correctly: if I forget the password, Liferay send me the e-mail.
But ... if I try to send email with my portlet from Liferay on HOST SERVER it doesn't work without any error. I'm using Liferay MailService.sendMail. I post the code but it works (on MY COMPUTER).
I get the service in this way:
#Reference(unbind = "-")
protected void setMailService(MailService mailService) {
_mailService = mailService;
}
And the calling code is in the following:
InternetAddress fromAddress = null;
String newsletterPrefix = null;
InternetAddress toAddress = null;
try {
String smtpUser = PropsUtil.get(
"newsletter.send.mail.smtp.user");
String smtpToUser = PropsUtil.get(
"newsletter.send.mail.smtp.to.user");
if (Validator.isNotNull(smtpUser)) {
fromAddress = new InternetAddress(smtpUser);
}
if (Validator.isNotNull(smtpToUser)) {
toAddress = new InternetAddress(smtpToUser);
}
}
catch (Exception e) {
_log.error(e, e);
result = false;
}
MailMessage mailMessage = new MailMessage(
fromAddress, toAddress, subject, body, true);
mailMessage.setBCC(addressList);
_mailService.sendEmail(mailMessage);
There could be several reasons behind this, some not even code related.
I see you are using this code for a newsletter, which suggests you are using a smtp service that is meant for this.
It could be that your server is in fact sending the email, with success, but the smtp server is simply blocking, rejecting or marking to resend later. Moreover, that server might be configured to not send an error message, or sending an error message in the form of a successful delivery, but the data contains the error.
I would start checking you mail server configuration, and the accounts permissions, then its logs.
Also, you might consider using plugins for mass mail delivery, like this one: https://www.e-systems.tech/blog/-/blogs/connecting-liferay-to-mailgun
Few things you can do to debug this problem:
Make sure you are deploying the intended code on HOST machine. (Silly suggestion, but many times this is the problem.)
Try to set following package's Log level to ALL/DEBUG to see if it shows any problem in logs.com.liferay.mail.service

ASP double hop request in kerberos delegation scenario

Please help!
I need my asp application to request remote systems with credentials of impersonated user. But always get 401 Unauthorized errors.
I made all configurations from here: https://support.microsoft.com/en-us/help/810572/how-to-configure-an-asp-net-application-for-a-delegation-scenario
Kerberos is configured and working in my app and my test remote app(i see kerberos tickets in fiddler). Delegation, spns and everything is configured.
Thats my code usnig System.Net.Http.httpclient:
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
PreAuthenticate = true
};
using (HttpClient client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
var method = new HttpMethod("GET");
var request = new HttpRequestMessage(method, "http://testdelegationapp.avp.ru/");
var response = client.SendAsync(request).Result;
}
In fact http request is made by Apppool account (I get 401 error when restricting access to Apppool account in remote app IIS)
Here: How to get HttpClient to pass credentials along with the request?
is claimed that HttpClient cant pass security token to another thread, and its better to use synchronous methods of System.Net.WebClient
Code using webclient:
var wi = (WindowsIdentity)HttpContext.User.Identity;
var wic = wi.Impersonate();
try
{
string URI = "http://testdelegationapp.avp.ru/";
using (WebClient wc = new WebClient())
{
wc.UseDefaultCredentials = true;
string response = wc.DownloadString(URI);
}
}
finally
{
wic.Undo();
}
Result is even worse, the same 401 error, but in fiddler i can see that webclient using NTLM ticket to get to remote app!
Configuring of flowing tokens throw threads from here :Unable to authenticate to ASP.NET Web Api service with HttpClient
doesnt help either. SecurityContext.IsWindowsIdentityFlowSuppressed() is false.
WindowsIdentity.GetCurrent().Name and Thread.CurrentPrincipal.Identity.Name shows impersonated user as it should be.
All that time problem was in chrome browser, by default it prohobits kerberos delegation. You shoud add the following to registry:
Path: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome ;
string: AuthNegotiateDelegateWhitelist ;
value: *.avp.ru
So, now my working configuration is
HttpClient for web requests.
ASP impersonation ON in IIS if you want to execute all your app under
delegated credentials. If you want method specific delegation, then use:
var wi = (WindowsIdentity)HttpContext.User.Identity;
var wic = wi.Impersonate();
wic.Undo();
HttpClient executes request in another thread , so in aspnet_config.config we need following changes:
<legacyImpersonationPolicy enabled="false"/>
<alwaysFlowImpersonationPolicy enabled="true"/>
You can find aspnet_config.config in:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet.config
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\aspnet.config
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet.config

SASL authorization failing while connecting to XMPP server

I am trying to connect to gmail using SMACK API through XMPP server. but getting the
error : SASL authentication failed using mechanism PLAIN
you can check a glimpse of code. I got it from net only
ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
connection = new XMPPConnection(connConfig);
connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
I checked in the smack debug window. it says in XML :
< invalid-authzid />
I am already having account on gmail and my gtalk is also running.
You need to set the authentication before you connect viz
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
must appear before connection.connect().
See my blog.
ConnectionConfiguration cc = new ConnectionConfiguration(
"vietnam.agilemobile.com", 5222, vietnam.agilemobile.com");
XMPPConnection connection = new XMPPConnection(cc);
try {
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.connect();
Log.e("LOGIN", "" + 111);
// You have to put this code before you login
Log.e("LOGIN", "" + 222);
// You have to specify your gmail addres WITH #gmail.com at the end
connection.login("nemodo", "123456", "resource");
Log.e("LOGIN", "" + 333);
// See if you are authenticated
System.out.println(connection.isAuthenticated());
} catch (XMPPException e1) {
e1.printStackTrace();
}
I also get this mistake, but i can not work.
For anyone looking for possible solutions to this many years after this was originally asked and answered, I recently was able to get past this authentication error by explicitly setting the authzid value on the XMPPTCPConnectionConfiguration.
I was running into an issue where my connection configuration worked fine for some client XMPP servers, but not for others, even though they were all using SASL PLAIN authentication. After some troubleshooting, I learned that the ones that were failing were expecting an authzid value. After adjusting my code to set this, it works in both the environments that were working before, as well as the environments that were failing.
Here is how I am building my connection configuration:
XMPPTCPConnectionConfiguration.builder()
.setHost(XMPP_DOMAIN)
.setXmppDomain(XMPP_DOMAIN)
.setPort(XMPP_PORT)
.setCompressionEnabled(true) // optional, not all servers will support this
.setUsernameAndPassword(XMPP_USER, XMPP_PASSWORD)
.setResource(XMPP_RESOURCE)
.setAuthzid(JidCreate.entityBareFrom(String.format("%s#%s", XMPP_USER, XMPP_DOMAIN))) // <-- this was the change I needed
.build();
Specifically I needed to add this line:
.setAuthzid(JidCreate.entityBareFrom(String.format("%s#%s", XMPP_USER, XMPP_DOMAIN)))