How to Implement SSL Pinning in Swift (2024)

Prevent man-in-the-middle attacks in your app, whether you use Apple’s APIs or Alamofire

How to Implement SSL Pinning in Swift (1)

Privacy — like eating and breathing — is one of life’s basic requirements.

— Katherine Neville

Nearly every iOS app communicates with servers to retrieve information. Sometimes this information is sensitive and you don’t want anyone to be able to access them (for example, their username and password to sign in to the app).

At the launch of iOS 9, Apple introduced App Transport Security, which forces apps to use a secure network connection by adopting HTTPS protocol and Transport Layer Security (TLS). What does this mean? It means our apps can’t communicate with a server through a non-secure connection. Actually, it’s possible to bypass this restriction but to avoid potential attacks, it’s not recommended.

So my data is safe, right? The answer is no! Even if TLS protects the transmitted data, it’s easier for an attacker to set up man-in-the-middle attacks using hacked or self-signed certificates. This means they can capture data moving to and from your app.

In this article, I’ll explain how to prevent these kind of attacks in order to make your app data safe. We will cover some basic knowledge on the following topics:

First, we need to understand how TLS and man-in-the-middle attacks work, to understand how to prevent them. TLS allows you to transmit data over a secure network, following three phases:

  • The client initiates a connection with the server by sending a message that includes the supported version of TLS and the cipher suite used for encryption. The server responds with the selected cipher suites and a digital certificate. The client verifies that those digital certificates are authentic (i.e. issued by a certificate authority).
  • If the validation succeeds, the client generates a pre-master key encrypted with the server’s public key included in the certificate. The server decrypts the secret with its private key. Both use this secret to generate a master key.
  • Both use encryption of plaintext and decryption of ciphertext by using the master key and symmetric encryption.

But, what is a certificate? A certificate is proof of identity of the server. It’s just a file that contains information about the server that owns the certificate and follows the X.509 standard. The client only trusts a server that can provide a valid certificate signed by one of the trusted Certificate Authorities, otherwise, the connection will be aborted.

In order to validate it, the app verifies:

  • The expiry date.
  • The digital signature.

A man-in-the-middle is an attack in which the attacker secretly listens and eventually alters the communication between two parties. It’s easier than you may think to use this kind of attack to intercept data that an app is sending to a server. All you need is a SSL Proxy Server.

The SSL proxy performs encryption and decryption between the client and the server (the keys are different for both direction). An example is Charles. It sits between your app and the internet and you can inspect and even change data midstream to test how your app responds.

  • Your app encrypts data with the Charles ProxyCertificate public’s key, instead of the server’s. The Charles Certificate is validated because the developer can install it in his device.
  • Charles is able to decrypt all data with its private key and then communicate with the server using the server’s public key.

This means that any developer can read all the data that your app is sending over the network!

Here’s how to set up Charles.

Fortunately, there’s a simple way to prevent this kind of attack through a technique called SSL Pinning.

This technique validates the server certificates again, even after SSL handshaking. The developer embeds a list of trustful certificates inside the client application and compare them with the server certificates during runtime. In case of a mismatch between the server’s certificates and the local copy, the connection is simply aborted.

This means that the app will check the Charles’s certificate and, even if it’s trusted, it will be different from the local certificate embedded inside the app.

One con is that a pinned certificate has an expiration date and this requires an app update, unless the developer also pins future certificates inside the app. Actually, instead of pinning the whole certificate, you can just use the hashed public key (this is a better approach because we can reuse the same hashed key also in future certificates).

Evaluating trust is a two-step process.

  • Validate the certificate’s digital signature. Your app can rely on any of the root certificates embedded in iOS or you can supply your own.
  • Testing the certificate against a trust policy. The policy indicates how particular fields or extensions of a certificate should be in order to be trusted.

All of this activity is facilitated by an instance of the SecTrust object that you prepare with one or more certificates and policy objects.

Prepare the certificate

Apple provides the SecCertificate to represent a X.509 certificate. If you add the certificate inside the bundle you can retrieve it with:

let filePath = Bundle.main.path(forResource: name, ofType: type)!let data = try! Data(contentsOf: URL(fileURLWithPath: filePath))let certificate = SecCertificateCreateWithData(nil, data as CFData)

Here you can find also more complex solutions — for example, using keychain and identity. There isn’t a “best” solution, because it mostly depends on the problem and on the level of security you need in your app. I suggest you read up and try them all, then decide which one suits your needs.

Prepare a policy

The best option is usually to use one of the predefined policies. For example, you could use the standard basic policy for X509 certificates with:

let policies = SecPolicyCreateBasicX509()

This is probably enough for your app, but if you need more flexibility you can create your own SSL policy with the SecPolicyCreateSSL(_:_:).

The SecTrust

Now it’s time to validate both certificates and policies. Apple facilitates all these operations with a SecTrust object.

var optionalTrust: SecTrust?
let status = SecTrustCreateWithCertificates(certArray as AnyObject,
policy,
&optionalTrust)
guard status == errSecSuccess else { return }
let trust = optionalTrust!

SecTrustCreateWithCertificates(_:_:_:) creates a trust management object based on the provided certificates and policies.

You can use SecTrustEvaluateWithError(_:_:) to validate a trust object. From the documentation:

This method evaluates a certificate’s validity to establish trust for a particular use — for example, in creating a digital signature or to establish a Secure Sockets Layer connection. The method validates a certificate by verifying its signature plus the signatures of the certificates in its certificate chain, up to the anchor certificate, according to the policy or policies included in the trust management object.

If the trust management instance lacks some of the certificates needed to verify the leaf certificate, SecTrustEvaluateWithError(_:_:) searches for certificates:

- In the user’s keychain.

- Among any certificates you previously provided by calling SecTrustSetAnchorCertificates(_:_:).

- In a system-provided set of keychains provided for this purpose.

- Over the network, if certain extensions are present in the certificate used to build the chain.

The only thing that you need now is to evaluate the SecTrust that you receive during a network call with your policies and compare the certificate with the one pinned inside the app.

Let’s take a look at an example:

This is a simple example, but there are many other parameters and objects to handle all the possible validations of a SecTrust. I suggest you carefully read all the documentation provided by Apple and test it before trying to use it in your app.

Here the main link.

As you can see, using the normal API is quite complex. I recommend using Alamofire, an external library that provides a higher level of API making your life simpler.

Everything is based on the ServerTrustEvaluating protocol that provides a way to perform any sort of server trust evaluation. Alamofire includes many different types of trust evaluators, for example:

  • DefaultTrustEvaluator: Allows you to control whether to validate the host provided by the challenge.
  • RevocationTrustEvaluator: Checks the status of the received certificate to ensure it hasn’t been revoked.
  • PinnedCertificatesTrustEvaluator: The server trust is considered valid if one of the pinned certificates matches one of the server certificates.
  • PublicKeysTrustEvaluator: The server trust is considered valid if one of the pinned public keys matches one of the server certificate’s public keys.

You only have to choose which ServerTrustEvaluating to use for each API:

let evaluators: [String: ServerTrustEvaluating] = [
"cert.example.com": PinnedCertificatesTrustEvalutor(),
]

let manager = ServerTrustManager(evaluators: serverTrustPolicies)

Then create a session with them:

let serverTrustManager = ServerTrustManager(evaluators: evaluators)self.session = Session(serverTrustManager: serverTrustManager)

You can read the full documentation here.

If you want to do some tests or you need to validate a public API you can download the certificate and pin it to your app.

Open your terminal and write the following:

openssl s_client -connect <url>:443 </dev/null \
| openssl x509 -outform DER -out <filename>.der

This will download the certificate into your current folder.

I hope you enjoyed the article! Fell free to reach out to me if you have any doubts.

How to Implement SSL Pinning in Swift (2024)

FAQs

How is SSL pinning implemented? ›

You can directly pin the SSL certificate by binding the certificate in your applications. However, it is significant to implement the transition plan before the certificate expires, else older applications will provide errors. The next method for SSL certificate pinning is pinning the certificate's public key.

How do I enable SSL pinning? ›

Public Key Pinning

In this approach, we generate a keypair, put the private key in our server and the public key in our app. And just like in certificate pinning, we check the extracted public key with its embedded copy of the public key. If it matches, we can trust the host else we will throw a SSL certificate error.

