tru.ID logo
LoginSignup

SIM Swap Detection with Android Firebase Phone Authentication

In this tutorial, you'll learn how to add SIM swap detection to an Android application authenticated with Firebase Phone Auth. You'll use SIMCheck to check if the SIM card associated with a phone number has changed recently in order to detect potential SIM swap attacks.

Timothy Ogbemudia

Developer Experience Engineer

Last updated: 12 August 2021

tutorial cover image

Many applications use Firebase Phone Auth to add SMS two-factor authentication (2FA) phone verification. By layering on tru.ID SIMCheck, you can provide applications and users with an extra layer of protection against SIM swap fraud. In general, SIMCheck can be used to augment existing 2FA or enhance anti-fraud workflows.

If you wish to skip the tutorial but want to see the finished code sample, you can find it on GitHub.

Before you begin

You'll need the following in order to complete this tutorial:

  • A mobile phone with a SIM card and mobile data connection
  • a tru.ID Account
  • NPM installed locally

Get Started

Clone the Github repository and check out the ‘starter-files’ branch to follow this tutorial with the following command in your Terminal:

$ git clone -b starter-files --single-branch https://github.com/tru-ID/firebase-phone-auth-sim-swap-detection-android.git

The tru.ID CLI will allow you to input and store your credentials for your account. It'll also allow you to create a tru.ID project for your application. In your Terminal, install the CLI with the following command:

$ npm install -g @tru_id/cli

You'll be asked to enter your tru.ID credentials, which are found in the tru.ID console.

$ tru setup:credentials {YOUR_CLIENT_ID} {YOUR_CLIENT_SECRET} EU

The tru.ID CLI has a development server plugin, which will initialize a local server and run a LocalTunnel to expose your project to the Internet. This is needed so your mobile application can communicate with your dev server. Install the plugin by running:

$ tru plugins:install @tru_id/cli-plugin-dev-server

In this next step, we're going to create a new tru.ID project. A project is a container that stores the credentials to authenticate the application when making requests to the API. Create a project by running the following command within the root project directory:

tru projects:create firebase-android --project-dir .

Run the development server using the --project-dir flag to point it to the directory containing the newly created project configuration. This will also open up a localtunnel to your development server, making it publicly accessible to the Internet so that your mobile phone can access it when only connected to mobile data. You will get a localtunnel URL in the form https://{subdomain}.loca.lt.

tru server -t --project-dir .

Set up Firebase Phone Auth for Android

This project uses Firebase Phone Auth for Android. The official documentation for this service will give a more in-depth description of how to get set up. However, below I've added a checklist on the steps you'll need to complete in order to progress:

  • Create a Firebase account.
  • Create a new Firebase project.
  • In the menu on the left is an item labelled Authentication. Click this and select the Sign-in method tab. Enable Phone as a sign-in method.
  • Next, in the Project settings, create an Application by clicking Add app. Choose the Android button. Then enter the Android application name (in this instance, it is com.example.firebaseandroid). Follow the instructions, but don't download the google-services.json file just yet.
  • In your Project settings, select the App Check tab and enable Safety Net. This will need an SHA-256 fingerprint retrieved by running the following command in the terminal: ./gradlew signingReport. (Note: Be sure to get the SHA-256 entry under the Variant: debug section.)
  • Download google-services.json and save it in the app directory beside build.gradle.

Finally, connect your phone to your computer so it's used for running the Android project and run the application from your IDE.

Your app should look like this:

Android Starter App

If you cloned the repository from GitHub and checked out the starter-files branch at the beginning of this tutorial, you can run the application on your phone and see it is a fully functional application with authentication using Firebase's Phone Auth. We're now going to add SIM Swap detection to this application.

Add SIM swap detection

Before the user authenticates with Firebase Phone Auth, we would like to perform SIM swap detection using the tru.ID SIMCheck API to ensure the user is not a victim of SIM swap fraud. Only if the user is successfully authenticated with SIMCheck do we proceed with Firebase Phone Authentication.

