Prevent MITM Attack by SSL Pinning (URLSession)

13 / Sep / 2023 by vibhash.kumar 0 comments

What is an MITM Attack?

An MITM is a form of cyber attack where a malicious individual manipulates two users to access data that two parties are trying to deliver to each other. A malicious hacker, without being recognized hacks the intended data that are meant to be sent to a particular person. In certain aspects, like MITM, MitM, MiM, or MIM, MITM attacks can be referred to.

Simply put, an MITM attack occurs when an attacker puts himself between a client and a webpage.

How does MITM work?

Hackers use MITM attacks to access personal information or anything confidential by pretending known users or webpages. They basically spy on users’ private meetings or confidential data and extract useful information.

Real-life Instances of MITM Attack 

How can we prevent MITM attacks with SSL Pinning?

In iOS we retrieve data from the server to use in the application, and then we work with this functionality in the application. While fetching these data from the server Transport Layer Security protocol is used to provide secure communication between each other. Apps don’t know which certificates are to be trusted rather they use certificates that iOS contains 

Let’s start with installing the certificate:

Here we need to download the certificate from the server, For that, we need to follow these steps:

  1. First, you need to ask for the certificate from the Backend People which they are using at their end.
  2. If it is a Public API like an open URL: for example: click on this link. 
  3. You will find a lock icon on the left when the connection is established with the server.

On clicking on this icon, you will find a popup showing


On Clicking Show Certificate, you will see:


 Just drag and drop this certificate in your project bundle

  1. The certificate name will be like:, you can edit the certificate name.

Now we have completed all the preparations for the implementation of SSL pinning

Implementing SSL Pinning using URL Session:

Now let’s set our Network Manager by URLSession for calling APIs


We need to do two things: 

  1. We have a local certificate in our bundle.
  2. We will create a certificate from the host.
  3. Now, we will compare both certificates by converting them into Data, and if the data is synced from both certificates, then we will say that Certificate Pinning is successful; otherwise, it has failed.

Now for certificate pinning:

1. We have to create a Server Trust first. Now, what does the Server Trust mean? – Server Trust means that your computer / Mobile app is sending out packet addresses to other computers (like server) IP addresses, but it is not receiving any response packet from that server. 

2. Now check for the SSL policy for the domain.

3. Evaluate the certificate using the policy as well as Server Trust

4. Convert the Local and Remote certificates into data

5. Compare both the certificates:

//MARK: URLSessionDelegate


Now if we are fetching any details from the server, and any MITM attack occurs, it will cancel the authentication challenge and return nothing, which means Man in the Middle will not find any request from the network. Show an error something like this one:

Detection of Man-in-the-middle attack

It is very hard to identify an MITM attack, so we have to take appropriate measures to monitor and identify the attack before it’s too late. The main technique to identify a potential attack is to always search for adequate page authorization and introduce some kind of temporary authorization; however, these will need forensic investigation and will be a lengthy process.

So instead of identifying an attack, we should take precautionary measures to avoid it, and for this, one should always be mindful of his surfing habits and beforehand identify the possible hazardous environment.

Preventions of Man-in-the-middle Attack:

  1. Wireless access point (WAP) Encryption: Creating a strong protection feature on access points eliminates legitimate access just from being closer to accessing the system. A vulnerable protection system will enable an intruder to brute-force his way into the system and start attacking the MITM.
  1. Use a VPN
  • Use a Virtual Private Network (VPN): An encrypted VPN must be used to Stop a hacker from reading or modifying web traffic. Must use a cybersecurity incident response plan to prevent data loss.
  • Network Security: A secure network should be installed to check any unwanted intrusion, and network administrators must use good network hygiene to reduce MITM attacks and also traffic patterns to be analyzed to detect any unusual behavior.
  1. Public Key Pair Authentication: MITM normally includes something to catch your eye. Public key pair authentication uses RSA, which ensures that you communicate with the objects that you essentially want to communicate with.
  1. Strong Network User Credentials: It is extremely important to ensure that the email login is modified. Not only the login credentials for Wi-Fi but the password hashes for your router because when a hacker detects or gets access to wireless router login details, they can switch  fraudulent servers to DNS servers or, at worst, hack the modem with the harmful malware.
  1. Communication Security: This helps the users to protect themselves from unauthorized messages and provides secure data encryption. This two-factor authentication can be used by giving an extra layer of protection other than login credentials. One can use a text to your device from Gmail with login credentials.
  1. Using proper hygiene for network protection on all platforms, such as smartphone apps.
  • Always be cautious before opening any email from an unknown source, as phishing emails are the most common attack.
  • Just mount plug-ins for the browser from trusted sources.
  • Log out from inactive accounts to reduce the chance of exploits to disprove persistent cookies.
  • Whenever you need a secure link but don’t get just stop there and run a security scan.
  1. Avoid using public Wi-Fi: The phone should be configured to require a manual link while using public Wi-Fi. It can be hard to identify an MITM attack, so the easiest thing to be secure is to include all these above points regularly. As we know, these are a part of social engineering, so if something seems abnormal, take some time and dig into it.

I have written the code in Swift language. Feel free to comment down below for any queries. You can access the complete code at GitHub. You can check this URL: 

Note: The certificate added in my repository can expire, so if you are not able to get a response from API, then check for the certificate and get a new one by following the above steps


Leave a Reply

Your email address will not be published. Required fields are marked *