Skip to content

Conversation

JerryTasi
Copy link
Contributor

@JerryTasi JerryTasi commented Aug 11, 2025

Detect CWE-502 in Android Application

This scenario seeks to find Deserialization of Untrusted Data in the APK file.

CWE-502: Deserialization of Untrusted Data

We analyze the definition of CWE-502 and identify its characteristics.

See CWE-502 for more details.

image

Code of CWE-502 in pivaa.apk

We use the pivaa.apk sample to explain the vulnerability code of CWE-502.

image

CWE-502 Detection Process Using Quark Script API

image

Let’s use the above APIs to show how the Quark script finds this vulnerability.

To begin with, we created a detection rule named deserializeData.json to identify behaviors that deserialize data.

Next, we retrieve the methods that interact with the deserialization API. Following this, we check if the methods match any APIs for verifying data.

If NO, it could imply that the APK deserializes the untrusted data, potentially leading to a CWE-502 vulnerability.

Quark Script CWE-502.py

image

from quark.script import runQuarkAnalysis, Rule

SAMPLE_PATH = "pivaa.apk"
RULE_PATH = "deserializeData.json"

ruleInstance = Rule(RULE_PATH)

result = runQuarkAnalysis(SAMPLE_PATH, ruleInstance)

verificationApis = [
    ["Ljava/io/File;", "exists", "()Z"],
    ["Landroid/content/Context;", "getFilesDir", "()Ljava/io/File;"],
    ["Landroid/content/Context;", "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;"],
    ["Landroid/os/Environment;", "getExternalStorageDirectory", "()Ljava/io/File;"],
]

for dataDeserialization in result.behaviorOccurList:
    apis = dataDeserialization.getMethodsInArgs()
    caller = dataDeserialization.methodCaller
    if not any(api in apis for api in verificationApis):
        print(f"CWE-502 is detected in method, {caller.fullName}")

Quark Rule: deserializeData.json

image

{
    "crime": "Deserialize Data",
    "permission": [],
    "api": [

        {
            "class": "Ljava/io/ObjectInputStream;",
            "method": "<init>",
            "descriptor": "(Ljava/io/InputStream;)V"
        },
        {
            "class": "Ljava/io/ObjectInputStream;",
            "method": "readObject",
            "descriptor": "()Ljava/lang/Object;"
        }

    ],
    "score": 1,
    "label": []
}

Quark Script Result

$ python CWE-502.py
CWE-502 is detected in method, Lcom/htbridge/pivaa/handlers/ObjectSerialization; loadObject ()V

Detect CWE-297 in Android Application

This scenario seeks to find Improper Validation of Certificate with Host Mismatch.

CWE-297: Improper Validation of Certificate with Host Mismatch

We analyze the definition of CWE-297 and identify its characteristics.

See CWE-297 for more details.

image

Code of CWE-297 in pivaa.apk

We use the pivaa.apk sample to explain the vulnerability code of CWE-297.

image

CWE-297 Detection Process Using Quark Script API

image

First, we use API findMethodImpls(samplePath, targetMethod) to locate the method that implements the hostname verification, which verifies the hostname of a certificate.

Next, we use API isMethodReturnAlwaysTrue(samplePath, targetMethod) to check if the method always returns true.

If the answer is YES, the method does not check the certificate of the host properly, which may cause CWE-297 vulnerability.

Quark Script CWE-297.py

image

from quark.script import findMethodImpls, isMethodReturnAlwaysTrue

SAMPLE_PATH = "pivaa.apk"

ABSTRACT_METHOD = [
    "Ljavax/net/ssl/HostnameVerifier;",
    "verify",
    "(Ljava/lang/String; Ljavax/net/ssl/SSLSession;)Z"
]

for hostVerification in findMethodImpls(SAMPLE_PATH, ABSTRACT_METHOD):
    methodImpls = [
        hostVerification.className,
        hostVerification.methodName,
        hostVerification.descriptor
    ]
    if isMethodReturnAlwaysTrue(SAMPLE_PATH, methodImpls):
        print(f"CWE-297 is detected in method, {hostVerification.fullName}")

Quark Script Result

$ python CWE-297.py
CWE-297 is detected in method, Lcom/htbridge/pivaa/handlers/API$1; verify (Ljava/lang/String; Ljavax/net/ssl/SSLSession;)Z

Detect CWE-1204 in Android Application

This scenario seeks to find Generation of Weak Initialization Vector (IV).

CWE-1204: Generation of Weak Initialization Vector (IV)

We analyze the definition of CWE-1204 and identify its characteristics.

See CWE-1204 for more details.

image

Code of CWE-1204 in InsecureBankv2.apk

We use the InsecureBankv2.apk sample to explain the vulnerability code of CWE-1204.

image

CWE-1204 Detection Process Using Quark Script API

image

Let’s use the above APIs to show how the Quark script finds this vulnerability.

First, we created a detection rule named initializeCipherWithIV.json to identify behaviors that initialize a cipher object with IV.

Then, we use API behaviorInstance.isArgFromMethod(targetMethod) to check if any random API is applied on the IV used in the cipher object. If NO, it could imply that the APK uses a weak IV, potentially leading to a CWE-1204 vulnerability.

Quark Scipt: CWE-1204.py

image

from quark.script import runQuarkAnalysis, Rule

SAMPLE_PATH = "InsecureBankv2.apk"
RULE_PATH = "initializeCipherWithIV.json"

randomAPIs = [
    ["Ljava/security/SecureRandom", "next", "(I)I"],
    ["Ljava/security/SecureRandom", "nextBytes", "([B)V"],
]

ruleInstance = Rule(RULE_PATH)
quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance)

for initCipherWithIV in quarkResult.behaviorOccurList:
    methodcaller = initCipherWithIV.methodCaller

    if not any(
        initCipherWithIV.isArgFromMethod(api) for api in randomAPIs
    ):
        print(f"CWE-1204 is detected in method, {methodcaller.fullName}")

Quark Rule: initializeCipherWithIV.json

image

{
    "crime": "Initialize a cipher object with IV",
    "permission": [],
    "api": [
        {
            "class": "Ljavax/crypto/spec/IvParameterSpec;",
            "method": "<init>",
            "descriptor": "([B)V"
        },
        {
            "class": "Ljavax/crypto/Cipher;",
            "method": "init",
            "descriptor": "(ILjava/security/Key;Ljava/security/spec/AlgorithmParameterSpec;)V"
        }
    ],
    "score": 1,
    "label": []
}

Quark Script Result

$ python CWE-1204.py
CWE-1204 is detected in method, Lcom/android/insecurebankv2/CryptoClass; aes256encrypt ([B [B [B)[B
CWE-1204 is detected in method, Lcom/android/insecurebankv2/CryptoClass; aes256decrypt ([B [B [B)[B
CWE-1204 is detected in method, Lcom/google/android/gms/internal/zzar; zzc ([B Ljava/lang/String;)[B

Detect CWE-24 in Android Application

This scenario aims to demonstrate the detection of the Relative Path Traversal vulnerability.

CWE-24: Path Traversal: '../filedir'

We analyze the definition of CWE-24 and identify its characteristics.

See CWE-24 for more details.

image

Code of CWE-24 in ovaa.apk

We use the ovaa.apk sample to explain the vulnerability code of CWE-24.

image

CWE-24 Detection Process Using Quark Script API

image

Let’s use the above APIs to show how the Quark script finds this vulnerability.

To begin with, we create a detection rule named accessFileInExternalDir.json to identify behavior that accesses a file in an external directory.

Next, we use methodInstance.getArguments() to retrieve the file path argument and check whether it belongs to the APK. If it does not belong to the APK, the argument is likely from external input.

Finally, we use the Quark Script API quarkResultInstance.findMethodInCaller(callerMethod, targetMethod) to search for any APIs in the caller method that are used to match strings, and getParamValues(none) to retrieve the parameters.

If no API is found or "../" is not in parameters, that implies the APK does not neutralize the special element ../ within the argument, possibly resulting in CWE-24 vulnerability.

Quark Script: CWE-24.py

image

from quark.script import runQuarkAnalysis, Rule

SAMPLE_PATH = "ovaa.apk"
RULE_PATH = "accessFileInExternalDir.json"


STRING_MATCHING_API = [
    ["Ljava/lang/String;", "contains", "(Ljava/lang/CharSequence)Z"],
    ["Ljava/lang/String;", "indexOf", "(I)I"],
    ["Ljava/lang/String;", "indexOf", "(Ljava/lang/String;)I"],
    ["Ljava/lang/String;", "matches", "(Ljava/lang/String;)Z"],
    [
        "Ljava/lang/String;",
        "replaceAll",
        "(Ljava/lang/String; Ljava/lang/String;)Ljava/lang/String;",
    ],
]

ruleInstance = Rule(RULE_PATH)
quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance)

for accessExternalDir in quarkResult.behaviorOccurList:

    filePath = accessExternalDir.secondAPI.getArguments()[2]

    if quarkResult.isHardcoded(filePath):
        continue

    caller = accessExternalDir.methodCaller
    strMatchingAPIs = [
        api
        for api in STRING_MATCHING_API
        if quarkResult.findMethodInCaller(caller, api)
    ]

    if not strMatchingAPIs or "../" not in accessExternalDir.getParamValues():
        print(f"CWE-24 is detected in method, {caller.fullName}")

Quark Rule: accessFileInExternalDir.json

image

{
    "crime": "Access a file in an external directory",
    "permission": [],
    "api": [
        {
            "class": "Landroid/os/Environment;",
            "method": "getExternalStorageDirectory",
            "descriptor": "()Ljava/io/File;"
        },
        {
            "class": "Ljava/io/File;",
            "method": "<init>",
            "descriptor": "(Ljava/io/File;Ljava/lang/String;)V"
        }
    ],
    "score": 1,
    "label": []
}

Quark Script Result

$ python3 CWE-24.py
CWE-24 is detected in method, Loversecured/ovaa/providers/TheftOverwriteProvider; openFile (Landroid/net/Uri; Ljava/lang/String;)Landroid/os/ParcelFileDescriptor;

@zinwang zinwang self-requested a review August 14, 2025 07:11
Copy link
Collaborator

@zinwang zinwang left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@zinwang
Copy link
Collaborator

zinwang commented Aug 14, 2025

Refer to #64

@zinwang zinwang merged commit f6dc423 into ev-flow:main Aug 14, 2025
1 check passed
@JerryTasi JerryTasi deleted the JerryTasi-CWE-502-1204-24 branch August 21, 2025 05:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants