HttpWebRequest.GetRequestStream() https certificate error exception

I am using a self-signed temp certificate on my https server. I think it is the cause of the exception I pasted below. Is there a way I can use my self-signed certificate? Thanks.

OnUserLoginReq exception:System.Net.WebException: Error: ConnectFailure (Unexpected error while trying to call method_GetSecurityPolicyBlocking : System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.WebException: Error getting response stream (Write: The authentication or decryption has failed.): SendFailure ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: Invalid certificate received from server. Error code: 0xffffffff800b010a at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates) [0x00000] in :0 at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 () [0x00000] in :0 at Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process () [0x00000] in :0 at (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process () at Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg) [0x00000] in :0 at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00000] in :0 --- End of inner exception stack trace --- at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x00000] in :0 --- End of inner exception stack trace --- at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in :0 at System.Net.HttpWebRequest.GetResponse () [0x00000] in :0 at System.Net.WebConnection.DownloadPolicy (System.String url, System.String proxy) [0x00000] in :0 at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in :0 --- End of inner exception stack trace --- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in :0 at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in :0 at UnityEngine.UnityCrossDomainHelper+WebRequestPolicyProvider.GetPolicy (System.String policy_url) [0x00000] in :0 at UnityEngine.UnityCrossDomainHelper.GetSecurityPolicy (System.String requesturi_string, IPolicyProvider policyProvider) [0x00000] in :0 at UnityEngine.UnityCrossDomainHelper.GetSecurityPolicyForDotNetWebRequest (System.String requesturi_string, System.Reflection.MethodInfo policyProvidingMethod) [0x00000] in :0 at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in :0 --- End of inner exception stack trace --- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in :0 at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in :0 at System.Net.WebConnection.CheckUnityWebSecurity (System.Net.HttpWebRequest request) [0x00000] in :0 ) ---> System.Security.SecurityException: Unexpected error while trying to call method_GetSecurityPolicyBlocking : System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.WebException: Error getting response stream (Write: The authentication or decryption has failed.): SendFailure ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: Invalid certificate received from server. Error code: 0xffffffff800b010a at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates) [0x00000] in :0 at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 () [0x00000] in :0 at Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process () [0x00000] in :0 at (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process () at Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg) [0x00000] in :0 at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00000] in :0 --- End of inner exception stack trace --- at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x00000] in :0 --- End of inner exception stack trace --- at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in :0 at System.Net.HttpWebRequest.GetResponse () [0x00000] in :0 at System.Net.WebConnection.DownloadPolicy (System.String url, System.String proxy) [0x00000] in :0 at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in :0 --- End of inner exception stack trace --- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in :0 at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in :0 at UnityEngine.UnityCrossDomainHelper+WebRequestPolicyProvider.GetPolicy (System.String policy_url) [0x00000] in :0 at UnityEngine.UnityCrossDomainHelper.GetSecurityPolicy (System.String requesturi_string, IPolicyProvider policyProvider) [0x00000] in :0 at UnityEngine.UnityCrossDomainHelper.GetSecurityPolicyForDotNetWebRequest (System.String requesturi_string, System.Reflection.MethodInfo policyProvidingMethod) [0x00000] in :0 at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&) at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in :0 --- End of inner exception stack trace --- at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in :0 at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in :0 at System.Net.WebConnection.CheckUnityWebSecurity (System.Net.HttpWebRequest request) [0x00000] in :0 at System.Net.WebConnection.LoggedThrow (System.Exception e) [0x00000] in :0 at System.Net.WebConnection.CheckUnityWebSecurity (System.Net.HttpWebRequest request) [0x00000] in :0 at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x00000] in :0 --- End of inner exception stack trace --- at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult asyncResult) [0x00000] in :0 at System.Net.HttpWebRequest.GetRequestStream () [0x00000] in :0 at NetHandler.OnUserLoginReq (.BaseCharacter rp) [0x00147] in C:\Users\mrieker\phoenix\viewer01\Assets\Scripts\Network\NetHandler.cs:86 UnityEngine.Debug:Log(Object) NetHandler:OnUserLoginReq(BaseCharacter) (at Assets/Scripts/Network/NetHandler.cs:122) Messenger`1:Broadcast(String, BaseCharacter, MessengerMode) (at Assets/Scripts/CSMessenger Extended/Messenger.cs:145) Messenger`1:Broadcast(String, BaseCharacter) (at Assets/Scripts/CSMessenger Extended/Messenger.cs:136) g_login:DoFollowUpWindow(Int32) (at Assets/Scripts/Gui/Login/g_login.cs:178)

I had the same problem and this post helped me to solve it.

Just add the following line before making your request:

ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;

And this method:

public bool MyRemoteCertificateValidationCallback(System.Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
	bool isOk = true;
	// If there are errors in the certificate chain, look at each error to determine the cause.
	if (sslPolicyErrors != SslPolicyErrors.None) {
		for (int i=0; i<chain.ChainStatus.Length; i++) {
			if (chain.ChainStatus *.Status != X509ChainStatusFlags.RevocationStatusUnknown) {*
  •  		chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;*
    
  •  		chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;*
    
  •  		chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan (0, 1, 0);*
    
  •  		chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;*
    
  •  		bool chainIsValid = chain.Build ((X509Certificate2)certificate);*
    
  •  		if (!chainIsValid) {*
    
  •  			isOk = false;*
    
  •  		}*
    
  •  	}*
    
  •  }*
    
  • }*
  • return isOk;*
    }

Okay I ran into a similar problem: A unity application I’m working on calls some .net logic in a dll file. That dll makes a .Net HttpWebRequest, which would run fine from visual stuido but get an error message similar to the one above - the request somehow being blocked by the security policy.

The problem, when caused by a .net web request, yielded very few hits on google (if you don’t read Korean, that is) so I thought I’d post my solution. There were plenty of hits on the problem caused by running in webplayer, and my solution is mostly a boil-down and combination of those.

Problem was solved by putting a crossdomain.xml file in the root of the unity project. The crossdomain.xml must be utf-8 encoded according to this (also has an example of a crossdomain.xml): crossdomain.xml policy file - Unity Answers

For my problem, the crossdomain.xml also had to specify “to-ports” - i.e.

<allow-access-from domain="*" to-ports="1200-1220"/> 

For more info, check out the security sandbox section of the unity manual: http://unity3d.com/support/documentation/Manual/Security%20Sandbox.html

The crypto problem still exists in Unity 5 (5.0.1f1). I’ve been testing HTTPS with a SHA-384-signed certificate and get this error on iOS only:

Adding cached authorization header: Basic ..............
ERROR building certificate chain: System.ArgumentException: certificate ---> System.Security.Cryptography.CryptographicException: Unsupported hash algorithm: 1.2.840.113549.1.1.12
  at Mono.Security.X509.X509Certificate.VerifySignature (System.Security.Cryptography.RSA rsa) [0x00000] in :0 
  at Mono.Security.X509.X509Certificate.VerifySignature (System.Security.Cryptography.AsymmetricAlgorithm aa) [0x00000] in :0 
  at System.Security.Cryptography.X509Certificates.X509Chain.IsSignedWith  (System.Security.Cryptography.X509Certificates.X509Certificate2 signed, System.Security.Cryptography.AsymmetricAlgorithm pubkey) [0x00000] in :0 
  at System.Security.Cryptography.X509Certificates.X509Chain.Process (Int32 n) [0x00000] in :0 
  at System.Security.Cryptography.X509Certificates.X509Chain.ValidateChain (X509ChainStatusFlags flag) [0x00000] in :0 
  at System.Security.Cryptography.X509Certificates.X509Chain.Build (System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) [0x00000] in :0 
  --- End of inner exception stack trace ---
  at System.Security.Cryptography.X509Certificates.X509Chain.Build (System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) [0x00000] in :0 
  at System.Net.ServicePointManager+ChainValidationHelper.ValidateChain (Mono.Security.X509.X509CertificateCollection certs) [0x00000] in :0 
Please, report this problem to the Mono team

This problem does not appear when testing in the Unity player and while running on Android: HTTPS works fine on both.

I’ve done a little digging and discovered that Mono.Runtime.GetDisplayName returns “2.6.5 (tarball)”. Is Unity 5 still using such an ancient version of Mono? I checked the source for Mono 2.8 and, sure enough, the VerifySignature method mentioned in the exception doesn’t recognize SHA-2 algorithms:

internal bool VerifySignature (RSA rsa) 
{
    RSAPKCS1SignatureDeformatter v = new RSAPKCS1SignatureDeformatter (rsa);
    switch (m_signaturealgo) {
        // MD2 with RSA encryption 
        case "1.2.840.113549.1.1.2":
            // maybe someone installed MD2 ?
            v.SetHashAlgorithm ("MD2");
            break;
        // MD5 with RSA encryption 
        case "1.2.840.113549.1.1.4":
            v.SetHashAlgorithm ("MD5");
            break;
        // SHA-1 with RSA Encryption 
        case "1.2.840.113549.1.1.5":
        case "1.3.14.3.2.29":
            v.SetHashAlgorithm ("SHA1");
            break;
        default:
            throw new CryptographicException ("Unsupported hash algorithm: " + m_signaturealgo);
    }
    return v.VerifySignature (this.Hash, this.Signature);
}

If this issue was fixed with a patch, then I’m not seeing the results. Something is still broken.

If it’s any help, my HTTPS REST code uses HttpWebRequest.

I’m going to look for workarounds (WWW looks interesting), but this is very disappointing. Why not upgrade Mono and not only resolve this issue once and for all, but also satisfy a huge and growing number of Unity developers?

Unity’s (v4.3) version of mono does not support SHA-256 SSL Certs. If its SHA-256 then that’s your problem. You will need to create a new cert (or rekey the old one) to work with SHA-1.

http://fogbugz.unity3d.com/default.asp?602783_4ddsl9l014uuvquo Here’s my bug report on the issue. The bug doesn’t exist in unity 5.0, which will probably be out sometime next year, but it does exist in 4.5 and 4.4 (and apparently 4.3). I’m not sure if there is an earlier version that does not have the bug. As you can see in the bug report, I have asked if there was any way the bug could be fixed sooner than 5.0 and received this response “I’ll send this issue to our developers for resolution. At the time we cannot say when the fix will be available to the public.”

Edit: As I mentioned, this is probably a different issue than the one mentioned here.

I guys i’ve the similar problem, for read a xml from a link i see the error:

“TlsException: Invalid certificate received from server. Error code: 0xffffffff800b010f”

Can someone help me?

Thanks :wink:

using UnityEngine;
using System.Collections;
using System.Collections.Generic; //Needed for Lists
using System.Xml; //Needed for XML functionality
using System.Xml.Serialization; //Needed for XML Functionality
using System.IO;
using System.Net;
using System.Xml.Linq; //Needed for XDocument

public class Networking : MonoBehaviour
{

private string filepath = "https://www.mytestsite.com/service/xml/testfile.xml";

public void Read()
{
    Debug.Log("eccolo");
    
    XDocument doc = XDocument.Load(filepath);

    foreach (XElement el in doc.Root.Elements())
    {
        Debug.Log(string.Format("{0} {1}", el.Name, el.Attribute("id").Value));
        Debug.Log(string.Format("  Attributes:"));
        foreach (XAttribute attr in el.Attributes())
            Debug.Log(string.Format("    {0}", attr));
        Debug.Log(string.Format("  Elements:"));

        foreach (XElement element in el.Elements())
            Debug.Log(string.Format("    {0}: {1}", element.Name, element.Value));
    }
}

}