Exemple #1
0
        public virtual void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            string authMethod = challenge.ProtectionSpace.AuthenticationMethod;

            Console.WriteLine("DidReceiveChallenge {0}", authMethod);

            if (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodServerTrust")
            {
                var trustRef    = challenge.ProtectionSpace.ServerSecTrust;
                var trustResult = SecTrustResult.Invalid;
                if (trustRef != null)
                {
                    trustResult = trustRef.Evaluate();
                }

                NSUrlCredential cred = NSUrlCredential.FromTrust(trustRef);
                completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, cred);
            }
            else if (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodHTTPBasic")
            {
                showAuthenticationViewForChallenge(challenge, completionHandler);
            }
            else if ((challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodNTLM") || (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodClientCertificate"))
            {
                handleChallengeforSession(challenge, completionHandler);
            }
            else
            {
                completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                //XamarinAlertController.showAlertViewForController(this, SDKErrorAuthNotSupportedTitle, SDKErrorAuthNotSupportedMessage);
            }
        }
 public void FromTrust()
 {
     using (var trust = GetTrust())
         using (var creds = NSUrlCredential.FromTrust(trust)) {
             Assert.Null(creds.Certificates, "Certificates");
             Assert.False(creds.HasPassword, "HasPassword");
             Assert.Null(creds.SecIdentity, "SecIdentity");
             Assert.Null(creds.Password, "Password");
             Assert.That(creds.Persistence, Is.EqualTo(NSUrlCredentialPersistence.ForSession), "Persistence");
             Assert.Null(creds.User, "User");
         }
 }
            private void sslErrorVerify(NSUrlSessionTask task, X509Certificate2 root, X509Chain chain, SslPolicyErrors errors,
                                        Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler, NSUrlAuthenticationChallenge challenge)
            {
                var hostname = task.CurrentRequest.Url.Host;
                var result   = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors);

                if (result)
                {
                    completionHandler(
                        NSUrlSessionAuthChallengeDisposition.UseCredential,
                        NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                }
                else
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                }
            }
Exemple #4
0
        public void FromTrust()
        {
            using (var trust = GetTrust())
                using (var creds = NSUrlCredential.FromTrust(trust)) {
                    Assert.Null(creds.Certificates, "Certificates");
                    Assert.False(creds.HasPassword, "HasPassword");
                    Assert.Null(creds.SecIdentity, "SecIdentity");
                    Assert.Null(creds.Password, "Password");
                    var expectedPersistence = NSUrlCredentialPersistence.ForSession;
#if __MACOS__
                    if (!TestRuntime.CheckSystemVersion(PlatformName.MacOSX, 10, 8))
                    {
                        expectedPersistence = (NSUrlCredentialPersistence)uint.MaxValue;
                    }
#endif
                    Assert.That(creds.Persistence, Is.EqualTo(expectedPersistence), "Persistence");
                    Assert.Null(creds.User, "User");
                }
        }
Exemple #5
0
        public override void ReceivedAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
        {
            if (challenge.PreviousFailureCount > 0)
            {
                showError = false;
                challenge.Sender.CancelAuthenticationChallenge(challenge);
                return;
            }

            if (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodServerTrust")
            {
                challenge.Sender.UseCredentials(NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerTrust), challenge);
            }


            if (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodDefault" && _credential != null)
            {
                challenge.Sender.UseCredentials(_credential, challenge);
            }
        }
        public override void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            if (Reference == null || !Reference.TryGetTarget(out FormsWebViewRenderer renderer))
            {
                return;
            }
            if (renderer.Element == null)
            {
                return;
            }
            if (challenge == null || challenge.ProtectionSpace == null || challenge.ProtectionSpace.AuthenticationMethod == null)
            {
                return;
            }

            if (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodServerTrust")
            {
                if (renderer.Element.IgnoreSSLErrors)
                {
                    using (var cred = NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust))
                    {
                        completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.UseCredential, cred);
                    }
                }
                else
                {
                    completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(renderer.Element.Username) && !string.IsNullOrEmpty(renderer.Element.Password))
                {
                    var crendential = new NSUrlCredential(renderer.Element.Username, renderer.Element.Password, NSUrlCredentialPersistence.ForSession);

                    completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, crendential);
                }
            }
        }
