httpwwwbethedevcom
324329524619168
Loading...

SSL pinning using TrustKit with Alamofire in iOS - Swift


SSL pinning one of the popular ways to inspect HTTPS requests in iOS Apps is the Man-in-the-middle (MITM) attack. This involves having a trusted server’s keys add into your iOS app and some additional code to ensure that the app only communicates with servers using that particular certificate.

When SSL certificate pinning is active, the app will not allow any requests to be sent out to any untrusted server. Here I'm going to use TrustKit for SSL Key Pinning Handling. TrustKit Github

Let’s start to write Swift code to intercept SSL Pinning Alamofire Requests

TrustKit Configuration 

Deploying SSL pinning in the App requires initializing TrustKit with a pinning policy (domains, Subject Public Key Info hashes, and additional settings).

The policy can be configured within the App's Info.plist:


Alternatively, the pinning policy can be set programmatically: 
didFinishLaunchingWithOptions  in (AppDelegate)



After TrustKit has been initialized, a TSKPinningValidator instance can be retrieved from the TrustKit singleton and can be used to perform SSL pinning validation in the App's network delegates.


Setting network delegate in Alamofrie. 


When you are creating/requesting from makeRequestAlamofire will validate the Keys in Host side SSL pining and it will produce an error when key validation got failed.

If this code was helpful, I would love to hear from you or If you have any questions please post your comments below.
TrustKit 2825076269052070175

Post a Comment Default Comments Disqus Comments

  1. I followed your tutorial but the flow of code does not reach the session delegate in my case. I'm guessing that I have to let the session manager know that I am using a my own session delegate? I am stuck at this part.

    ReplyDelete
    Replies
    1. Did you manage to make it work? I am having the same issue

      Delete
  2. Hi Dholakia and Gallhager,

    Please check and confirm you have set "sessionManager = SessionManager.init(configuration: URLSessionConfiguration.ephemeral, delegate: self)"

    if yes, Check your calling domain contains "https://" and is that same URL you have configured on trustKitConfig. :smile:

    if you are still facing issue don't hesitate to contact me. Cheers.

    ReplyDelete
    Replies
    1. Hi!

      Thank you for your reply! I finally managed to get it working. But there is another problem which is not related to your code:

      It's not possible to know that the error actually is a certificate pinning failure. The message "Result Pinning validation failed for..." is shown regardless of type of error. When the pinning fails, the error is of type NSURLErrorCancelled and not NSURLErrorServerCertificateUntrusted as it should be.

      I would be very happy if someone has a good solution to this :)

      Delete

emo-but-icon

Home item

Follow by Email

Popular Posts

Random Posts