The first step is to detect if the SIMCheck API supports the user's mobile carrier. To do this, we'll use the tru.ID Android SDK – specifically, the isReachable function. This function returns information like the network provider and an array of supported products.

Next, we'll create the SIMCheck resource by sending a POST request to base_url + /sim-check with the user's phone number to the development server.

When we make that request, we get back a no_sim_change property which is a boolean indicating whether the SIM card related to the phone number changed recently.

First add the following imports to app/build.gradle:

dependencies {
// HTTPS
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0'
implementation 'id.tru.sdk:tru-sdk-android:0.2.5'
}

Be sure to sync with Gradle after this.

Next, we need add the imports listed below to the top of src/main/java/com/example/firebaseandroid/MainActivity.kt:

import id.tru.sdk.TruSDK
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

In this MainActivity.kt file, locate the onCreate() function, and add the following code to initialize the tru.ID SDK above the auth = FirebaseAuth.getInstance() line:

TruSDK.initializeSdk(this.applicationContext)

Next, within SubmitHandler.setOnClickListener and underneath setUIStatus(SubmitHandler, phoneInput, false), paste the following:

CoroutineScope(Dispatchers.IO).launch {
val truSdk = TruSDK.getInstance()
val reachabilityDetails = truSdk.isReachable()
var supportsSimCheck = false
reachabilityDetails?.let {
if (it.error == null && it.products?.size!! >= 1) {
it.products?.forEach {
if (it.productId == "SCK") {
supportsSimCheck = true
}
}
}
}
if (!supportsSimCheck) {
renderMessage("Something went wrong.", "Please contact support.")
setUIStatus(SubmitHandler, phoneInput, true);
return@launch
}
}

Here, we call the isReachable function and create a mutable variable supportsSimCheck. If we have a list of products, we loop through the products and see if any supported product IDs match the ‘Sim Check’ product ID. If there is a match, it means we support the SIMCheck API, then we set our supportsSimCheck variable to true. Else, we set it to false.

We then check if the variable is false – i.e. we do not support the SIMCheck API – and we render an error message and enable the UI.

Create the SIMCheck resource

The next step is to create the SIMCheck resource.

Create a folder (package) called API within src/main/java/com/example/firebaseandroid. Then within this new folder, create a new subfolder called data.

Now, within data, create a class called SIMCheck.kt and copy the following code sample into this file:

package com.example.firebaseandroid.API.data
import com.google.gson.annotations.SerializedName
data class SIMCheckPost(@SerializedName("phone_number") val phone_number: String)
data class SIMCheckResult(@SerializedName("no_sim_change") val no_sim_change: Boolean)

The example above defined two new data model classes called:

  • SIMCheckPost which maps to the POST body
  • SIMCheckResult which maps to the response of the POST request to /sim-check

We use @SerializedName to ensure the values match the expected input and response.

Next, navigate back to the API folder and create another folder (package) named retrofit. Within it, create an interface named RetrofitService and replace its contents with the following:

package com.example.firebaseandroid.API.retrofit
import com.example.firebaseandroid.API.data.SIMCheckPost
import com.example.firebaseandroid.API.data.SIMCheckResult
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Headers
import retrofit2.http.POST
interface RetrofitService {
@Headers("Content-Type: application/json")
@POST("/sim-check")
suspend fun createSIMCheck(@Body user: SIMCheckPost): Response<SIMCheckResult>
companion object {
const val base_url = "https://{subdomain}.loca.lt"
}
}

Here, we make use of the model we created to make the POST request. We also create a companion object, which allows us to access base_url as an object (i.e. RetrofitService.base_url).

Remember to replace the placeholder URL value in base_url with the localTunnel URL for your running development server.

Request the SIMCheck resource

All that's left is to make the POST request to the SIMCheck endpoint.

First, ensure to add the relevant imports to MainActivity.kt:

import com.example.firebaseandroid.API.retrofit.RetrofitService
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import com.example.firebaseandroid.API.data.SIMCheckPost
import com.example.firebaseandroid.API.data.SIMCheckResult

Next, create a function to handle data fetching with retrofit at the bottom of MainActivity.kt:

//retrofit setup
private fun rf(): RetrofitService {
return Retrofit.Builder().baseUrl(RetrofitService.base_url).addConverterFactory(
GsonConverterFactory.create()).build().create(RetrofitService::class.java)
}

Next, within SubmitHandler.setOnClickListener and underneath the if (!supportsSimCheck) block, paste the following:

val response = rf().createSIMCheck(SIMCheckPost(phoneNumber))
if (response.isSuccessful && response.body() != null) {
val simCheckResult = response.body() as SIMCheckResult
// update the UI if the SIM has changed recently
if (!simCheckResult.no_sim_change) {
renderMessage("SIM Changed Recently. Cannot Proceed 😥", "SIM-Changed")
setUIStatus(SubmitHandler, phoneInput, true);
return@launch
}
}

Here, we call our data fetching function and get the response. If the SIM has changed we render a message informing the user.

If the SIM has changed, the UI will look like this:

SIM Card changed recently UI.

The last step is to ensure we make the SIMCheck before Firebase Phone Authentication. For that, first remove the following from the bottom of the else block:

// proceed with Firebase Phone Auth
val options = PhoneAuthOptions.newBuilder(auth!!)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
.build()
PhoneAuthProvider.verifyPhoneNumber(options)

We only want to proceed with the Firebase Phone Auth if we have a successful SIMCheck response. So we'll move the block we removed and place it below the if (!simCheckResult.no_sim_change) block.

Update CoroutineScope(Dispatchers.IO).launch to the same as the example below:

CoroutineScope(Dispatchers.IO).launch {
val truSdk = TruSDK.getInstance()
val reachabilityDetails = truSdk.isReachable()
var supportsSimCheck = false
if (reachabilityDetails != null) {
if (reachabilityDetails.error == null && reachabilityDetails.products?.size!! >= 1) {
reachabilityDetails.products?.forEach {
if (it.productId == "SCK") {
supportsSimCheck = true
}
}
}
}
if (!supportsSimCheck) {
renderMessage("Something went wrong.", "Please contact support.")
setUIStatus(SubmitHandler, phoneInput, true)
return@launch
}
val response = rf().createSIMCheck(SIMCheckPost(phoneNumber))
if (response.isSuccessful && response.body() != null) {
val simCheckResult = response.body() as SIMCheckResult
// update the UI if the SIM has changed recently
if (!simCheckResult.no_sim_change) {
renderMessage("SIM Changed Recently. Cannot Proceed 😥", "SIM-Changed")
setUIStatus(SubmitHandler, phoneInput, true)
return@launch
}
// proceed with Firebase Phone Auth
val options = PhoneAuthOptions.newBuilder(auth!!)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this@MainActivity) // Activity (for callback binding)
.setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
}

Here, we proceed with Firebase Phone Authentication only if we have a response and if the SIM has not changed.

The image below shows an example of there being no SIM swap fraud, but the authentication with Firebase Phone Auth has failed:

tru.ID verification successful but Firebase Phone Auth verification failed

The image below shows an example of there being no SIM swap fraud, and the authentication with Firebase Phone Auth has passed:

tru.ID verification successful and Firebase Phone Auth verification successful

That's it!

Wrapping up

If you've made it this far in the tutorial, we've managed to:

  • Set up an existing Android application that authenticates with Firebase Phone Auth
  • Create a tru.ID account and configure this through the tru.ID CLI
  • Modify the existing Android application to first detect any signs of SIM swap fraud
  • If there is no sign of SIM swap fraud, then proceed to authenticate with Firebase Phone Auth

Resources

tru.ID logo

Platform

Docs

DON'T MISS A BEAT — STAY ON THE DOT!

Keep current with industry news and updates from tru.ID.

Follow us on:

Made with ❤️ across the 🌍

© 2021 4Auth Limited. All rights reserved. tru.ID is the trading name of 4Auth Limited.