Пример #1
0
 public virtual void DidReceiveChallenge(NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 {
     if (challenge.PreviousFailureCount == 2)
     {
         //TODO: update UserCreds
     }
     else if (challenge.PreviousFailureCount > 2)
     {
         XamarinAlertController.showAlertViewForController(this, SDKErrorLoginFailedTitle, SDKErrorLoginFailedMessage);
         completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
     }
     else
     {
         if (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodServerTrust")
         {
             completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
         }
         else if ((challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodHTTPBasic") || (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodNTLM") || (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodClientCertificate"))
         {
             handleChallangeforSession(challenge, completionHandler);
         }
         else
         {
             completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
             XamarinAlertController.showAlertViewForController(this, SDKErrorAuthNotSupportedTitle, SDKErrorAuthNotSupportedMessage);
         }
     }
 }
        public override void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            if (Reference == null || !Reference.TryGetTarget(out FormsWebViewRenderer renderer))
            {
                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
                return;
            }
            if (renderer?.Element == null)
            {
                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
                return;
            }

            if ((!string.IsNullOrWhiteSpace(renderer.Element.Username)) &&
                (!string.IsNullOrWhiteSpace(renderer.Element.Password)))
            {
                if (challenge.PreviousFailureCount > 5) //cancel autorization in case of 5 failing requests
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                    return;
                }
                completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, new NSUrlCredential(renderer.Element.Username, renderer.Element.Password, NSUrlCredentialPersistence.ForSession));
            }
            else
            {
                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
            }
        }
Пример #3
0
        void showAuthenticationViewForChallenge(NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> handler)
        {
            AuthenticationChallengeController challengeController = new AuthenticationChallengeController();

            challengeController.completionHandler = handler;
            challengeController.createCredAlertForChallenge(challenge);
        }
Пример #4
0
        private static bool ValidateLeafCert(NSUrlAuthenticationChallenge challenge)
        {
            var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;

            var first = serverCertChain[0].DerData;
            var cert  = NSData.FromFile("xamarin.cer");

            return(first.IsEqual(cert));
        }
Пример #5
0
        private static bool IsValid(NSUrlAuthenticationChallenge challenge)
        {
            var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;

            var first       = serverCertChain[0].DerData;
            var firstString = first.GetBase64EncodedString(NSDataBase64EncodingOptions.None);

            var cert       = NSData.FromFile("xamarin.cer");
            var certString = cert.GetBase64EncodedString(NSDataBase64EncodingOptions.None);

            return(firstString == certString);
        }
Пример #6
0
 public void ReceivedAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
 {
     if (challenge.PreviousFailureCount == 0)
     {
         var credential = new NSUrlCredential("USER", "PASSWORD", NSUrlCredentialPersistence.ForSession);
         challenge.Sender.UseCredential(credential, challenge);
     }
     else
     {
         Console.WriteLine("previous authentication failure");
     }
 }
Пример #7
0
        //user method
        void handleChallengeforSession(NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            NSError outError;

            if (AWController.ClientInstance().CanHandleProtectionSpace(challenge.ProtectionSpace, out outError))
            {
                bool success = AWController.ClientInstance().HandleChallengeForURLSessionChallenge(challenge, completionHandler);
                if (success)
                {
                    Console.WriteLine("AWXamarin Client Challenge successful using Session");
                }
            }
        }
Пример #8
0
        void handleChallengeForConnection(NSUrlAuthenticationChallenge challenge)
        {
            NSError outError;

            if (AWController.ClientInstance().CanHandleProtectionSpace(challenge.ProtectionSpace, out outError))
            {
                bool success = AWController.ClientInstance().HandleChallenge(challenge);
                if (success)
                {
                    Console.WriteLine("AWXamarin Client Challenge successful using connection");
                }
            }
        }
        public void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            SecTrustResult result = challenge.ProtectionSpace.ServerSecTrust.Evaluate();

            if (result == SecTrustResult.Unspecified || result == SecTrustResult.Proceed)
            {
                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
            }
            else
            {
                completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
            }
        }
Пример #10
0
        public void createCredAlertForChallenge(NSUrlAuthenticationChallenge challenge)
        {
            InvokeOnMainThread(() =>
            {
                var alertController       = UIAlertController.Create("Login", challenge.ProtectionSpace.Realm, UIAlertControllerStyle.Alert);
                UIAlertAction loginAction = UIAlertAction.Create("Submit", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                {
                    string username = alertController.TextFields[0].Text;
                    string password = alertController.TextFields[1].Text;
                    if (username != null && password != null)
                    {
                        useCredentialsForLogin(username, password);
                    }
                    else
                    {
                        Console.WriteLine("Cant create creds");
                    }
                });
                alertController.AddAction(loginAction);
                alertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (UIAlertAction obj) =>
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                }));

                alertController.AddTextField(textField =>
                {
                    textField.Placeholder     = "Username";
                    textField.ClearButtonMode = UITextFieldViewMode.WhileEditing;
                });

                alertController.AddTextField(textField =>
                {
                    textField.Placeholder     = "Password";
                    textField.ClearButtonMode = UITextFieldViewMode.WhileEditing;
                    textField.SecureTextEntry = true;
                });
                XamarinAlertController.showAlertOnTopViewController(alertController);
            });
        }
        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);
                }
            }
        }
Пример #12
0
 public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 => completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
		public void CancelledAuthenticationChallenge (NSUrlProtocol protocol, NSUrlAuthenticationChallenge challenge)
		{
			Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, Selector.GetHandle (selUrlProtocolDidCancelAuthenticationChallenge_), protocol.Handle, challenge.Handle);
		}
Пример #14
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);
        }
Пример #15
0
 public void ReceivedAuthenticationChallenge(NSUrlProtocol protocol, NSUrlAuthenticationChallenge challenge)
 {
     Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, selUrlProtocolDidReceiveAuthenticationChallenge_, protocol.Handle, challenge.Handle);
 }
Пример #16
0
            private void WillSendRequestForAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
            {
                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust)
                {
                    var  trust              = challenge.ProtectionSpace.ServerSecTrust;
                    var  result             = trust.Evaluate();
                    bool trustedCertificate = result == SecTrustResult.Proceed || result == SecTrustResult.Unspecified;

                    if (!trustedCertificate && trust.Count != 0)
                    {
                        var originalCertificate = trust[0].ToX509Certificate2();
                        var x509Certificate     = new Certificate(challenge.ProtectionSpace.Host, originalCertificate);
                        trustedCertificate = _renderer.Element.ShouldTrustUnknownCertificate(x509Certificate);
                    }

                    if (trustedCertificate)
                    {
                        challenge.Sender.UseCredential(new NSUrlCredential(trust), challenge);
                    }
                    else
                    {
                        Console.WriteLine("Rejecting request");
                        challenge.Sender.CancelAuthenticationChallenge(challenge);

                        SendFailedNavigation();

                        return;
                    }
                }
                challenge.Sender.PerformDefaultHandling(challenge);
            }
            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);
                }

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

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

                // 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(hostname, root, chain, SslPolicyErrors.None);
                if (result) {
                    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. 
                     * completionHandler(
                        NSUrlSessionAuthChallengeDisposition.UseCredential,
                        NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                    */

                } else {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                }
                return;
            }
Пример #18
0
        public void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            NSUrlCredential userCredential = NSUrlCredential.FromUserPasswordPersistance(UserName, Password, NSUrlCredentialPersistence.None);

            completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, userCredential);
        }
		public override void CanceledAuthenticationChallenge (NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
		{
			//Console.WriteLine("canceled");
		}
Пример #20
0
        // this is tough to implement due to NSInputStream & CFStream delegates
        // reauthorize?
        //public override void NeedNewBodyStream(NSUrlSession session, NSUrlSessionTask task, Action<NSInputStream> completionHandler)
        //{
        //    var transfer = task.FromNative();
        //    var file = new FileInfo(transfer.LocalFilePath);
        //    //var stream = new BodyStream(file);
        //    //completionHandler(stream);
        //}


        public override void DidReceiveChallenge(NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            this.logger.LogDebug($"DidReceiveChallenge");
            completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
        }
Пример #21
0
//		public override void DidReceiveChallenge (NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
//		{
//			Console.WriteLine("[NSUrlSessionManager] DidReceiveChallenge");
//			Console.WriteLine ("[NSUrlSessionManager] DidReceiveChallenge");
//			Console.WriteLine("[NSUrlSessionManager] DidReceiveChallenge");
//
//			completionHandler (challenge, NSUrlCredential.);
//		}

        public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
        {
            Console.WriteLine("[NSUrlSessionManager] DidReceiveChallenge2");
        }
Пример #22
0
 public override void CanceledAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
 {
     //Console.WriteLine("canceled");
 }
Пример #23
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 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 (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;
            }
 public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 {
     // No handle?
 }
Пример #27
0
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                var inflight = GetInflightData(task);

                if (inflight == null)
                {
                    return;
                }

                // ToCToU for the callback
                var trustCallback = sessionHandler.TrustOverride;

                if (trustCallback != null && challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust)
                {
                    if (trustCallback(sessionHandler, challenge.ProtectionSpace.ServerSecTrust))
                    {
                        var credential = new NSUrlCredential(challenge.ProtectionSpace.ServerSecTrust);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    else
                    {
                        // user callback rejected the certificate, we want to set the exception, else the user will
                        // see as if the request was cancelled.
                        lock (inflight.Lock) {
                            inflight.Exception = new HttpRequestException("An error occurred while sending the request.", new WebException("Error: TrustFailure"));
                        }
                        completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                    }
                    return;
                }
                // case for the basic auth failing up front. As per apple documentation:
                // The URL Loading System is designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers using
                // the addValue(_:forHTTPHeaderField:) or setValue(_:forHTTPHeaderField:) methods:
                //  Authorization
                //  Connection
                //  Host
                //  Proxy-Authenticate
                //  Proxy-Authorization
                //  WWW-Authenticate
                // but we are hiding such a situation from our users, we can nevertheless know if the header was added and deal with it. The idea is as follows,
                // check if we are in the first attempt, if we are (PreviousFailureCount == 0), we check the headers of the request and if we do have the Auth
                // header, it means that we do not have the correct credentials, in any other case just do what it is expected.

                if (challenge.PreviousFailureCount == 0)
                {
                    var authHeader = inflight.Request?.Headers?.Authorization;
                    if (!(string.IsNullOrEmpty(authHeader?.Scheme) && string.IsNullOrEmpty(authHeader?.Parameter)))
                    {
                        completionHandler(NSUrlSessionAuthChallengeDisposition.RejectProtectionSpace, null);
                        return;
                    }
                }

                if (sessionHandler.Credentials != null && TryGetAuthenticationType(challenge.ProtectionSpace, out string authType))
                {
                    NetworkCredential credentialsToUse = null;
                    if (authType != RejectProtectionSpaceAuthType)
                    {
                        var uri = inflight.Request.RequestUri;
                        credentialsToUse = sessionHandler.Credentials.GetCredential(uri, authType);
                    }

                    if (credentialsToUse != null)
                    {
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    else
                    {
                        // Rejecting the challenge allows the next authentication method in the request to be delivered to
                        // the DidReceiveChallenge method. Another authentication method may have credentials available.
                        completionHandler(NSUrlSessionAuthChallengeDisposition.RejectProtectionSpace, null);
                    }
                }
                else
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                }
            }
Пример #28
0
 public override void OnCancelledAuthenticationChallenge(WebView sender, NSObject identifier, NSUrlAuthenticationChallenge challenge, WebDataSource dataSource);
Пример #29
0
        public override void ReceivedAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
        {
            //			if (challenge.PreviousFailureCount > 0) {
            //				showError = false;
            //				challenge.Sender.CancelAuthenticationChallenge (challenge);
            //				Application.AuthenticationFailure ();
            //				return;
            //			}
            //
            //			if (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodServerTrust")
            //				challenge.Sender.UseCredentials (NSUrlCredential.FromTrust (challenge.ProtectionSpace.ServerTrust), 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 (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;
            }
            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 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 DidReceiveChallenge(NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 {
     Console.WriteLine ("DidReceiveChallenge");
     // No Handle
 }
Пример #34
0
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                var inflight = GetInflightData(task);

                if (inflight == null)
                {
                    return;
                }

                // case for the basic auth failing up front. As per apple documentation:
                // The URL Loading System is designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers using
                // the addValue(_:forHTTPHeaderField:) or setValue(_:forHTTPHeaderField:) methods:
                //  Authorization
                //  Connection
                //  Host
                //  Proxy-Authenticate
                //  Proxy-Authorization
                //  WWW-Authenticate
                // but we are hiding such a situation from our users, we can nevertheless know if the header was added and deal with it. The idea is as follows,
                // check if we are in the first attempt, if we are (PreviousFailureCount == 0), we check the headers of the request and if we do have the Auth
                // header, it means that we do not have the correct credentials, in any other case just do what it is expected.

                if (challenge.PreviousFailureCount == 0)
                {
                    var authHeader = inflight.Request?.Headers?.Authorization;
                    if (!(string.IsNullOrEmpty(authHeader?.Scheme) && string.IsNullOrEmpty(authHeader?.Parameter)))
                    {
                        completionHandler(NSUrlSessionAuthChallengeDisposition.RejectProtectionSpace, null);
                        return;
                    }
                }

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM && sessionHandler.Credentials != null)
                {
                    var credentialsToUse = sessionHandler.Credentials as NetworkCredential;
                    if (credentialsToUse == null)
                    {
                        var uri = inflight.Request.RequestUri;
                        credentialsToUse = sessionHandler.Credentials.GetCredential(uri, "NTLM");
                    }
                    NSUrlCredential credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                    completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                }
                else
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                }
            }
//		public override void DidReceiveChallenge (NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
//		{
//			Console.WriteLine("[NSUrlSessionManager] DidReceiveChallenge");
//			Console.WriteLine ("[NSUrlSessionManager] DidReceiveChallenge");
//			Console.WriteLine("[NSUrlSessionManager] DidReceiveChallenge");
//
//			completionHandler (challenge, NSUrlCredential.);
//		}

		public override void DidReceiveChallenge (NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
		{
			Console.WriteLine("[NSUrlSessionManager] DidReceiveChallenge2");
		}
Пример #36
0
 public void CancelledAuthenticationChallenge(NSUrlProtocol protocol, NSUrlAuthenticationChallenge challenge)
 {
     Messaging.void_objc_msgSend_IntPtr_IntPtr(this.Handle, Selector.GetHandle(selUrlProtocolDidCancelAuthenticationChallenge_), protocol.Handle, challenge.Handle);
 }
 public override void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 {
     //base.DidReceiveAuthenticationChallenge(webView, challenge, completionHandler);
     completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, new NSUrlCredential(Username, Password, NSUrlCredentialPersistence.ForSession));
     return;
 }
Пример #38
0
 public virtual void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, [BlockProxy(typeof(Trampolines.NIDActionArity2V0))] Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 {
     throw new NotImplementedException();
 }
Пример #39
0
 public virtual void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 {
     State = -2;
     completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
 }
Пример #40
0
 public override void ReceivedAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
 {
     throw new System.NotImplementedException ();
 }
Пример #41
0
 public override bool ShouldWaitForResponseToAuthenticationChallenge(AVAssetResourceLoader resourceLoader,
                                                                     NSUrlAuthenticationChallenge authenticationChallenge)
 {
     return(base.ShouldWaitForResponseToAuthenticationChallenge(resourceLoader, authenticationChallenge));
 }
            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) {
                    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;
            }
Пример #43
0
 /// <summary>
 /// Handle the auth challenge on the connection
 /// </summary>
 public override void ReceivedAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge)
 {
     if(challenge.PreviousFailureCount == 0)
     {
         var cred = NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerTrust);
         challenge.Sender.UseCredentials(cred, challenge);
     }
     else
     {
         challenge.Sender.CancelAuthenticationChallenge(challenge);
     }
 }