Problems with TLS handshake

Hi, I am trying to connect to an API stream using a TcpClient and the SslStream from .NET, but I keep getting stuck with an error when I am about to authenticate client. I need a TCP connection since I want a http stream, and I need SSL since the API requires you to connect via HTTPS.

The interesting thing is that connecting to the TLS stream works with Curl on the same machine. Others have told me the problem might be that Unity/.NET does not have an updated CA for the certificate the API uses (letsencrypt). How do I solve this?

The error is:

TlsException: Handshake failed - error code: UNITYTLS_INTERNAL_ERROR, verify result: 4294938112
Mono.Unity.Debug.CheckAndThrow (Mono.Unity.UnityTls+unitytls_errorstate errorState, Mono.Unity.UnityTls+unitytls_x509verify_result verifyResult, System.String context, Mono.Security.Interface.AlertDescription defaultAlert) (at <0463b2ef957545c0a51b42f372cd4fbb>:0)
Mono.Unity.UnityTlsContext.ProcessHandshake () (at <0463b2ef957545c0a51b42f372cd4fbb>:0)
Mono.Net.Security.MobileAuthenticatedStream.ProcessHandshake (Mono.Net.Security.AsyncOperationStatus status) (at <0463b2ef957545c0a51b42f372cd4fbb>:0)
(wrapper remoting-invoke-with-check) Mono.Net.Security.MobileAuthenticatedStream.ProcessHandshake(Mono.Net.Security.AsyncOperationStatus)
Mono.Net.Security.AsyncHandshakeRequest.Run (Mono.Net.Security.AsyncOperationStatus status) (at <0463b2ef957545c0a51b42f372cd4fbb>:0)
Mono.Net.Security.AsyncProtocolRequest+<ProcessOperation>d__24.MoveNext () (at <0463b2ef957545c0a51b42f372cd4fbb>:0)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0)
Mono.Net.Security.AsyncProtocolRequest+<StartOperation>d__23.MoveNext () (at <0463b2ef957545c0a51b42f372cd4fbb>:0)
Rethrow as AuthenticationException: A call to SSPI failed, see inner exception.
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0)
Mono.Net.Security.MobileAuthenticatedStream+<ProcessAuthentication>d__47.MoveNext () (at <0463b2ef957545c0a51b42f372cd4fbb>:0)
Rethrow as AggregateException: One or more errors occurred.
System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Threading.Tasks.Task.Wait (System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Threading.Tasks.Task.Wait () (at <695d1cc93cca45069c528c15c9fdd749>:0)
Mono.Net.Security.MobileAuthenticatedStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, System.Boolean checkCertificateRevocation) (at <0463b2ef957545c0a51b42f372cd4fbb>:0)
System.Net.Security.SslStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, System.Boolean checkCertificateRevocation) (at <0463b2ef957545c0a51b42f372cd4fbb>:0)
HttpClient.RetrieveAisStream () (at Assets/Scripts/HttpClient.cs:166)
System.Threading.ThreadHelper.ThreadStart_Context (System.Object state) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Threading.ThreadHelper.ThreadStart () (at <695d1cc93cca45069c528c15c9fdd749>:0)
UnityEngine.<>c:<RegisterUECatcher>b__0_0(Object, UnhandledExceptionEventArgs)

My code looks like this:

System.Net.ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, sslPolicyErrors) => true;
  
using (TcpClient client = new TcpClient())
{
    client.Connect("live.ais.barentswatch.no", 80);
  
    using (SslStream stream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
    {
        try
        {
            stream.AuthenticateAsClient("live.ais.barentswatch.no", null, SslProtocols.Tls12, false);
        }
        catch (AuthenticationException e)
        {
            if (e.InnerException != null)
            {
                Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
            }
            Console.WriteLine("Authentication failed - closing the connection.");
            client.Close();
            return;
        }
        // continues...

and:

public static bool ValidateServerCertificate(
          object sender,
          X509Certificate certificate,
          X509Chain chain,
          SslPolicyErrors sslPolicyErrors)
{
    print("Inside callback
");
    if (sslPolicyErrors == SslPolicyErrors.None)
        return true;
  
    Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
  
    // Do not allow this client to communicate with unauthenticated servers.
    return false;
}

Did you find a solution? I’m having the same issue.

HI, we are getting the same error. We can use Postman to login but within unity, we are getting the same error as above. Has anyone figured this out?

System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception. ---> Mono.Security.Interface.TlsException: Handshake failed - error code: UNITYTLS_INTERNAL_ERROR, verify result: 4294957312
  at Mono.Unity.Debug.CheckAndThrow (Mono.Unity.UnityTls+unitytls_errorstate errorState, Mono.Unity.UnityTls+unitytls_x509verify_result verifyResult, System.String context, Mono.Security.Interface.AlertDescription defaultAlert) [0x00036] in :0 
  at Mono.Unity.UnityTlsContext.ProcessHandshake () [0x00082] in :0 
  at Mono.Net.Security.MobileAuthenticatedStream.ProcessHandshake (Mono.Net.Security.AsyncOperationStatus status, System.Boolean renegotiate) [0x000da] in :0

@EwanMe - @sandro-ixt - @kinetisense - I see there are three people here with the same issue. Let me try to see if I can help here. I believe you are correct in the fact that the issue you’re experiencing might be related to an outdated CA for the Let’s Encrypt certificate. In order to resolve this, you can try updating the CA certificates in Unity. Like this:

Download the latest CA certificates from Mozilla: https://curl.haxx.se/docs/caextract.html

Place the downloaded cacert.pem file in your Unity project’s Assets folder.

Use the following code to load the new CA certificates and set them as default:

using System.IO;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;

public class CertificateUpdater : MonoBehaviour
{
    void Start()
    {
        UpdateCACertificates();
    }

    private void UpdateCACertificates()
    {
        TextAsset cacertFile = Resources.Load<TextAsset>("cacert");

        if (cacertFile == null)
        {
            Debug.LogError("Failed to load cacert.pem file.");
            return;
        }

        using (var stream = new MemoryStream(cacertFile.bytes))
        {
            var certificates = new X509Certificate2Collection();
            certificates.Import(stream);

            System.Net.ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, sslPolicyErrors) =>
            {
                foreach (X509Certificate2 ca in certificates)
                {
                    chain.ChainPolicy.ExtraStore.Add(ca);
                }

                chain.Build(new X509Certificate2(cert));
                return true;
            };
        }
    }
}

After implementing these changes, your Unity application should be able to connect to the API stream without the TLS handshake issue.

Remember to remove the original ServerCertificateValidationCallback line from your code, as it will be replaced by the updated callback in the CertificateUpdater script:

// Remove this line:
System.Net.ServicePointManager.ServerCertificateValidationCallback = (message, cert, chain, sslPolicyErrors) => true;

Let me know if this gets you guys closer to an answer.

Having looked into this extensively for us, where I know our credentials were correctly configured on backend and frontend. I was absolutely stumped and was going to blame Unity for yet another obscure bug.

Turns out it was the certificate and Unity not working well together. The certificate was missing intermediary certificates which Unity was not able to resolve but the frontend (website) could do so automatically.

So for those of you encountering this bug. Make sure your installed certificates has intermediary certificates included.

Hope this helps someone.