---
title: Playing with SNU Application
date: 2024-03-26T18:00:48+09:00
slug: playing-with-snu-application
description: Playing with SNU Application
---


I initially planned to explore our school's official mobile app. My goal was to make a Telegram Bot for the Mobile ID QR code, so I needed to understand how the app retrieves QR information. I disassembled the app using JADX and started analyzing the functions, but then I got lazy...

The spring semester began, and a few of my classes started using an electronic attendance system, also known as beacon-based attendance. Many schools use beacon-based digital attendance systems, which made me think that it might be relatively easy to work with. So, I reopened the application and decided to dig deep into its logics. My aim was to fully understand the logic of the attendance system to the point where I could mark myself present without using the official app.

### 1. APK JADX analyzing

I decompiled apk using JADX and tried to rename every function and classes. Since It was first time looking at these Android application logics, it took a long time. By looking at internal logic, I discovered that there wasn't any authentication going on, it just read attributes of beacon (which is very likely to be fixed value), and send it to server. So we didnt need to think about any kind of token-based authentication going on inside iBeacon which I could never analyze or manipulate. Also iBeacon reading thing in Android. We need to look at what it sends to server.

### 2. App MITM patch, repackaging.

So now we have to analyze its packets to potentially replay it by ourself.
Using `apk-mitm` and `uber-apk-signer`, I modified app for use with mitmproxy.
Since app has its own signature verifing on startup and "secure actions", we have to bypass that verification.

1. Startup

It retrieves App signature from `https://mob.snu.ac.kr/api/versionCheck.action` on splash screen. Using mitmproxy script, we can easily modify server's response.

```python
def response(flow: http.HTTPFlow) -> None:
    url = flow.request.pretty_url
    if url == "https://mob.snu.ac.kr/api/versionCheck.action":
        data = json.loads(flow.response.get_text())
        data["VERSION"]["SIGN_KEY"] = "MYSIGNATURE"
        flow.response.text = json.dumps(data)
```

2. JNI Signature checking.

It uses JNI `libEncryptionKeyStore.so` for additional `checkRoot`. Name is checkRoot, but what it does is just verifies app's signature with some simple loops and comparisons. When it doesnt match, it branches into `std::terminate`.

```asm
00007d48          int64_t x0_8 = data_3d158
00007d50          if ((*(x0_8 - 8) & 0x80000000) == 0)
00007d58              sub_ba58(&data_3d158)
00007d5c              x0_8 = data_3d158
00007d68          *x0_8 = 0x35
...
```

Since original signature is hard-coded into binary, we can either modify binary as our signature or just bypass checking function.
Replacing every single bytes manually would be a nightmare. So I had to do it automatically. To track down where every bytes are assigned, I just wrote my own machine codes parser and keeped track of important registers. I matched binary expressions into opcode and tracked down when and where it stored bytes into string register, and changed it into my signature.
This is of course very very inefficient and very limited way, but it worked well for me this time. Its just one time script.

More simply we can just bypass `b std::terminate` to `ret`. It doesnt return anything, so just returning should be fine.

```armasm
0000830c  43801fb8   stur    w3, [x2, #-0x8]
00008310  f8ffff17   b       0x82f0
00008314  04030094   bl      std::terminate   -->   ret
{ Does not return }
```


### 2. JNI Sniffing

After bypassing signature check, we can now test various packets sent from application. But as expected, it used additional encryption on every data it sends.
I thought whole encryption will be done on JNI itself, but suprisingly it used it only for retriving secret key.

```java
package com.ubivelox.security;
public class EncryptionKeyStore {
    static {
        System.loadLibrary("EncryptionKeyStore");
    }
    public String secretKeyEx() {
        return getSecretKeyEx();
    }
    public native void checkRooting(String str);
    public native String getBleInfo();
    public native String getSecretKeyEx();
}
```

So important things were all in this JNI. App sends request as `{header: encryped-header, body: body}` and this encryption key is retrieved with `getSecretKeyEx()` as JNI. So I need to somehow extract key from this function.

```c
00007124      int64_t var_38 = time(nullptr)
00007130      int32_t x1 = *(localtime(&var_38) + 0x10)
00007134      int32_t x1_1 = x1 + 1
00007138      int32_t x0_9
00007138      if (x1 + 1 s< 0)
00007388          x0_9 = 0
00007150      else
00007150          int32_t x0_7 = ((muls.dp.q(x1_1, 0x2aaaaaab) u>> 0x20).d s>> 1) - (x1_1 s>> 0x1f)
0000715c          x0_9 = x1_1 - ((x0_7 << 4) - (x0_7 << 2))
```

First, it calculates some kind of index from current time. I didnt know what was going on here exactly, but I learned that multipling `0x2aaaaaab` thing is to divide number by 3. Well, the calculation wasnt 'understandable' for me, so I just moved this into C code and observed the output. Surprisingly, it outputted only fixed value.

```armasm
00007180  1f040071   cmp     w0, #0x1
00007184  60100054   b.eq    0x7390
00007188  1f080071   cmp     w0, #0x2
0000718c  e0150054   b.eq    0x7448
...
000071d0  1f2c0071   cmp     w0, #0xb
000071d4  210c0054   b.ne    0x7358
```

They wrote code to do some kind of key rotating with that index above, and that index was fixed, so it was just all useless obsfucation. (but it is more likely that I didnt looked it carefully and it changes daily or randomly)

+) And some days later it's April. Output index has changed . So it was like rotating every three months?

```asm
00007204  06078052   mov     w6, #0x38
00007208  29078052   mov     w9, #0x39
0000720c  88068052   mov     w8, #0x34
00007210  65088052   mov     w5, #0x43
00007214  acd30039   strb    w12, [x29, #0x34 {var_30+0x4}]  {0x46}
00007218  a3f30039   strb    w3, [x29, #0x3c {var_28+0x4}]  {0x44}
0000721c  2c068052   mov     w12, #0x31
00007220  ab070139   strb    w11, [x29, #0x41 {var_20+0x1}]
00007224  ab068052   mov     w11, #0x35
```

Each subroutine builds key into var_30, var_20, ... , so I just need to write down these keys right?

Well it wasnt. After each subroutine it all branched into this part.

```asm
00007358  820240f9   ldr     x2, [x20]
0000735c  e00314aa   mov     x0, x20
00007360  429c42f9   ldr     x2, [x2, #0x538]
00007364  40003fd6   blr     x2
00007368  73ce47f9   ldr     x19, [x19, #0xf98]  {__stack_chk_guard}
0000736c  a22f40f9   ldr     x2, [x29, #0x58 {var_8}]
00007370  610240f9   ldr     x1, [x19]
00007374  5f0001eb   cmp     x2, x1
00007378  413b0054   b.ne    0x7ae0
0000737c  f35341a9   ldp     x19, x20, [sp, #0x10] {__saved_x19} {__saved_x20}
00007380  fd7bc6a8   ldp     x29, x30, [sp], #0x60 {__saved_x29} {__saved_x30}
00007384  c0035fd6   ret    
00007388  00008052   mov     w0, #0
0000738c  75ffff17   b       0x7160
```

It loads x20 into x2 and branches into value of `x2+0x538`. And x20 was saved value of `int64_t* arg1`, which is JNIenv passed from Java.
And of course I spend a lot of hard time figuring out what this function does. I just couldnt see where that function was, and this was almost first time analyzing JNI. I didnt even knew any Android programming.
And I just gave up at this point. I even tried to read all defined functions, but I couldnt find anything useful.


I had to find other way. And I rememdered about library sniffing. You know, we can sniff and log return values using mocked JNI, which just forwards function calls. We can even bypass `checkRoot` by just not actually calling it.

So I just did that. I wrote my own shared object, and named original one ~.orig.so. Now what I should do is to call original fcuntions inside my own shared object. Its like LD_PRELOAD. What a easy task it was. Now I can just get encryption key using `adb logcat`.

```cpp
#include "com_ubivelox_security_EncryptionKeyStore.h"
#include <dlfcn.h>
#include <stdio.h>
#include <android/log.h>

void* libhandle = dlopen("libEncryptionKeyStore-orig.so", RTLD_LAZY);

typedef void (*checkRooting_ft)(JNIEnv*, jobject, jstring);
typedef jstring (*getBleInfo_ft)(JNIEnv*, jobject);
typedef jstring (*getSecretKeyEx_ft)(JNIEnv*, jobject);
checkRooting_ft checkRooting_ptr;
getBleInfo_ft getBleInfo_ptr;
getSecretKeyEx_ft getSecretKeyEx_ptr;

JNIEXPORT void JNICALL checkRooting(JNIEnv* arg1, jobject arg2, jstring arg3) {
    if (!checkRooting_ptr)
        checkRooting_ptr = (checkRooting_ft)dlsym(libhandle, "Java_com_ubivelox_security_EncryptionKeyStore_checkRooting");
    if (checkRooting_ptr)
//      return checkRooting_ptr(arg1, arg2, arg3);
        return;
}

JNIEXPORT jstring JNICALL getBleInfo(JNIEnv* env, jobject obj) {
    if (!getBleInfo_ptr)
        getBleInfo_ptr = (getBleInfo_ft)dlsym(libhandle, "Java_com_ubivelox_security_EncryptionKeyStore_getBleInfo");
    if (getBleInfo_ptr) {
        jstring ret = getBleInfo_ptr(env, obj);

        const char *cStr = env->GetStringUTFChars(ret, NULL);
        if (cStr == NULL) {
            return NULL;
        }
        char log[2048] = {0};
        snprintf(log, sizeof(log), "getBleInfo: %s", cStr);
        __android_log_write(ANDROID_LOG_ERROR, "libEncryptionKeyStore", log);
        env->ReleaseStringUTFChars(ret, cStr);
        return ret;
    }
    return NULL;
}

JNIEXPORT jstring JNICALL getSecretKeyEx(JNIEnv* env, jobject obj) {
    if (!getSecretKeyEx_ptr)
        getSecretKeyEx_ptr = (getSecretKeyEx_ft)dlsym(libhandle, "Java_com_ubivelox_security_EncryptionKeyStore_getSecretKeyEx");
    if (getSecretKeyEx_ptr) {
        jstring ret = getSecretKeyEx_ptr(env, obj);

        const char *cStr = env->GetStringUTFChars(ret, NULL);
        if (cStr == NULL) {
            return NULL;
        }
        char log[2048] = {0};
        snprintf(log, sizeof(log), "getSecretKeyEx: %s, %p", cStr, *(*env + 0x538));
        __android_log_write(ANDROID_LOG_ERROR, "libEncryptionKeyStore", log);
        env->ReleaseStringUTFChars(ret, cStr);
        return ret;
    }
    return NULL;
}

JNIEXPORT void JNICALL Java_com_ubivelox_security_EncryptionKeyStore_checkRooting (JNIEnv* arg1, jobject arg2, jstring arg3)
{
    return checkRooting(arg1, arg2, arg3);
}
JNIEXPORT jstring JNICALL Java_com_ubivelox_security_EncryptionKeyStore_getBleInfo (JNIEnv* arg1, jobject arg2) 
{
    return getBleInfo(arg1, arg2);
}

JNIEXPORT jstring JNICALL Java_com_ubivelox_security_EncryptionKeyStore_getSecretKeyEx (JNIEnv* arg1, jobject arg2)
{
    return getSecretKeyEx(arg1, arg2);
}
```

> ```
> 03-26 11:04:03 E libEncryptionKeyStore: RETURN: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
> ```

So, I now extracted Encryption Key, and I have all packets containing all informations. Now its time to decrypt messages and build our own requests!

Messages were encrypted in AES-CBC mode with IV of just 0s, padded with PKCS#5. 

I modified mitm script to automatically decrypt messages and log them.

```python
elif "https://scard1.snu.ac.kr/" in url:
        req = json.loads(flow.request.get_text())
        data = json.loads(flow.response.get_text())
        with open(LOG, "a") as f:
            f.write(flow.request.pretty_url))
            f.write(decrypt(req["header"]).decode())
            f.write(req["body"])
            f.write(decrypt(data["header"]).decode())
            f.write(data["body"])
```

Everything was clear, but there was `enc` field inside "header" of body (not HTTP header) which was just SHA1 of body content for verifing maybe.
I have all of informations, now I can just send requests to server, retrieve class and lecture infos and do attendance.

### 5

As in case of Attendace Checking, It uses BLE Beacon (or iBeacon). 

At first I thought there should be some kind of randomization and special ble service, but it just sends existing and constant beacon data (UUID, MacAddress, ...) to server. 

It seemed easy to manipulate, and by knowing this, I can just build my BLE server with matching UUID and such properties, and use unmodified app to do attendance as usual. Modifing and sending custom built raw packets could be illegal in some circumstances, so this way is more safe and undetectable.

Attendance packets involves encryption twice. Once in other encrypts header, and twice it encrypts BLE beacon data in header. I dont know why they encrypt twice, but there should be some context in it.

Using all of informations, now we can save BLE data and send our own attendance, and potentially take an attendance without attending!

*But one thing, it sends data without any cookies or authentication about student data. So no need any account information but student id.  This made me little bit concerned and I decided to keep analyzing app.*

### 6. Mobile ID, QR code

So going back to original task, retrieving Mobile QR Code with my own.

Since I anaylzed deep about app's behaviour now, I just needed to read through source one more time and it was it. I did exactly same thing but with mobile id, and it was very simmilar except it used raw hex digested form instead of base64 encoded form.

One thing very surprising was that mobile id also didn't used authentication. Mobile ID is used on various identifications simmilar to ID card. This level of personal information is retrieved without any authenticaion but only student id which is very opened. It seems like problem..

Anyways we also can retrieve Mobile ID QR code and Profile Picture (ID Picture registered) with our own.
I expected I will do authentication with at least ID and Password, so no authentication was a bit of surprise.

<br>

### Afterthoughts.

It seemed very complex at the beginning but solution was pretty easy and straightforward. I bet anyone could do it if one puts some times in it, I wonder why this wasnt the case. Maybe because it's actually illegal to do, and because of that it was less appealing to do it? I dont know..

Also, hardcoding encryption keys or verification tokens inside the app itself seems dangerous, as I could extract keys from decompilation. And any app has potential to be preloaded and sniffed, especially JNI like this case, so using JNI to retrive raw keys is not good I think. Its more better to just encrypt inside JNI so that key itself can be contained in itself, right?

I dont think there is a way to contain key in blackbox even for end user. User has all access to app so it is hard to hide key from them maybe. I dont have deep knowledge in this area.. Even TPM is vulnerable to hardware key sniffing, so using hardware blackboxes are also not that sufficient unless it is really really blackbox. Maybe ZKP can solve this problem?

`mitmproxy` done most important job in this case. Nowadays apps uses certificate pinning, but it was also useless with repackaging... So any problems is all sign verification and I think there is no way to perfectly do it.

Signature verifing is hard. Using Network is dangerous, and using internal logic can be also bypassed. I think only way to prevent this is in operating system, like in iOS it's much more hard to do this kind of job. 

Also obviously they need to add some kind of authentication. There was SSO token field on their API, but it wasnt used anyway. A LOT of things were done without authentication, at least I can see on my logs. They should fix this. Since its institute, they dont care at all,, so its possible that they all know but ignored.