Exemple #7
0
        public override void ReceivedAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
        {
            if (challenge.PreviousFailureCount > 0)
            {
                challenge.Sender.CancelAuthenticationChallenge(challenge);
                return;
            }

            if (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodServerTrust")
            {
                challenge.Sender.UseCredentials(NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerTrust), challenge);
            }

            if (_ChallengeAction != null)
            {
                _ChallengeAction(connection, challenge);
            }

//			if (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodDefault" && Application.Account != null && Application.Account.Login != null && Application.Account.Password != null)
//			{
//				challenge.Sender.UseCredentials(NSUrlCredential.FromUserPasswordPersistance(Application.Account.Login, Application.Account.Password, NSUrlCredentialPersistence.None), challenge);
//			}
        }
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                if (!This.customSSLVerification)
                {
                    goto doDefault;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust")
                {
                    goto doDefault;
                }

                if (ServicePointManager.ServerCertificateValidationCallback == null)
                {
                    goto doDefault;
                }

                // Convert Mono Certificates to .NET certificates and build cert
                // chain from root certificate
                var serverCertChain   = challenge.ProtectionSpace.ServerSecTrust;
                var chain             = new X509Chain();
                X509Certificate2 root = null;
                var errors            = SslPolicyErrors.None;

                if (serverCertChain == null || serverCertChain.Count == 0)
                {
                    errors = SslPolicyErrors.RemoteCertificateNotAvailable;
                    goto sslErrorVerify;
                }

                if (serverCertChain.Count == 1)
                {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var netCerts = Enumerable.Range(0, serverCertChain.Count)
                               .Select(x => serverCertChain[x].ToX509Certificate2())
                               .ToArray();

                for (int i = 1; i < netCerts.Length; i++)
                {
                    chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
                }

                root = netCerts[0];

                chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode      = X509RevocationMode.NoCheck;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllowUnknownCertificateAuthority;

                try {
                    if (!chain.Build(root))
                    {
                        errors = SslPolicyErrors.RemoteCertificateChainErrors;
                        goto sslErrorVerify;
                    }
                } catch (System.Security.Cryptography.CryptographicException) {
                    // As best we can tell, a XAMMIT (spurious).
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var subject   = root.Subject;
                var subjectCn = cnRegex.Match(subject).Groups[1].Value;

                if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn))
                {
                    errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                    goto sslErrorVerify;
                }

sslErrorVerify:
                // NachoCove: Add this to make it look like other HTTP client
                var url = task.CurrentRequest.Url.ToString();
                var request = new HttpWebRequest(new Uri(url));
                // End of NachoCove
                bool result = ServicePointManager.ServerCertificateValidationCallback(request, root, chain, errors);

                if (result)
                {
                    completionHandler(
                        NSUrlSessionAuthChallengeDisposition.UseCredential,
                        NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                }
                else
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                }
                return;

doDefault:
                if (null != This.Credentials)
                {
                    var authenticationType = AuthenticationTypeFromAuthenticationMethod(challenge.ProtectionSpace.AuthenticationMethod);
                    var uri = UriFromNSUrlProtectionSpace(challenge.ProtectionSpace);
                    if (null != authenticationType && null != uri)
                    {
                        var specifedCredential = This.Credentials.GetCredential(uri, authenticationType);
                        var state = getResponseForTask(task);
                        if (null != specifedCredential &&
                            null != specifedCredential.UserName && null != specifedCredential.Password)
                        {
                            if (specifedCredential == state.PresentedCredential)
                            {
                                completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, null);
                            }
                            else
                            {
                                state.PresentedCredential = specifedCredential;
                                var credential = new NSUrlCredential(
                                    specifedCredential.UserName,
                                    specifedCredential.Password,
                                    NSUrlCredentialPersistence.ForSession);
                                completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                            }
                            return;
                        }
                    }
                }
                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                return;
            }
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
               

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM) {
                    NetworkCredential credentialsToUse;

                    if (This.Credentials != null) {
                        if (This.Credentials is NetworkCredential) {
                            credentialsToUse = (NetworkCredential)This.Credentials;
                        } else {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = This.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    return;
                }
#if !XAMARIN_MODERN
                if (!This.customSSLVerification) {
                    goto doDefault;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust") {
                    goto doDefault;
                }

                if (ServicePointManager.ServerCertificateValidationCallback == null) {
                    goto doDefault;
                }

                // Convert Mono Certificates to .NET certificates and build cert 
                // chain from root certificate
                var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;
                var chain = new X509Chain();
                X509Certificate2 root = null;
                var errors = SslPolicyErrors.None;

                if (serverCertChain == null || serverCertChain.Count == 0) { 
                    errors = SslPolicyErrors.RemoteCertificateNotAvailable;
                    goto sslErrorVerify;
                }

                if (serverCertChain.Count == 1) {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var netCerts = Enumerable.Range(0, serverCertChain.Count)
                    .Select(x => serverCertChain[x].ToX509Certificate2())
                    .ToArray();

                for (int i = 1; i < netCerts.Length; i++) {
                    chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
                }

                root = netCerts[0];

                chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

                if (!chain.Build(root)) {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var subject = root.Subject;
                var subjectCn = cnRegex.Match(subject).Groups[1].Value;

                if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn)) {
                    errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                    goto sslErrorVerify;
                }

            sslErrorVerify:
                var hostname = task.CurrentRequest.Url.Host;
                bool result = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors);
                if (result) {
                    completionHandler(
                        NSUrlSessionAuthChallengeDisposition.UseCredential,
                        NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                } else {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                }
                return;

            doDefault:
#endif
                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                return;
            }
Exemple #10
0
        public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM)
            {
                if (_secureHttpClientHandler.Credentials != null)
                {
                    NetworkCredential credentialsToUse;
                    var credentials = _secureHttpClientHandler.Credentials as NetworkCredential;
                    if (credentials != null)
                    {
                        credentialsToUse = credentials;
                    }
                    else
                    {
                        var uri = GetResponseForTask(task).Request.RequestUri;
                        credentialsToUse = _secureHttpClientHandler.Credentials.GetCredential(uri, "NTLM");
                    }
                    var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                    completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    return;
                }
            }

            if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust)
            {
                challenge.ProtectionSpace.ServerSecTrust.SetAnchorCertificates(_trustedRoots);

                var hostname = task.CurrentRequest.Url.Host;
                if (_certificatePinner != null && _certificatePinner.HasPin(hostname))
                {
                    var serverTrust = challenge.ProtectionSpace.ServerSecTrust;
                    var status      = serverTrust.Evaluate();
                    if (status == SecTrustResult.Proceed || status == SecTrustResult.Unspecified)
                    {
                        var serverCertificate = serverTrust[0];
                        var x509Certificate   = serverCertificate.ToX509Certificate2();
                        var match             = _certificatePinner.Check(hostname, x509Certificate.RawData);
                        if (match)
                        {
                            completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, NSUrlCredential.FromTrust(serverTrust));
                        }
                        else
                        {
                            var inflightRequest = GetResponseForTask(task);
                            inflightRequest.Error = new NSError(NSError.NSUrlErrorDomain, (nint)(long)NSUrlError.ServerCertificateUntrusted);
                            completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                        }
                        return;
                    }
                }
            }

            if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodClientCertificate)
            {
                var certificate = _secureHttpClientHandler.ClientCertificate;
                if (certificate == null)
                {
                    var url   = task.CurrentRequest.Url;
                    var space = new NSUrlProtectionSpace(url.Host, url.Port, url.Scheme, null, NSUrlProtectionSpace.AuthenticationMethodClientCertificate);
                    certificate = NSUrlCredentialStorage.SharedCredentialStorage.GetDefaultCredential(space);
                }
                if (certificate != null)
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, certificate);
                    return;
                }
            }

            completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
        }
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                // TODO: add NSUrlProtectionSpace.HTTPSProxy case

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM)
                {
                    NetworkCredential credentialsToUse;

                    if (nativeHandler.Credentials != null)
                    {
                        if (nativeHandler.Credentials is NetworkCredential)
                        {
                            credentialsToUse = (NetworkCredential)nativeHandler.Credentials;
                        }
                        else
                        {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = nativeHandler.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    return;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust)
                {
                    var errors = SslPolicyErrors.None;

                    if (nativeHandler.TLSConfig.DangerousAcceptAnyServerCertificateValidator)
                    {
                        goto sslErrorVerify;
                    }

                    var hostname = task.CurrentRequest.Url.Host;

                    // Convert java certificates to .NET certificates and build cert chain from root certificate
                    var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;

                    var netCerts = Enumerable.Range(0, serverCertChain.Count)
                                   .Select(x => serverCertChain[x].ToX509Certificate2())
                                   .ToList();

                    switch (nativeHandler.PinningMode)
                    {
                    case "CertificateOnly":

                        //Security.addProvider(new BouncyCastleProvider());
                        //CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");

                        var chain             = new X509Chain();
                        X509Certificate2 root = null;

                        // Build certificate chain and check for errors
                        if (serverCertChain == null || serverCertChain.Count == 0)
                        {    //no cert at all
                            errors = SslPolicyErrors.RemoteCertificateNotAvailable;
                            PinningFailureMessage = FailureMessages.NoCertAtAll;
                            goto sslErrorVerify;
                        }

                        if (serverCertChain.Count == 1)
                        {    //no root?
                            errors = SslPolicyErrors.RemoteCertificateChainErrors;
                            PinningFailureMessage = FailureMessages.NoRoot;
                            goto sslErrorVerify;
                        }

                        for (int i = 1; i < netCerts.Count; i++)
                        {
                            chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
                        }

                        //chain.ChainPolicy.CertificatePolicy.Add(new Oid("1.2.840.10045.2.1"));
                        chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain;
                        chain.ChainPolicy.RevocationMode      = X509RevocationMode.NoCheck;
                        chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                        chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllowUnknownCertificateAuthority;

                        root = netCerts[0];

                        /*if (!chain.Build(root))
                         * {
                         *  errors = SslPolicyErrors.RemoteCertificateChainErrors;
                         *  PinningFailureMessage = FailureMessages.ChainError;
                         *  goto sslErrorVerify;
                         * }*/

                        var subject   = root.Subject;
                        var subjectCn = cnRegex.Match(subject).Groups[1].Value;

                        if (string.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(hostname, subjectCn))
                        {
                            var subjectAn = root.ParseSubjectAlternativeName();

                            if (subjectAn.FirstOrDefault(s => Utility.MatchHostnameToPattern(hostname, s)) == null)
                            {
                                errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                                PinningFailureMessage = FailureMessages.SubjectNameMismatch;
                                goto sslErrorVerify;
                            }
                        }
                        break;

                    case "PublicKeysOnly":

                        if (nativeHandler.CertificatePinner != null)
                        {
                            if (!nativeHandler.CertificatePinner.HasPins(hostname))
                            {
                                errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                                PinningFailureMessage = FailureMessages.NoPinsProvided + " " + hostname;
                                goto sslErrorVerify;
                            }

                            if (!nativeHandler.CertificatePinner.Check(hostname, netCerts))
                            {
                                errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                                PinningFailureMessage = FailureMessages.PinMismatch;
                            }
                        }
                        break;
                    }

sslErrorVerify:
                    if (errors == SslPolicyErrors.None)
                    {
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                    }
                    else
                    {
                        completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                    }
                    return;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodClientCertificate)
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, nativeHandler.UrlCredential);

                    return;
                }

                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
            }
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM)
                {
                    NetworkCredential credentialsToUse;

                    if (This.Credentials != null)
                    {
                        if (This.Credentials is NetworkCredential)
                        {
                            credentialsToUse = (NetworkCredential)This.Credentials;
                        }
                        else
                        {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = This.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                        return;
                    }
                }

                if (!This.customSSLVerification)
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                    return;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust")
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                    return;
                }

                if (ServicePointManager.ServerCertificateValidationCallback == null)
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                    return;
                }

                // Convert Mono Certificates to .NET certificates and build cert
                // chain from root certificate
                var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;
                var chain           = new X509Chain();

                var netCerts = Enumerable.Range(0, serverCertChain.Count)
                               .Select(x => serverCertChain [x].ToX509Certificate2())
                               .ToArray();

                for (int i = 1; i < netCerts.Length; i++)
                {
                    chain.ChainPolicy.ExtraStore.Add(netCerts [i]);
                }

                X509Certificate2 root = netCerts [0];

                chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode      = X509RevocationMode.NoCheck;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllowUnknownCertificateAuthority;

                chain.Build(root);

                var  hostname = task.CurrentRequest.Url.Host;
                bool?result   = ServicePointManager.ServerCertificateValidationCallback?.Invoke(hostname, root, chain, SslPolicyErrors.None);

                if (result == null || result == true)
                {
                    //completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                    ///* Normally, the ServerCertificateValidationCallback can override the actual validation of the certificate. However, for some dumb reason,
                    // * the validation doesn't happen correctly. Thus either always rejecting trusted CAs, or always trusting untrusted CAs. The best way to fix this is if the callback
                    // * returns true, do the default validation. This will prevent the callback from ever trusting and untrusted certificate. But we'll never need to do that.
                    // except for now we need to do that.
                    completionHandler(
                        NSUrlSessionAuthChallengeDisposition.UseCredential,
                        NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                    return;
                }

                completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
            }
