Last active
December 12, 2019 12:47
-
-
Save wcoder/50ab3b18fea4f3f76553fa47fdb6469c to your computer and use it in GitHub Desktop.
Sample of SSL-pinning via NSUrlSession for Xamarin.iOS.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal static class Samples | |
{ | |
public static void MakeRequest() | |
{ | |
var s = "https://secure-domain.org"; | |
var request = new NSMutableUrlRequest(new NSUrl(s)) | |
{ | |
HttpMethod = "GET" | |
}; | |
var session = NSUrlSession.FromConfiguration(NSUrlSessionConfiguration.DefaultSessionConfiguration, | |
(INSUrlSessionDelegate)new MySessionDelegate(), | |
new NSOperationQueue()); | |
NSUrlSessionTask task = session.CreateDataTask(request, (data, response, error) => | |
{ | |
Debug.WriteLine("data is " + data + " response is " + response + " error is " + error); | |
}); | |
task.Resume(); | |
} | |
public class MySessionDelegate : NSUrlSessionDelegate | |
{ | |
public override void DidReceiveChallenge(NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler) | |
{ | |
Debug.WriteLine("challenge is " + challenge.ProtectionSpace.AuthenticationMethod); | |
if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust.ToString()) | |
{ | |
var c = NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust); | |
challenge.Sender.UseCredential(c, challenge); | |
challenge.Sender.ContinueWithoutCredential(challenge); | |
completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, c); | |
} | |
else | |
{ | |
var password = "cert-pass"; | |
var path = Path.Combine(NSBundle.MainBundle.BundlePath, "bundle/path/to/sert.p12"); | |
var options = NSDictionary.FromObjectAndKey(NSObject.FromObject(password), SecImportExport.Passphrase); | |
var certData = File.ReadAllBytes(path); | |
SecImportExport.ImportPkcs12(certData, options, out NSDictionary[] importResult); | |
var identityHandle = importResult[0][SecImportExport.Identity]; | |
var identity = new SecIdentity(identityHandle.Handle); | |
var cert = new X509Certificate(certData, password); | |
var certificate = new SecCertificate(cert.GetRawCertData()); | |
var cred = NSUrlCredential.FromIdentityCertificatesPersistance(identity, new[] { certificate }, NSUrlCredentialPersistence.ForSession); | |
completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, cred); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More details: