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); }
private void SetClientCertificate(ClientCertificate certificate) { if (certificate == null) { return; } byte[] bytes; try { bytes = Convert.FromBase64String(certificate.RawData); } catch (Exception ex) { throw new HttpRequestException(FailureMessages.InvalidRawData, ex); } var options = NSDictionary.FromObjectsAndKeys(new object[] { certificate.Passphrase }, new object[] { "passphrase" }); var status = SecImportExport.ImportPkcs12(bytes, options, out NSDictionary[] items); var identityRef = items[0]["identity"]; var identity = new SecIdentity(identityRef.Handle); SecCertificate[] certs = { identity.Certificate }; this.UrlCredential = new NSUrlCredential(identity, certs, NSUrlCredentialPersistence.ForSession); }
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); } }
void AddHeaders(HttpRequestMessage request) { ProxyInfo proxy = GetProxy(request.RequestUri); if (proxy == null || proxy.ProxyType != CFProxyType.HTTPS) { return; } NSUrlCredential credential = GetProxyCredential(proxy); if (credential == null) { return; } string auth = GetBasicAuthHeaderValue(credential); if (string.IsNullOrEmpty(auth)) { return; } request.Headers.ProxyAuthorization = new AuthenticationHeaderValue("Basic", auth); }
public virtual void WillSendRequestForAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge) { if (challenge.PreviousFailureCount == 2) { //TODO: update cred } else if (challenge.PreviousFailureCount > 2) { //display alert XamarinAlertController.showAlertViewForController(this, SDKErrorLoginFailedTitle, SDKErrorLoginFailedMessage); } else { //handle challenges if (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodServerTrust") { var cred = new NSUrlCredential(challenge.ProtectionSpace.ServerSecTrust); challenge.Sender.UseCredential(cred, challenge); } else if ((challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodHTTPBasic") || (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodNTLM") || (challenge.ProtectionSpace.AuthenticationMethod == "NSURLAuthenticationMethodClientCertificate")) { handleChallengeForConnection(challenge); } else { Console.WriteLine("AWXamarin Authentication challenge is not supported by the SDK"); XamarinAlertController.showAlertViewForController(this, SDKErrorAuthNotSupportedTitle, SDKErrorAuthNotSupportedMessage); } } }
/// <summary> /// Import the specified certificate and its associated private key. /// </summary> /// <param name="certificate">The certificate and key, in PKCS12 format.</param> /// <param name="passphrase">The passphrase that protects the private key.</param> public void Import(byte[] certificate, string passphrase) { NSDictionary opt; if (string.IsNullOrEmpty(passphrase)) { opt = new NSDictionary(); } else { opt = NSDictionary.FromObjectAndKey(new NSString(passphrase), SecImportExport.Passphrase); } var status = SecImportExport.ImportPkcs12(certificate, opt, out NSDictionary[] array); if (status == SecStatusCode.Success) { var identity = new SecIdentity(array[0]["identity"].Handle); NSArray chain = array[0]["chain"] as NSArray; SecCertificate[] certs = new SecCertificate[chain.Count]; for (System.nuint i = 0; i < chain.Count; i++) { certs[i] = chain.GetItem <SecCertificate>(i); } Credential = new NSUrlCredential(identity, certs, NSUrlCredentialPersistence.ForSession); } }
public UrlDelegate(string name, Action <UIImage> success, Action <NSError> failure, NSUrlCredential credential) { _name = name; imgCallback = success; _credential = credential; _failure = failure; data = new NSMutableData(); }
public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler) { //base.DidReceiveChallenge(session, task, challenge, completionHandler); NSUrlCredential userCredential = NSUrlCredential.FromUserPasswordPersistance(UserName, Password, NSUrlCredentialPersistence.None); //challenge.Sender.UseCredential(userCredential, challenge); completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, userCredential); }
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 (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); } }
public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler) { // 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 = GetInflightData(task)?.Request?.Headers?.Authorization; if (!(string.IsNullOrEmpty(authHeader?.Scheme) && string.IsNullOrEmpty(authHeader?.Parameter))) { completionHandler(NSUrlSessionAuthChallengeDisposition.RejectProtectionSpace, null); return; } } if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM) { if (sessionHandler.Credentials != null) { var credentialsToUse = sessionHandler.Credentials as NetworkCredential; if (credentialsToUse == null) { var uri = GetInflightData(task).Request.RequestUri; credentialsToUse = sessionHandler.Credentials.GetCredential(uri, "NTLM"); } var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession); completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential); } return; } //NOTE: SSL Pinning here var serverCertChain = challenge.ProtectionSpace.ServerSecTrust; var first = serverCertChain[0].DerData; var cert = NSData.FromFile("httpbin.cer"); if (first.IsEqual(cert)) { completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential); } else { completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null); } }
public override void WillSendRequestForAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge) { var identity = SecIdentity.Import(Certificate); var certificate = new SecCertificate(Certificate); SecCertificate[] certificates = { certificate }; var credential = NSUrlCredential.FromIdentityCertificatesPersistance(identity, certificates, NSUrlCredentialPersistence.ForSession); challenge.Sender.UseCredential(credential, challenge); }
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"); } }
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"); } }
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) { 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; } } } completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential); }
string GetBasicAuthHeaderValue(NSUrlCredential credential) { if (string.IsNullOrEmpty(credential.User)) { return(null); } string password = credential.Password ?? string.Empty; byte[] bytes = GetBytes(credential.User + ":" + password); return(Convert.ToBase64String(bytes)); }
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); } }
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"); } }
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); } }
/// <summary> /// Import the specified certificate and its associated private key. /// </summary> /// <param name="certificate">The certificate and key, in PKCS12 format.</param> /// <param name="passphrase">The passphrase that protects the private key.</param> public void Import(byte[] certificate, string passphrase) { NSDictionary opt; if (string.IsNullOrEmpty(passphrase)) { opt = new NSDictionary(); } else { opt = NSDictionary.FromObjectAndKey(new NSString(passphrase), SecImportExport.Passphrase); } var status = SecImportExport.ImportPkcs12(certificate, opt, out NSDictionary[] array); if (status == SecStatusCode.Success) { var identity = new SecIdentity(array[0]["identity"].Handle); SecCertificate[] certs = { identity.Certificate }; Credential = new NSUrlCredential(identity, certs, NSUrlCredentialPersistence.ForSession); } }
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); } } }
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 (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 (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; }
public void useCredentialsForLogin(string username, string password) { var cred = new NSUrlCredential(username, password, NSUrlCredentialPersistence.None); completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, cred); }
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) { // 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 DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler) { var crendential = new NSUrlCredential(_webclient.Username, _webclient.Password, NSUrlCredentialPersistence.ForSession); completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, crendential); }
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); }
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 UrlDelegate(string name, Action<UIImage> success, Action<NSError> failure, NSUrlCredential credential) { _name = name; imgCallback = success; _credential = credential; _failure = failure; data = new NSMutableData(); }
public void DidReceiveAuthenticationChallenge(WKWebView webView, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler) { NSUrlCredential userCredential = NSUrlCredential.FromUserPasswordPersistance(UserName, Password, NSUrlCredentialPersistence.None); completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, userCredential); }
/// <summary> /// Set the client certificate provider (iOS implementation) /// </summary> /// <param name="provider">The provider for client certificates on this platform</param> public virtual void SetClientCertificates(Abstractions.IClientCertificateProvider provider) { ClientCertificate = (provider as IClientCertificateProvider)?.Credential; }
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; }
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; }