Exemple #13
0
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM)
                {
                    NetworkCredential credentialsToUse;

                    if (This.Credentials != null)
                    {
                        if (This.Credentials is NetworkCredential)
                        {
                            credentialsToUse = (NetworkCredential)This.Credentials;
                        }
                        else
                        {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = This.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    return;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodClientCertificate)
                {
                    Console.WriteLine("Client Cert!");

                    var password = "******";
                    var options  = NSDictionary.FromObjectAndKey(NSObject.FromObject(password), SecImportExport.Passphrase);

                    var path     = Path.Combine(NSBundle.MainBundle.BundlePath, "Content", "client.p12");
                    var certData = File.ReadAllBytes(path);

                    NSDictionary[] importResult;

                    X509Certificate cert = new X509Certificate(certData, password);

                    SecStatusCode statusCode     = SecImportExport.ImportPkcs12(certData, options, out importResult);
                    var           identityHandle = importResult[0][SecImportExport.Identity];
                    var           identity       = new SecIdentity(identityHandle.Handle);
                    var           certificate    = new SecCertificate(cert.GetRawCertData());

                    SecCertificate[] certificates = { certificate };
                    NSUrlCredential  credential   = NSUrlCredential.FromIdentityCertificatesPersistance(identity, certificates, NSUrlCredentialPersistence.ForSession);
                    completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);

                    return;
                }

                if (!This.customSSLVerification)
                {
                    goto doDefault;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust")
                {
                    goto doDefault;
                }

                if (ServicePointManager.ServerCertificateValidationCallback == null)
                {
                    goto doDefault;
                }

                // Convert Mono Certificates to .NET certificates and build cert
                // chain from root certificate
                var serverCertChain   = challenge.ProtectionSpace.ServerSecTrust;
                var chain             = new X509Chain();
                X509Certificate2 root = null;
                var errors            = SslPolicyErrors.None;

                if (serverCertChain == null || serverCertChain.Count == 0)
                {
                    errors = SslPolicyErrors.RemoteCertificateNotAvailable;
                    goto sslErrorVerify;
                }

                if (serverCertChain.Count == 1)
                {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var netCerts = Enumerable.Range(0, serverCertChain.Count)
                               .Select(x => serverCertChain[x].ToX509Certificate2())
                               .ToArray();

                for (int i = 1; i < netCerts.Length; i++)
                {
                    chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
                }

                root = netCerts[0];

                chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode      = X509RevocationMode.NoCheck;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllowUnknownCertificateAuthority;

                if (!chain.Build(root))
                {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var subject   = root.Subject;
                var subjectCn = cnRegex.Match(subject).Groups[1].Value;

                if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn))
                {
                    errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                    goto sslErrorVerify;
                }

sslErrorVerify:
                var hostname = task.CurrentRequest.Url.Host;
                bool result = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors);

                if (result)
                {
                    completionHandler(
                        NSUrlSessionAuthChallengeDisposition.UseCredential,
                        NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                }
                else
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                }
                return;

doDefault:
                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                return;
            }
