SSL Pinning in Android

Amit Gupta
5 min readJan 12, 2022

I have seen many people are confused for SSL pinning in Android , So I want to share my experience for it and I will be happy to see comments if anything in this article is written wrong.

What is SSL Pinning:

According to the documentation, SSL stands for Secure Sockets Layer. SSL is the standard security technology for establishing an encrypted link between a client and a server. This link ensures that all data passed between the web server and browser remain private.SSL is the most widely deployed cryptographic protocol to provide a secure communication channel.

SSL pinning is a process of associating a host with the expected X509 certificate or public key. Once a certificate or public key is known or seen for a host, the certificate or public key is associated or ‘pinned’ to the host. If more than one certificate or public key is acceptable then advertised identity must match one of the elements in the certificate chain set. This allows the application to trust only the valid or pre-defined certificates or public Keys. We should use SSL pinning technique as an additional security layer for application traffic and to validate the remote host’s identity. If we do not implement SSL Pinning, application trusts custom certificate and allows proxy tools to intercept the traffic.

Why SSL is Important:

There are 3 important security aspects:

1.) Client app on user phone should have surety that it is communicating to the app server only and not to the proxy server or intruder in between the client and server connection. (SSL Certificate Pinning)

2.) Server should have surety that the data which is received from the client is genuine and should not be changed in between the communication.(HTTPS Protocol Connection)

3.) Android Phone is having preinstalled CA authority in the phone binary which is responsible to check the certificates are valid or not. So if any person downloads the unauthorised CA at Airport or Railway Station in the phone to use their Wifi then they can become victim of MITM if that CA is suspicious.So SSL Pining certificates helps to avoid MITM.

Note : Do you think , We should take care that Server should also validate the client whether it is genuine client/user?

  1. ) I think , it is not required if attacker is making any such modification on his/her device, then it will not effect other users, So why backend will care for it.
  2. ) If that communication is related to payment then at server we can make Server to Server calls to validate the amount and can also generate different token with OTP mechanism to secure that transaction.

How SSL provides the Security?

  1. ) SSL Certificate Pinning: A Man-in-the-Middle attack occurs when an attacker places himself between the server/host and the client, impersonating one of them. In other words, when the client is connecting to the server, it is actually dealing with the hacker and vice versa. Thus, although the client “thinks” that it has established an encrypted connection with the server, but in reality both of them are actually “talking” to the attacker who can view and modify the data. For this reason, everyone calls it a “Man-in-the-Middle” attack.
  2. HTTPS: SSL encrypts the data being transmitted so that a third party or any “Man-in-the-Middle” cannot “eavesdrop” on the transmission and view the data being transmitted. Only the client and the secure server are able to recognise and understand the data. This means that anyone who tries to intercept this data will only see a garbled mix of characters that’s nearly impossible to decrypt.

How to Implement SSL Pinning:

Certificate Pinning is easiest to achieve. We can store the certificate in our application and when the certificate expires, we would update our application with the new certificate. At runtime, we retrieve the server’s certificate in the callback. Within the callback, we compare the retrieved certificate with the certificate embedded within our app. If it matches, we can trust the host else we will throw a SSL certificate error.

Downsides with Solution:

  1. ) If the Certificates gets expired then we have to rotate these certificates proactively in android code so that it can be reached to all users even for the previous market builds.
  2. ) To solve the problem in Step1, We can fetch the certificate from the server config Apis during App launch or may use Firebase Config to update the certificates proactively and it will be updated into the app for previous market version.

Let’s Come to Coding to Implement the SSL Pinning:

Let’s first create the TrustManager which is responsible for modifying and injecting the certificates through key store into Certification Authority verification process.

fun getCertStreamPath(){

return certStream = if(SharedPreferences.getString(“certKey”, null)!=null){

// return stream for file fetched from server config or firebase config //response

}else{

resources.openRawResource(R.raw.my_cert)

}

val inputStream = getCertStreamPath();
val keyStoreType = KeyStore.getDefaultType()
val keyStore = KeyStore.getInstance(keyStoreType)
keyStore.load(inputStream, null)

val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm()
val trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm)
trustManagerFactory.init(keyStore)

val sslContext = SSLContext.getInstance(“TLS”)
sslContext.init(null, trustManagerFactory.trustManagers, null)
val url = URL(“http://www.yourdomain.com/")
val urlConnection = url.openConnection() as HttpsURLConnection
urlConnection.sslSocketFactory = sslContext.socketFactory

Now Certification Authority which is Preinstalled in your phone binary will verify this certificate from TrustManager with the certificate fetched from server during SSL handshaking.If they get matched then only SSL handshaking will be completed and client app can trust that response is coming from trustworthy server.

Note: After Android N , Android gives us one setting in NetworkConfig xml file to avoid to install the User certificates and hence no suspicious CA can’t harm our app if we provide that setting in NetworkConfig xml file. But if device is having version lesser than Android N , then without SSL pinning app can be strong candidate for MITM.

SERVER Certificates Security on Mobile APP:

Many people will say that these certificates can be stolen from the apk of Mobile app , Let’s Attacker steal that , Do we need to worry about it?

Answer is No, Majority of Rest Apis are exposed publically and certificates can be found publically by using some commands for any domain , But we don’t care for it , since from SSL pining we are just authenticate that client app is communicating with the correct Server nothing else so normal user phone just have surety that his phone app is getting data from the app server only.

I have covered the points in this article which confuse many developers while implementing the SSL pinning , I was also confused first time once I started working on it , But after going deep from you tube videos and different articles , I have concluded all these things. I can’t mention these you tube videos and articles since I do not remember them right now. Just wrote this article since many people ask these questions to me.

I hope you will like this article , If someone feel my understanding is wrong , please give comments and if someone need clarification on some parts of SSL pinning, please comment , I will try to clarify those things. Please don’t forgot to clap if you liked this information.

Due to lack of time, For content , I have taken reference from the article mentioned below :

--

--