How do I know if SSL pinning is implemented? ›

Testing request capture with SSL Pinning implemented

In the first place it could be seen on the event log on the dashboard of Burp that the connection SSL, when requests are sent on the application, can't be done because it fails on the exchange of certificates.

What is SSL vs SSL pinning? ›

To think big picture: an SSL connection tells the client to make an encrypted connection with any identity matching that host. Pinning tells the client a specific identity they should accept when making a secure connection. So, for example, if our site is TheSSLStore.com, we could pin an identity.

How to implement SSL pinning in mobile app? ›

Types of SSL Certificate Pinning
  1. Pin the certificate: You can download the server's certificate and bundle it into your app. At runtime, the app compares the server's certificate to the one you've embedded.
  2. Pin the public key: You can retrieve the certificate's public key and include it in your code as a string.

How to generate SSL certificate for iOS app? ›

Creating the iOS Distribution Certificate
  1. Sign in to your Apple Developer account and navigate to Certificates, IDs & Profiles > Certificates > Production.
  2. Add a new certificate.
  3. Set up a certificate of type Production and activate App Store and Ad Hoc.
  4. Click Continue.
Nov 14, 2022

How do I add an SSL certificate to my app? ›

The process is:
  1. Prerequisite: A chosen SSL-certificate vendor.
  2. Create the key file and the signing request file needed by the vendor.
  3. Purchase the SSL certificate from chosen vendor.
  4. Install an SSL certificate in your Engine Yard account.
  5. Apply the SSL certificate to an environment.
  6. Verify your SSL certificate.
May 17, 2022

What is the use of SSL pinning iOS? ›

SSL Pinning is a method used in Swift. A language used in the iOS platform to prevent dangerous security attacks by pinning trustworthy certificates. This typically allows you to verify the identity and refuse all connections different from the designated server.

How many implementation methods are there for SSL? ›

There are three kinds of cryptographic techniques used in SSL: Public-Private Key, Symmetric Key, and Digital Signature.

How do you implement SSL on a server? ›

Binding a certificate to port 443 in IIS
  1. Select your site in the tree view and in the Actions pane, click Bindings. If port 443 is not available in the Bindings list, click Add. From the Type drop-down list, select https. ...
  2. From the SSL certificate drop-down list, select your certificate name and click OK.

Why SSL pinning is not recommended? ›

There is a downside to pinning a certificate. If the site rotates its certificate on a regular basis, then your application would need to be updated regularly. For example, Google rotates its certificates, so you will need to update your application about once a month (if it depended on Google services).

Is certificate pinning still used? ›

Securing your mobile applications ensures that you and your customers are safe. And unfortunately, just using SSL and HTTPS doesn't fully protect your data. Instead, certificate pinning currently tops the list of ways to make your application traffic secure.

What is the difference between public key pinning and certificate pinning? ›

The only difference between certificate pinning and public key pinning is what data you are checking against in your whitelist. Since the certificate contains the public key you can think of the certificate being a superset of the data being checked.

Who holds public key for SSL pinning? ›

SSL Pinning is the process of associating a host with their expected X509 certificate or a public key. Once a host's certificate or public key is known or identified, the certificate or public key is associated or 'pinned' to the host.

How to validate SSL certificates on iOS? ›

If you want to turn on SSL/TLS trust for that certificate, go to Settings > General > About > Certificate Trust Settings. Under "Enable full trust for root certificates," turn on trust for the certificate. Apple recommends deploying certificates via Apple Configurator or Mobile Device Management (MDM).

Why is SSL on port 443? ›

HTTPS is secure and is on port 443, while HTTP is unsecured and available on port 80. Information that travels on the port 443 is encrypted using Secure Sockets Layer (SSL) or its new version, Transport Layer Security (TLS) and hence safer.

Is SSL pinning a vulnerability? ›

What is SSL Pinning? It is a process where we can check the authenticity of a HOST by checking its core X509 certificate. This X509 certificate is the integral part of SSL. we can find more about it here X509 certificate.

Do mobile apps use SSL certificate? ›

Mobile apps have access to almost everything – from your personal information to banking details to passwords. Utilizing SSL/TLS certificates helps app developers ensure that users' data – stored and in transit – remains protected and uncompromised.

How to create certificate in Swift? ›

Create a certificate signing request
  1. Launch Keychain Access located in /Applications/Utilities .
  2. Choose Keychain Access > Certificate Assistant > Request a Certificate from a Certificate Authority.
  3. In the Certificate Assistant dialog, enter an email address in the User Email Address field.

How do I add a certificate to Xcode? ›

REQUIREMENTS:
  1. Launch Xcode.
  2. Go to the Preferences...
  3. Select the Account tab.
  4. Select your account.
  5. Select the appropriate Team and click on Manage Certificates... ...
  6. Click on the + icon and select the type of certificate you need, depending on the Build Type.
Jan 23, 2017

How do I manually create a SSL certificate? ›

How to Create an SSL Certificate for Manual Installation
  1. Step One: Generate Your CSR. ...
  2. Step Two: Start Your Order on the Gandi Website. ...
  3. Step Three: Provide the Necessary Documents. ...
  4. Step Four: Validate Your Domain. ...
  5. Step Five: Answer Callback. ...
  6. Step Six: Await Verification.

How do I enable certificates in IOS? ›

If you want to turn on SSL/TLS trust for that certificate, go to Settings > General > About > Certificate Trust Settings. Under "Enable full trust for root certificates", turn on trust for the certificate. Apple recommends deploying certificates via Apple Configurator or Mobile Device Management (MDM).

How do I create and install an SSL certificate? ›

  1. 1 Have the Correct Website Information. ...
  2. 2 Decide Which SSL Certificate You Need. ...
  3. 3 Choose a Certificate Authority. ...
  4. 4 Generate a Certificate Signing Request (CSR) ...
  5. 5 Submit the CSR to Your Certificate Authority. ...
  6. 6 Await Validation by Your Certificate Authority. ...
  7. 7 Install Your SSL Certificate.
Jan 5, 2023

How do I ensure SSL certificate is installed correctly? ›

Check installation of the certificate using one of these checkers: sslchecker, certlogic, SSLLabs. Make sure that there is an automatic redirect from http://yourdomain.tld to https://yourdomain.tld (if needed). Check that port 443 is open. Avoid displaying any insecure content here.

Is certificate pinning deprecated? ›

HTTP Public Key Pinning (HPKP) is an obsolete Internet security mechanism delivered via an HTTP header which allows HTTPS websites to resist impersonation by attackers using misissued or otherwise fraudulent digital certificates.

What SSL pinning is and how it can be bypassed? ›

SSL Pinning Bypass can be prevented using two-way SSL authentication. Two-way SSL Authentication also known as mutual authentication between client and server. The application acts as SSL client and send its certificate to the SSL server to validate after SSL server validates itself to the SSL client.

What does enabling SSL do? ›

In short: SSL keeps internet connections secure and prevents criminals from reading or modifying information transferred between two systems. When you see a padlock icon next to the URL in the address bar, that means SSL protects the website you are visiting.

What are the 3 types of SSL? ›

There are three recognized categories of SSL certificate authentication types:
  • Extended Validation (EV)
  • Organization Validation (OV)
  • Domain Validation (DV)

What are the 4 stages of SSL? ›

How an SSL connection is established
  • The client sends a request to the server for a secure session. ...
  • The client receives the server's X. ...
  • The client authenticates the server, using a list of known certificate authorities.
  • The client generates a random symmetric key and encrypts it using server's public key.

How does SSL work step by step? ›

how SSL works
  1. A browser attempts to connect to a web site secured with SSL. ...
  2. The server sends the browser a copy of its SSL certificate.
  3. The browser checks whether it trusts the SSL certificate. ...
  4. The server sends back a digitally signed acknowledgement to start an SSL encrypted session.

What is SSL and how do you implement it? ›

SSL uses port number 443, encrypting data exchanged between the browser and the server and authenticating the user. Therefore, when the communications between the web browser and server need to be secure, the browser automatically switches to SSL — that is, as long as the server has an SSL certificate installed.

What are the different types of SSL implementation? ›

There are three types of SSL Certificate available today; Extended Validation (EV SSL), Organization Validated (OV SSL) and Domain Validated (DV SSL). The encryption levels are the same for each certificate, what differs is the vetting and verification processes needed to obtain the certificate.

Where is SSL implemented? ›

SSL can only be implemented by websites that have an SSL certificate (technically a "TLS certificate"). An SSL certificate is like an ID card or a badge that proves someone is who they say they are. SSL certificates are stored and displayed on the Web by a website's or application's server.

What are the cons of SSL pinning? ›

Certificate pinning does not help provide integrity of network communication as SSL does. It does not help in the compromised private key of a pinned certificate. It does not protect the jailbroken device or rooted device. It does not avoid reverse engineering.

What is more secure than SSL? ›

Transport Layer Security (TLS) is the successor protocol to SSL. TLS is an improved version of SSL. It works in much the same way as the SSL, using encryption to protect the transfer of data and information.

Is certificate pinning a good idea? ›

In a word - yes; when implemented correctly, certificate pinning is an effective method for securing mobile application traffic by restricting the accepted certificates to just those you are willing to trust.

Is SSL certificate a public key? ›

When performing authentication, SSL uses a technique called public-key cryptography. Public-key cryptography is based on the concept of a key pair, which consists of a public key and a private key. Data that has been encrypted with a public key can be decrypted only with the corresponding private key.

What is SSL pinning in iOS Swift? ›

SSL Pinning is a method used in Swift. A language used in the iOS platform to prevent dangerous security attacks by pinning trustworthy certificates. This typically allows you to verify the identity and refuse all connections different from the designated server.

How do I use SSL in REST API? ›

Configure SSL settings in the configuration file:
  1. Copy the SSL settings from the *. xml. ...
  2. Open the configuration file: ...
  3. Add the keystore file location and password to the keyStore element. ...
  4. Optional: Encrypt the password using the securityUtilities command. ...
  5. Save your changes to server_ascd.

What is pinning in Swift? ›

SSL Pinning is a technique used in swift to prevent man-in-middle attacks. In this process, the app validates the Server's certificate again after the SSL handshaking. There is a local copy of trustful certificates maintained at the client's end and compare them with the Server's certificates at runtime.

Why do we need to bypass SSL pinning? ›

Because organizations are more concerned about data privacy as well as secure data transfer over the network from threats like Man-in-the-Middle (MiTM) attacks, SSL pinning bypass is a major step that needs to be done before we even start the dynamic analysis of HTTP requests for most mobile applications nowadays.

How do I enable SSL on HTTP? ›

To do this, follow these steps:
  1. Select the Directory Security tab. In the Secure Communication section, Edit is now available. Select Edit.
  2. Select Require Secure Channel (SSL). Note.
Jan 24, 2022

How do I deploy an SSL certificate? ›

In the Websites and Domains section for the domain name you want to use, click SSL/TLS Certificates. Click Add SSL Certificate. Enter a Certificate name, complete the fields in the Settings section, and then click Request.

How do I configure SSL? ›

Procedure
  1. Click Security > SSL certificate and key management > Manage endpoint security configurations.
  2. Select an SSL configuration link on either the Inbound or Outbound tree, depending on the process you are configuring. ...
  3. Click SSL configurations. ...
  4. Click New to display the SSL configuration panel.

What is dynamic SSL pinning? ›

The SSL pinning (or public key, or certificate pinning) is a technique mitigating Man-in-the-middle attacks against the secure HTTPS communication. The typical Android solution is to bundle the hash of the certificate, or the exact data of the certificate into the application.

What are the disadvantages of SSL pinning? ›

Certificate pinning does not help provide integrity of network communication as SSL does. It does not help in the compromised private key of a pinned certificate. It does not protect the jailbroken device or rooted device. It does not avoid reverse engineering.

Is certificate pinning worth it? ›

In a word - yes; when implemented correctly, certificate pinning is an effective method for securing mobile application traffic by restricting the accepted certificates to just those you are willing to trust.

How do I mitigate SSL pinning? ›

SSL Pinning Bypass can be prevented using two-way SSL authentication. Two-way SSL Authentication also known as mutual authentication between client and server. The application acts as SSL client and send its certificate to the SSL server to validate after SSL server validates itself to the SSL client.

Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 6274

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.