Exemple #14
0
 public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 {
     // 信任所有服务器证书,支持自签名证书
     if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust)
     {
         completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
     }
     else
     {
         completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
     }
 }
Exemple #15
0
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                // 信任所有服务器证书,支持自签名证书
                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust)
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                    return;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM)
                {
                    NetworkCredential credentialsToUse;

                    if (nativeHandler.Credentials != null)
                    {
                        if (nativeHandler.Credentials is NetworkCredential)
                        {
                            credentialsToUse = (NetworkCredential)nativeHandler.Credentials;
                        }
                        else
                        {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = nativeHandler.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    return;
                }

                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
            }
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM)
                {
                    NetworkCredential credentialsToUse;

                    if (This.Credentials != null)
                    {
                        if (This.Credentials is NetworkCredential)
                        {
                            credentialsToUse = (NetworkCredential)This.Credentials;
                        }
                        else
                        {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = This.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    return;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust)
                {
                    var serverCertChain   = challenge.ProtectionSpace.ServerSecTrust;
                    X509Certificate2 root = null;
                    var errors            = SslPolicyErrors.None;

                    var netCerts = Enumerable.Range(0, serverCertChain.Count)
                                   .Select(x => serverCertChain[x].ToX509Certificate2())
                                   .ToArray();

                    root = netCerts[0];

                    // Convert java certificates to .NET certificates and build cert chain from root certificate

                    /*var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;
                     * var chain = new X509Chain();
                     * X509Certificate2 root = null;
                     * var errors = SslPolicyErrors.None;
                     *
                     * // Build certificate chain and check for errors
                     * if (serverCertChain == null || serverCertChain.Count == 0)
                     * {//no cert at all
                     *  errors = SslPolicyErrors.RemoteCertificateNotAvailable;
                     *  PinningFailureMessage = FailureMessages.NoCertAtAll;
                     *  goto sslErrorVerify;
                     * }
                     *
                     * if (serverCertChain.Count == 1)
                     * {//no root?
                     *  errors = SslPolicyErrors.RemoteCertificateChainErrors;
                     *  PinningFailureMessage = FailureMessages.NoRoot;
                     *  goto sslErrorVerify;
                     * }
                     *
                     * var netCerts = Enumerable.Range(0, serverCertChain.Count)
                     *  .Select(x => serverCertChain[x].ToX509Certificate2())
                     *  .ToArray();
                     *
                     * for (int i = 1; i < netCerts.Length; i++)
                     * {
                     *  chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
                     * }
                     *
                     * root = netCerts[0];
                     *
                     * chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                     * chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                     * chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                     * chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
                     *
                     * if (!chain.Build(root))
                     * {
                     *  errors = SslPolicyErrors.RemoteCertificateChainErrors;
                     *  PinningFailureMessage = FailureMessages.ChainError;
                     *  goto sslErrorVerify;
                     * }
                     *
                     * var subject = root.Subject;
                     * var subjectCn = cnRegex.Match(subject).Groups[1].Value;
                     *
                     * if (string.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn))
                     * {
                     *  errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                     *  PinningFailureMessage = FailureMessages.SubjectNameMismatch;
                     *  goto sslErrorVerify;
                     * }*/

                    var hostname = task.CurrentRequest.Url.Host;

                    if (!This.CertificatePinner.HasPins(hostname))
                    {
                        errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                        PinningFailureMessage = FailureMessages.NoPinsProvided + " " + hostname;
                        goto sslErrorVerify;
                    }

                    var match = This.CertificatePinner.Check(hostname, root.RawData);
                    if (!match)
                    {
                        errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                        PinningFailureMessage = FailureMessages.PinMismatch;
                    }

sslErrorVerify:
                    if (errors == SslPolicyErrors.None)
                    {
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                    }
                    else
                    {
                        completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                    }
                    return;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodClientCertificate)
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, This.UrlCredential);

                    return;
                }

                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
            }