Steal That Api Key With A Man In The Middle Attack
Tags: mobile, android, api, security
Published: 2019-12-04 18:04:42

---
title: "Steal That Api Key With A Man In The Middle Attack"
canonical_url: "https://blog.approov.io/steal-that-api-key-with-a-man-in-the-middle-attack"
cover_image: "https://thepracticaldev.s3.amazonaws.com/i/t820vkx4q2qchw5cg5kv.jpg"
published: true
description: "Learn how to setup and run a MitM attack to intercept https traffic in a mobile device under your control, so that you can steal that API key. Finally, you will see at a high level how MitM attacks can be mitigated."
tags: "mobile, android, api,security" 
---

![man-in-the-middle](https://thepracticaldev.s3.amazonaws.com/i/5f6v6evao432j9c90jer.png)

As I promised in my [previous article](https://blog.approov.io/how-to-extract-an-api-key-from-a-mobile-app-with-static-binary-analysis), here it is the follow up article about performing a man in the middle (MitM) attack to steal an API key, and to follow this article you will need to become the man sitting in the middle of the actual channel, using mitmproxy to help you with the task of stealing the API key. Now it should be clear why MitM stands for man in the middle!

In order to help to demonstrate how to steal an API key, I have built and released in Github the [Currency Converter Demo](https://github.com/approov/currency-converter-demo/tree/0.1.1) app for Android, which uses the same [JNI/NDK](https://developer.android.com/training/articles/perf-jni) technique we used in the earlier [Android Hide Secrets](https://github.com/approov/android-hide-secrets/blob/ed0217325d42be480a15c003fae9f201ee0f3f88/app/src/main/java/com/criticalblue/androidhidesecrets/MainActivity.java#L37-L41) app to [hide the API key](https://github.com/approov/android-hide-secrets/blob/ed0217325d42be480a15c003fae9f201ee0f3f88/app/src/main/cpp/api_key.h.example).

So, in this article you will learn how to setup and run a MitM attack to intercept https traffic in a mobile device under your control, so that you can steal the API key. Finally, you will see at a high level how MitM attacks can be mitigated.

## **Setup for the MitM Attack**

In order to perform the MitM attack you need to have mitmproxy installed, have both the computer and the mobile device on the same wifi network, set up the proxy on the mobile device, have a free API key for the third party service that provides the currency rates, and then build and install the Currency Converter demo app on the mobile device.

### **Clone the Currency Converter Demo**

From Github you need to git clone the [Currency Converter Demo](https://github.com/approov/currency-converter-demo/tree/0.1.1) app:

```
git clone --branch 0.1.1 https://github.com/approov/currency-converter-demo.git && cd currency-converter-demo
```

### **Mitmproxy Install**

To perform the MitM attack you should use the open source tool [mitmproxy](https://mitmproxy.org/) which is an interactive https proxy that can be used from the command line or from a web interface, although if you are already using other tools, such as the Charles or Fiddler Proxy, feel free to skip the install and setup for the mitmproxy.

If you don’t yet have the mitmproxy tool installed you should follow [the official documentation](https://docs.mitmproxy.org/stable/overview-installation/) to install it on your platform, but if you have Docker on your system then you can use their official image.

##### Using Docker

If you decided to use docker and don't want to type long commands, you can use the `./stack` bash script in the root of the demo:

```
$ ./stack install  
4.0.4: Pulling from mitmproxy/mitmproxy  
911c6d0c7995: Pull complete   
6c177ecba9eb: Pull complete   
4e66c1c16ddc: Pull complete   
0a3a1ba37d3c: Pull complete   
Digest: sha256:2964508c2091f0425d46971cfc11741e67f462cbd6ed6773c465a671d060fb6f  
Status: Downloaded newer image for mitmproxy/mitmproxy:4.0.4
```

Now it’s time for a smoke test to check that mitmproxy is working:

```
$ ./stack mitmweb --version  
Mitmproxy: 4.0.4  
Python:    3.6.3  
OpenSSL:   OpenSSL 1.0.2o  27 Mar 2018  
Platform:  Linux-4.15.0-50-generic-x86_64-with  
```

All mitmproxy commands in this demo will be prefixed with `./stack`, because we will run them within docker containers, but if you have mitmproxy installed in your computer just remove the prefix `./stack` when executing each command.

### **The Wifi Network**

In order to be able to perform the MitM attack you need to connect the computer and the mobile device to the same wifi network.

Next you need to know the IP address for the wifi network. In Ubuntu 18.04 you can discover from going to **Settings > Wi-Fi > Visible Networks** and click on settings for the wifi network you are connected to:

![Visible Networks](https://lh3.googleusercontent.com/6hjhbQ8PmHRbkow7bE46pKbVxJHK0Vj7PQ0sKM3JllXqOw1IcsjsxFQ4KPEQEU9corjG-eCHMCMqXglypY6_VDLlEcpp3FiHJhDGEQXYJZoju1-XoYfJHOkymX7UbrmXhgLBmS0v)

You should take note of the IP address 10.0.3.55 in order to later use it to set up the proxy in the mobile device and to access the mitmproxy web interface.


### **Starting the mitmproxy**

Now that you know the wifi IP address, it’s time to launch the mitmproxy web interface to listen to all requests made into the wifi network, on port 8080, by issuing the following command:

```
$ ./stack mitmweb --listen-host 10.0.3.35 --web-iface 10.0.3.35                                                               130 ↵  
Web server listening at http://10.0.3.35:8081/  
No web browser found. Please open a browser and point it to http://10.0.3.35:8081/  
Proxy server listening at http://10.0.3.35:8080
```

Let's do a smoke test to check if we can see the web interface for mitmproxy, by visiting in the browser http://10.0.3.55:8081:

![MitmProxy Web Interface](https://cdn2.hubspot.net/hubfs/2449407/Screenshot%20from%202019-03-29%2010-26-44.png)

Now that mitmproxy is listening in all traffic that goes through the wifi, on port 8080 (10.0.3.35:8080), it's time to set up our mobile device proxy to send all traffic through it.

The mitmproxy needs to be launched before you setup the mobile device, because when the mitmproxy web interface starts, a custom authority certificate is auto generated, and it will be later used to setup the proxy on the mobile device.

### **Proxy Setup on the Mobile Device**

In android this is usually done by selecting the wifi network, then advanced options, and set the proxy to manual mode, fill the proxy hostname field with the wifi IP, in this case 10.0.3.35, and the proxy port with 8080, the one where mitmproxy is listening. Depending on your Android version it will look something like this:

![mobile-proxy-setup-1](https://cdn2.hubspot.net/hubfs/2449407/mobile-proxy-setup-1.png)

In order for mitmproxy to be able to intercept all the https traffic we need to add to the mobile device a custom certificate authority. This was auto generated by mitmproxy when we started the proxy, thus is unique to this mitmproxy installation. To do so, please open the browser in the mobile device and go to [http://mitm.it](http://mitm.it) where you should see this page:

![MimtProxy page](https://lh6.googleusercontent.com/0uA_i_2OULJ2X_hmLQ6hcZQo8AFNoQyzNv1R-AZm2DY75_hPbWAz0DT-dmW1vO5gouJSFtEXT04B_jel_qrufa3LPVdB0LoMgicmv-3OG033QDkj-i0iw78tBsyIFliSnGOL8xzl)

> NOTE: If you see any other screen that means the traffic from your mobile device is not being intercepted, thus you need to review the previous steps and ensure that you followed them correctly.

Time to click on the Android symbol and install the custom authority certificate for mitmproxy by following the on screen instructions. This will require the mobile device to have authentication enabled when unlocking the screen. If you do not have it done already, you will be prompted to set it up.

### **Install the Mobile App**

For this step you first need to get an API key for the third party service that will provide the currency rates used in the mobile app in order to perform the currency conversion. Just visit [this page](https://free.currencyconverterapi.com/free-api-key) to get your free API key.

However, before you can build the app, you need to copy/paste the free API key into the file **app/src/main/cpp/api_key.h.** This file does not exist yet in the project, and is not tracked by git, but you can use [**app/src/main/cpp/api_key.h.example**](https://github.com/approov/currency-converter-demo/tree/0.1.1/mobile-app/android/app/src/main/cpp/api_key.h.example) as a template:

```C
// app/src/main/cpp/api_key.h  

#ifndef CURRENCY_CONVERTER_DEMO_API_KEY_H  
#define CURRENCY_CONVERTER_DEMO_API_KEY_H  "place-the-api-key-here"  

#endif</pre>
```

If the mobile device you are installing this app on is using Android Nougat or later OS version, then you need to uncomment [this line](https://github.com/approov/currency-converter-demo/blob/20f8c6ed5a63edd48e7e39ff757604cbbd10201e/mobile-app/android/app/src/main/AndroidManifest.xml#L14) in the code.

So this code:

```xml
android:theme="@style/AppTheme">  
<!--android:networkSecurityConfig="@xml/network_security_config">-->
```

Must become:

```xml
android:theme="@style/AppTheme"  
android:networkSecurityConfig="@xml/network_security_config">
```

This will allow the mobile app to trust the mitmproxy certificate we have already installed because, since API level 24, the Android operating system by default doesn't allow the mobile apps to trust in user supplied certificates, unless explicitly told to do so, and that is what we are doing by providing [this network security config file](https://github.com/approov/currency-converter-demo/blob/20f8c6ed5a63edd48e7e39ff757604cbbd10201e/mobile-app/android/app/src/main/res/xml/network_security_config.xml).

Now you can build the app and install it via usb. How to do this is out of scope for this article, but you can refer to the [official docs](https://developer.android.com/training/basics/firstapp/running-app). After you have installed the Currency Converter demo app you should be presented with this screen:

![App screen](https://lh4.googleusercontent.com/Yhar8UH7bYDCVnPPPZHPXgzeIpKVSYDAI3ekQLGdvieLSqRjppsXnGC7gsKhvboi4K02Wk60RQKn0c_tEVgMgUA9WNxal1ir0bFNikDNsnyUnkjl3jbum4CFsUiXcWAXiQHPNM5i)

This was the final step in the setup for the MitM attack, so now we just need to play with the app and watch the mitmproxy web interface for the intercepted requests.



## **The MitM Attack in Action**

Assuming that you still have the mitmproxy running from the setup process, just open the browser on [http://your-wifi-ip-here:8081](http://your-wifi-ip-here:8081) and start playing with the android app in order to see the API requests being used to get the currency rates from a third party API being intercepted.

So let's try to convert £1000 into euros and see if we can intercept and steal the API key when the app calls the third party service to get the currency rate for exchanging pounds for euros.

![Appr screen](https://lh4.googleusercontent.com/FmaYkT3PhPzb6r78wrAY874iO9RqRKiru5SvkshYm6csw_FXtnqjJoTF6TR-XIH2l9c64cjHUQZmRcDjtROZF6HMgdhyOXFUlObI-BbQXkNB2YS3EUaB8ymdd3sjH9Q_-pBKH6jr)

Well I got €1,163.74 for £1000, and if I look into the mitmproxy web interface I can see that the https request to get the currency rate for the exchange was intercepted:

![intercepted-request](https://cdn2.hubspot.net/hubfs/2449407/intercepted-request.png)

Can you spot where the API key is in the intercepted https request?

Well, I bet that you quickly found the API key as a parameter in the url, but if you haven’t, then just look a bit closer:

![MitmProxy screen](https://lh5.googleusercontent.com/3t4wwtgEpEF5qht1XdgarO5BhaLkhjUx5Dn_0D4YPt_e9V7k_r8POYrHnrJ-S7kdg1rWhehhqzBBYe9ZTwphvhrJ1Fp43KT0R8eKArthH4lrJI22DsgejaDad38jdwnL-d7tki05)

Congratulations, you have been able to steal the super secret API key that the developer thought to be very well protected. So just to be clear, this is the same API key you copy/pasted into the file **app/src/main/cpp/api_key.h** and then hid in the mobile app binary through the use of the advanced JNI/NDK technique. This technique makes it difficult to reverse engineer the binary using static analysis, but as you have seen the API key can easily be extracted with a MitM attack.

An attacker using a MitM attack to steal an API key can then create huge commercial damage to a company. They can abuse the API resources in the name of the API key owner, thus increasing their usage costs, or they can exfiltrate and exploit the data exposed by the API.

### **What is the difference between https and http requests intercepted by mitmproxy?**

If you edit the mobile app code and switch the url to the third party API to use the http protocol, rebuild, install it again, and do some more currency conversions you will be able to compare the difference between http and https requests:

![MitmProxy screen](https://lh4.googleusercontent.com/a_sNaAqrFrk3iCH8vgdGYvgILBtbn-PpKYTYyevtvC6ynZ9JFlGFh6WUWaxA7RhisXI1daA1CIe6iYnVqb6KlYi_tcMohZGWz-J3BOoj5jZcMsYae9b8lz1XRfZBaNNtAhPTX5xn)

So can you spot what are the differences between intercepted requests over http and https?

If you are struggling to find any substantial differences… look a little closer:

![MitmProxy screen](https://lh6.googleusercontent.com/KRcgwfMpQ2lkJ8cakU9fwZwCASQc4mlGR7sPPSItuSI-OQ_2TC8IcGXr6wmjpBoc7hJgZCcoEht1IgEGxO5sZ8qp_D9rk9UiV4cxJGWz0EraNFdU9hXlM3EG3xo9LcQARy4sgEX9)

Although they look exactly the same, there is a difference - the green bar preceding the https requests. So if until now you thought that https was enough to protect your API key, you may now see that during a MitM attack it does not offer any protection at all.

This is possible because of the custom certificate authority we installed on the mobile device when we visited [http://mitm.it](http://mitm.it). Tricking a user into installing this type of custom certificate authority on a device is usually done with fake captive portals to get free wifi in public places, because some users will click on anything just to have free wifi !!!

## **Mitigating MitM Attacks**

We can mitigate the MitM attack by using certificate pinning on the connection between the mobile app and the API server, and we have an excellent article on it, [Hands On Mobile API Security: Pinning Client Connections](/hands-on-mobile-api-security-pinning-client-connections). Therefore I will not go into detail here, but I want to let you know that pinning can be an operational challenge, and unfortunately it can be bypassed, but if you read [this article](/toughen-up-soft-certificate-pinning-with-approov) you will understand how to detect and prevent it from happening.

So now you may be wondering what more can be done in terms of mobile API security. I would recommend a deep dive into [this series of articles](/tag/a-series-mobile-api-security) to understand several other security techniques that can be employed to protect a mobile API.

## **Conclusion**

While we can use advanced techniques, like JNI/NDK, to hide the API key in the mobile app code, it will not impede someone from performing a MitM attack in order to steal the API key. In fact a MitM attack is easy to the point that it can even be achieved by non developers.

We have highlighted some good resources that will show you other techniques to secure mobile APIs, like certificate pinning, even though it can be challenging to implement and to maintain. We also noted that certificate pinning by itself is not enough since it can be bypassed, thus other techniques need to be employed to guarantee that no one can steal your API key, and, if you have completed the deep dive I recommended, you will know by now that in the context of a mobile API, the API key can be protected from being stolen through a MitM attack. So if you have not already done it, please read the articles I linked to in the section about mitigating MitM attacks.

See you in my next article...