Created
March 3, 2016 18:47
-
-
Save lifeisfoo/63478c8520d9c0f74477 to your computer and use it in GitHub Desktop.
Swift version of OWASP's didReceiveAuthenticationChallenge method (for ios SSL PINNING) (complete method http://stackoverflow.com/a/34223292/3340702)
This file contains 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
import Foundation | |
import Security | |
class NSURLSessionPinningDelegate: NSObject, NSURLSessionDelegate { | |
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { | |
// Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS | |
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { | |
if let serverTrust = challenge.protectionSpace.serverTrust { | |
var secresult = SecTrustResultType(kSecTrustResultInvalid) | |
let status = SecTrustEvaluate(serverTrust, &secresult) | |
if(errSecSuccess == status) { | |
if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) { | |
if let serverCertificateData = SecCertificateCopyData(serverCertificate) as? CFDataRef { | |
let data = CFDataGetBytePtr(serverCertificateData); | |
let size = CFDataGetLength(serverCertificateData); | |
let cert1 = NSData(bytes: data, length: size) | |
let file_der = NSBundle.mainBundle().pathForResource("my-https-website", ofType: "der") | |
if let file = file_der { | |
if let cert2 = NSData(contentsOfFile: file) { | |
if cert1.isEqualToData(cert2) { | |
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust:serverTrust)) | |
return | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
// Pinning failed | |
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Want to add multiple Certificates how can I do it