Skip to content

Instantly share code, notes, and snippets.

@wcoder
Last active December 12, 2019 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wcoder/50ab3b18fea4f3f76553fa47fdb6469c to your computer and use it in GitHub Desktop.
Save wcoder/50ab3b18fea4f3f76553fa47fdb6469c to your computer and use it in GitHub Desktop.
Sample of SSL-pinning via NSUrlSession for Xamarin.iOS.
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);
}
}
}
}
@wcoder
Copy link
Author

wcoder commented Dec 12, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment