Your App, your public API

Thu 16 February 2017 by David Hontecillas

If you have an App in the market, you already have a public API.

And getting access to that API is much easier than you might think. I am not a security expert, and I have never done any kind of reverse engineering.


I had one of those weekends where I wanted to gather some information from a webpage for a short personal project, and I checked if the web page provided some kind of API. It actually did, but, you had to request access filling a form, that someone would review, and then provide access to the API.

I did not want to wait, so it was a good excuse to try to extract the API from their app.

About APIs for mobile devices

Mobile API are exposed to everyone. With more or less trouble, but your API contract can be extracted.

You can not easily deprecate the API : Once you have released an App you can not deprecate that API from one day to the next. The point is that, releasing a new version of the App does not mean that your users will update it soon (some of them won't update it at all).

Your mobile app is a frontend, that is easily "hackable". Do not expect your mobile devs to fix API deficiencies.

It could be your presentation card . Are you looking to hire developers? candidates can know a lot about your code by looking at your APIs.

Example: VIBBO

Vibbo is a marketplace, where people can sell and buy used items. It is like LetGo or Wallapop, with the only difference that they are not using HTTPS for their main webpage (ehem! :P).

I did not choose this app for any particular reason: I selected a random downloaded app from my phone.

I used the Android App (is easier to extract the app when we need to decompile it). The same process could be done on iOS, but with different tools. Look at the references at the end of the post. (Hint: if the man in the middle is not enough you will need a jailbroken device).

I did not extract all API calls, I only wanted to show how it can be done.

Set up the MITM

First of all I connected the phone to the same network than my laptop, and looked for a tool to help me do the Man-in-the-middle.

There are several tools to inspect traffic, but I decided to use MITMProxy, mainly because:

  • It provides a very easy way to install self-signed certificate. (You run the proxy in interactive mode, configure your device to use that proxy, visit, and follow the instructions).
  • It has an "interactive" mode (mitmproxy) where you can modify requests on the fly, and a "dump" mode (mitmdump) to save requests flows to a file so you can later and reproduce the calls as many times as you want.
  • An easy way to Filter the requests. (Take into account that once you set the proxy all the requests from the device will use that proxy configuration).
  • It is scriptable with Python (actually all the tool is written in python)

It has a lot of options, I recommend you to read the full MITMProxy documentation.

Key bindings are pretty similar to those used in the Vi editor.

Capture all traffic

I used mitmdump for the first run, so I saved the request / response flows to a file, so after that I load the flows from the file with mitmproxy to inspect everything.

mitmdump -w vibbo.mitm

If you capture before downloading the app from the Android market, you will have the .apk file inside the capture file (that can be useful later, to dump, extract and decompile it).

Once we finished some navigation, I closed the app so I could start working with the file using mitmproxy (the interactive mitm tool):

mitmproxy -nr vibbo.mitm

(the n flag is to not run the proxy, otherwise the proxy would read the captured saved file, but also would keep capturing new traffic).

Then I could have a look at the domains I was interested (because I did not have any filtering yet, I could see all traffic, not only from the App we are inspecting, but also all other apps in the device).

I chose to inspect domains containing the 'vibbo' string:

mitmproxy -nr vibbo.mitm  -f '~d .*vibbo.*' ```

At first saw I could find different kind of apis:

  • v1 via HTTP

    vibbo api call 1

  • v2 via HTTP

    vibbo api call 1

  • the users api call using HTTPS

    vibbo api call 1

When I looked at some of the requests, I found that the query parameters were encoded. The q param looked like a base64 encoded string, while the s param looked like it was hex encoded.

vibbo api q and s param

I tried to decode the q param, to find that It did not have any meaning to me:

vibbo api q and s param

Looking at the response, it was not much better:


vibbo api q and s param

So, I thought I would probably need to access the app code to see how the encoding was done.

There were other requests ( ), that did not had encoding. In this case, the response looked like a set of categories and rules to show suggestions for the app's search view.

I was missing something. I could see the /detail request, but not the actual search that I performed before (for PS4 consoles). So I loaded again the file, this time without filtering by domain name, to find that I actually missed an important request that was not being done against a vibbo domain:

and that it looked that were the actual search result

vibbo api q and s param

There were also api calls to get information about a user, following an easier RESTful scheme, with non-encoded params in the url, and also a non encoded response.


From my point of view, it looks like the encoding part of the /detail API endpoints are a measure to compensate for the use of HTTP instead of HTTPS.

But I wanted to get access to this endpoint too, so, the next step was to decompile the app to check how to decode the requests.

Decompiling the APP

First of all, I extracted the apk (the body of the request is actually a gzip, once you decompress it you get the .apk file), and decompressed it (the .apk is actually a zip file).

Then I found the .dex files, and I used the dex2jar tool te convert all .dex files into .jar files, that I fed to the Procyon decompiler.

Procyon can choke with some methods (where it spits out the Java bytecode opcodes), but it does a very good job producing Java source code.

procyon-decompiler -o .
procyon-decompiler -o .

vibbo procyon decompiler sample output

And it looked that the source code had been obfuscated probably with proguard.

So, I did a simple grep to search for the api.vibbo and /detail strings, so I could find spots to start diving into the code. And I found a couple of definitions:

Constants.d = ""
Constants.H = "/api/detail"

After looking around a little bit for the constants, and not finding anything in the code that could easily hint me how to encode / decoded the fields, I decided to grep for Base64. Just before the code that performs the base 64 encoding I should find the encryption part for the query param and the response body.

And finally found two interesting classes:

  • com.anuntis.segundamano.api.ApiHandler : This class gives us information about how the s param is baked: by making an md5 over the q param before the q param is cyphered:
public static InputStream a(String s) {
    final InputStream inputStream = null;
    try {
        final Encryption encryption = new Encryption();
        final String encryptAsBase64 = encryption.encryptAsBase64(s);
        s = encryption.md5(s);
        s = String.format(Constants.h, URLEncoder.encode(encryptAsBase64, "ISO-8859-15"), s);
        final Response execute = new OkHttpClient().newCall(new Request$Builder().url(s).get().addHeader("charset", "iso-8859-15").addHeader("User-Agent", "android").build()).execute();
        InputStream byteStream = inputStream;
        if (execute != null) {
            byteStream = execute.body().byteStream();
        return byteStream;
    catch (Exception ex) {
        return null;
  • com.anuntis.segundamano.utils.Encryption : This is where the main encryption / decription algorithm is performed.


The encryption class required some patience, since the decompiler failed to transform byte code into java code.

    private static String getPass() {
        return "4425363b0c9ecd76a4fee7680e41e3285ef507e18521a916ea6bd9f589df89ef2c2fda41547bd32543b38e82bcbc74da";

    public String decrypt(final String p0) {
        // This method could not be decompiled.
        // Original Bytecode:
        //     0: aload_1
        //     1: invokevirtual   java/lang/String.length:()I
        //     4: bipush          16
        //     6: irem
        //     7: ifne            54
        //    10: ldc             "AES/CBC/NoPadding"
        //    12: invokestatic    javax/crypto/Cipher.getInstance:(Ljava/lang/String;)Ljavax/crypto/Cipher;
        //    15: astore_2
        //    16: aload_1
        //    17: ldc             "ISO-8859-15"
        //    19: invokevirtual   java/lang/String.getBytes:(Ljava/lang/String;)[B
        //    22: invokestatic    com/anuntis/segundamano/utils/Base64.decode:([B)[B
        //    25: astore_3
        //    26: aload_2
        //    27: iconst_2
        //    28: getstatic       com/anuntis/segundamano/utils/Encryption.secretKey:Ljavax/crypto/SecretKey;
        //    31: getstatic       com/anuntis/segundamano/utils/Encryption.ivParameterSpec:Ljavax/crypto/spec/IvParameterSpec;
        //    34: invokevirtual   javax/crypto/Cipher.init:(ILjava/security/Key;Ljava/security/spec/AlgorithmParameterSpec;)V
        //    37: new             Ljava/lang/String;
        //    40: dup
        //    41: aload_2
        //    42: aload_3
        //    43: invokevirtual   javax/crypto/Cipher.doFinal:([B)[B
        //    46: ldc             "ISO-8859-15"
        //    48: invokespecial   java/lang/String.<init>:([BLjava/lang/String;)V
        //    51: astore_2
        //    52: aload_2
        //    53: areturn
        //    54: ldc             "AES/CBC/PKCS7Padding"
        //    56: invokestatic    javax/crypto/Cipher.getInstance:(Ljava/lang/String;)Ljavax/crypto/Cipher;
        //    59: astore_2
        //    60: goto            16
        //    63: astore_2
        //    64: aload_2
        //    65: invokevirtual   java/security/NoSuchAlgorithmException.printStackTrace:()V
        //    68: aconst_null
        //    69: astore_2
        //    70: goto            16

The byte code was actually an AES encryption algorithm. And I found that in the class there was a getPass() method, but actually that 'pass' was used to generate the the secret key and initialization vector for the AES algorithm

    public Encryption() m{
        this.passphrase = getPass();
        final byte[] hexStringToByteArray = this.hexStringToByteArray(this.passphrase);
        final byte[] array = new byte[32];
        final byte[] array2 = new byte[16];
        while (true) {
            try {
                System.arraycopy(hexStringToByteArray, 0, array, 0, 32);
                System.arraycopy(hexStringToByteArray, 32, array2, 0, 16);
                Encryption.ivParameterSpec = new IvParameterSpec(array2);
                Encryption.secretKey = new SecretKeySpec(array, "AES");
            catch (Exception ex) {

Given that I only needed to check if that was what I required to be able to use the /detail endpoint. So I coded a python script, and fed it the q param, and a response from the captured request.

# -*- encoding: utf8 -*-
# from __future__ import unicode_strings
import requests
import json
from pprint import pprint as _p
from datetime import datetime
import io
import base64
import hashlib
import random
import struct
from Crypto.Cipher import AES

class Encryption(object):
to view the algorithm I used the jvm opcodes:
    def __init__(self, key, initialization_vector=None):
        self.key = buffer(key)
        if initialization_vector:
            self.initialization_vector = buffer(initialization_vector)
            self.initialization_vector = buffer(bytearray(16))
        self.cbc_block_size = 16

    def _pkcs_7(self, message, blocksize):
        padd_byte = blocksize - (len(message) % blocksize)
        padded_message = message + struct.pack("{}B".format(padd_byte), *[padd_byte]*padd_byte)
        return padded_message

    def encrypt(self, message):
        if len(message) % self.cbc_block_size != 0:
            message = self._pkcs_7(message, self.cbc_block_size)
        aes_crypt =, AES.MODE_CBC, self.initialization_vector)
        res = aes_crypt.encrypt(message)
        return res

    def decrypt(self, message):
        aes_crypt =, AES.MODE_CBC, self.initialization_vector)
        message = aes_crypt.decrypt(buffer(message))
        return message

    def encrypt_ftcws(self, message):
        padded_message = self._pkcs_7(message, self.cbc_block_size)
        aes_crypt =, AES.MODE_CBC, self.initialization_vector)
        res = aes_crypt.encrypt(message)
        return res

    def encrypt_to_hex(self, message):
        enc_message = self.encrypt(message)
        hex_message = ''.join('{:02x}'.format(x) for x in bytearray(enc_message))
        return hex_message

    def decrypt_from_hex(self, message):
        message = bytearray.fromhex(message)
        return self.decrypt(message)

    def encrypt_to_b64(self, message):
        enc_message = self.encrypt(message)
        # b64_enc_message = base64.b64encode(enc_message)
        b64_enc_message = ''.join('{:02x}'.format(x) for x in bytearray(enc_message))
        return b64_enc_message

    def decrypt_from_b64(self, message):
        decoded_b64 = base64.b64decode(message)
        return self.decrypt(str(decoded_b64))

def vibbo_test(encoded_snippet):
    passphrase = "4425363b0c9ecd76a4fee7680e41e3285ef507e18521a916ea6bd9f589df89ef2c2fda41547bd32543b38e82bcbc74da"
    bin_passphrase = bytearray.fromhex(passphrase)
    secret_key = bin_passphrase[:32]
    initialization_vector = bin_passphrase[32:]
    enc = Encryption(key=secret_key,
    qparams = str(enc.decrypt_from_b64(encoded_snippet)).encode('ascii')
    endstr = -1
    while ord(qparams[endstr]) < 16:
        endstr -= 1
    qparams = qparams[:endstr+1]
        jparams = json.loads(qparams)
    except Exception as e:

test_b = "FxLN30qJl+zcQfcXh4EMAA=="


Aaaaand... it worked !

So at this point I could do searches, and extract details from the results without problems.

Obviouly there are a lot of API calls that I didn't use, but that could be 'extracted' too.

Improvements to the API 'extraction' process

If you plan to use the explained method, you will probably want to automate some stuff.

  • Automate decompilation Given that mitmproxy support scripts, is easy to create an script that extracts the .apk from the flows file, and automatically decompiles it.

  • Automate schema extraction: There are libraries to automate the extraction of the JSON schema, like skinfer that can be used.

Difficulting the API 'extraction'

As previously stated, the battle is mostly lost: if someone want to extract your API, will do it. However we can make it a little bit harder:

  • Using certificate pinning: But you should take into account, that If you do certificate pinning, you should provide a way to update the information of the certificate in your app (in case you have your certificate compromised, or it expires). On the other hand, the app could be decompiled, modified and then recompiled in order to tamper with the certificate check. I'm not sure what would be more time consuming, directly inspecting the decompiled code to extract API requests or doing the decompile/recompile process.

  • Obfuscate the secret key and initialization vector: We could probably try to compose / generate a complex algorithm in order to generate the secret key / initialization vector. But since we can get the code, we could run it to generate both of them.

  • Move sensitive code to a binary library. Those libraries can also be reversed, but that requires more work and knowledge than has been required for the Vibbo app. The problem is you would need to use jni, and provide binary libraries for ARM, MIPS and Intel architectures.


Other tools: