Skip to content

Instantly share code, notes, and snippets.

@litoarias
Last active June 20, 2024 20:19
Show Gist options
  • Save litoarias/cd1057729ad159e60ba50df4e96a98c5 to your computer and use it in GitHub Desktop.
Save litoarias/cd1057729ad159e60ba50df4e96a98c5 to your computer and use it in GitHub Desktop.
Custom class of WKWebView implementing SSL Pinning
import WebKit
public class CustomWebView: WKWebView {
// var javascript: Javascript!
public override init(frame: CGRect, configuration: WKWebViewConfiguration = WKWebViewConfiguration()) {
super.init(frame: frame, configuration: configuration)
doInit()
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func doInit() {
//clearCache()
//self.javascript = Javascript(webView: self)
self.allowsBackForwardNavigationGestures = true
self.navigationDelegate = self
self.uiDelegate = self
self.scrollView.delegate = self
}
}
extension CustomWebView : WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate {
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation){
print("didStartProvisionalNavigation")
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("didFinish")
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
/// Handle SSL connections by default. We aren't doing SSL pinning or custom certificate handling.
public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("didReceive challenge")
let whiteStaticList = ["www.google.nl", "www.yahoo.com"]
let whiteList = whiteStaticList.filter { challenge.protectionSpace.host.hasPrefix($0) }
if whiteList.count > 0 {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!))
return
}
/**
* We started listening to this delegate method to avoid of `SSL Pinning`
* and `man-in-the-middle` attacks. Is required have certificate in
* local project e.g. `example.com.der`
*/
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if let serverTrust = challenge.protectionSpace.serverTrust {
var secresult = SecTrustResultType.invalid
let status = SecTrustEvaluate(serverTrust, &secresult)
if(errSecSuccess == status) {
if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
let serverCertificateData = SecCertificateCopyData(serverCertificate)
let data = CFDataGetBytePtr(serverCertificateData);
let size = CFDataGetLength(serverCertificateData);
let cert1 = NSData(bytes: data, length: size)
let file_der = Bundle.main.path(forResource: "example.com", ofType: "der")
if let file = file_der {
if let cert2 = NSData(contentsOfFile: file) {
if cert1.isEqual(to: cert2 as Data) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust))
return
}
}
}
}
}
}
}
//Pinning failed
completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
print("Error 'didFail': \(error.localizedDescription)\nSchema: \(String(describing: webView.url?.absoluteString))")
}
public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
print("Error 'didFailProvisionalNavigation': \(error.localizedDescription)\nSchema: \(String(describing: webView.url?.absoluteString))")
}
// Called when js need open _blank link
public func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame == nil {
let url = navigationAction.request.url
if url?.description.lowercased().hasPrefix("http://") != nil ||
url?.description.lowercased().hasPrefix("https://") != nil ||
url?.description.lowercased().hasPrefix("mailto:") != nil {
UIApplication.shared.openURL(url!)
}
}
return nil
}
// MARK: - Scrollview Delegate
// keeps the page from scrolling horizontally
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.x != 0 {
var offset = scrollView.contentOffset
offset.x = 0
scrollView.contentOffset = offset
}
}
// Disables zooming
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return nil
}
}
extension WKWebView {
public func constraint(toView contentView: UIView) {
self.translatesAutoresizingMaskIntoConstraints = false
self.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
self.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
self.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
self.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
}
@litoarias
Copy link
Author

litoarias commented Jan 22, 2020

Hi @Kizer1978, this class is an extension of WKWebView and avoids possible SSL pinning attacks automatically. You just need to get your web certificate and drag and drop it into your root project and then replace "example.com" with your certificate file name. To verify it, you can put break points to check it. This class is 2 years old and I'm not sure if it works correctly yet. You can send feedback when you can ckeck the class. Thanks a lot

@pbartolome
Copy link

As the server trust challenge.protectionSpace.serverTrust! is being force unwrapped, the client will crash if the challenge is not a "Server Trust", like for example "AuthBasic", or a "ClientCertificate".

An option could be to guard against the authentication method to only perform the check if the method is NSURLAuthenticationMethodServerTrust and unwrap properly the serverTrust. If another type of challenge is received it will just be cancelled (for example, visiting a website that requires basic authentication)

		guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
			let serverTrust = challenge.protectionSpace.serverTrust else {
			completionHandler(.cancelAuthenticationChallenge, nil)
			return
		}

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