From 71b838674f18c9abe063cd86fea931663bbdc323 Mon Sep 17 00:00:00 2001 From: zinwang Date: Fri, 13 Sep 2024 14:04:55 +0800 Subject: [PATCH] Update CWE showcases Update CWE showcases --- CWE-117/CWE-117.py | 5 +- CWE-117/README.md | 42 ++++++--- CWE-20/CWE-20.py | 17 ++++ CWE-20/README.md | 83 +++++++++++++++++ CWE-20/openUrlThatUserInput.json | 18 ++++ CWE-22/CWE-22.py | 8 +- CWE-22/README.md | 64 ++++++++----- CWE-23/CWE-23.py | 14 ++- CWE-23/README.md | 92 ++++++++++++------- CWE-295/CWE-295.py | 6 +- CWE-295/README.md | 43 +++++---- CWE-312/CWE-312.py | 27 +++--- CWE-312/README.md | 70 ++++++++++---- CWE-319/README.md | 41 +++++++-- CWE-327/README.md | 41 +++++++-- CWE-328/CWE-328.py | 47 +++++----- CWE-328/README.md | 99 ++++++++++++-------- CWE-338/README.md | 24 +++-- CWE-489/CWE-489.py | 2 +- CWE-489/README.md | 36 +++++--- CWE-502/CWE-502.py | 2 +- CWE-502/README.md | 48 +++++++--- CWE-532/README.md | 27 ++++-- CWE-601/CWE-601.py | 47 +++++----- CWE-601/README.md | 93 ++++++++++--------- CWE-73/CWE-73.py | 2 +- CWE-73/README.md | 53 +++++++++-- CWE-749/CWE-749.py | 2 +- CWE-749/README.md | 45 +++++++-- CWE-78/CWE-78.py | 2 +- CWE-78/README.md | 56 ++++++++---- CWE-780/CWE-780.py | 8 +- CWE-780/README.md | 45 +++++++-- CWE-79/CWE-79.py | 23 +++-- CWE-79/README.md | 67 +++++++++----- CWE-798/CWE-798.py | 12 +-- CWE-798/README.md | 69 ++++++++------ CWE-88/CWE-88.py | 2 +- CWE-88/README.md | 54 +++++++---- CWE-89/CWE-89.py | 2 +- CWE-89/README.md | 41 +++++++-- CWE-921/CWE-921.py | 2 +- CWE-921/README.md | 43 +++++++-- CWE-925/CWE-925.py | 18 ++-- CWE-925/README.md | 78 ++++++++-------- CWE-926/README.md | 49 ++++++++-- CWE-94/CWE-94.py | 18 ++-- CWE-94/README.md | 58 ++++++++---- CWE-940/CWE-940.py | 2 +- CWE-940/README.md | 152 ++++++++++++++++--------------- 50 files changed, 1261 insertions(+), 638 deletions(-) create mode 100644 CWE-20/CWE-20.py create mode 100644 CWE-20/README.md create mode 100644 CWE-20/openUrlThatUserInput.json diff --git a/CWE-117/CWE-117.py b/CWE-117/CWE-117.py index 9b93363..a73a5a6 100644 --- a/CWE-117/CWE-117.py +++ b/CWE-117/CWE-117.py @@ -9,7 +9,7 @@ for logOutputBehavior in quarkResult.behaviorOccurList: - secondAPIParam = logOutputBehavior.getParamValues()[1] + secondAPIParam = logOutputBehavior.secondAPI.getArguments() isKeywordFound = False for keyword in KEYWORDS_FOR_NEUTRALIZATION: @@ -18,4 +18,5 @@ break if not isKeywordFound: - print(f"CWE-117 is detected in method,{secondAPIParam}") + caller = logOutputBehavior.methodCaller.fullName + print(f"CWE-117 is detected in method, {caller}") \ No newline at end of file diff --git a/CWE-117/README.md b/CWE-117/README.md index 65c885f..b036d52 100644 --- a/CWE-117/README.md +++ b/CWE-117/README.md @@ -1,17 +1,27 @@ # Detect CWE-117 in Android Application (allsafe.apk) -This scenario seeks to find **Improper Output Neutralization for Logs**. See [CWE-117](https://cwe.mitre.org/data/definitions/117.html) for more details. -Let’s use this [APK](https://github.com/t0thkr1s/allsafe) and the above APIs to show how the Quark script finds this vulnerability. -First, we design a detection rule ``writeContentToLog.json`` to spot on behavior using the method that writes contents to the log file. +This scenario seeks to find **Improper Output Neutralization for Logs**. +See [CWE-117](https://cwe.mitre.org/data/definitions/117.html) for more +details. -Then, we use ``behaviorInstance.getParamValues()`` to get all parameter values of this method. And we check if these parameters contain keywords of APIs for neutralization, such as escape, replace, format, and setFilter. +Let's use this [APK](https://github.com/t0thkr1s/allsafe) and the above +APIs to show how the Quark script finds this vulnerability. -If the answer is **YES**, that may result in secret context leakage into the log file, or the attacker may perform log forging attacks. +First, we design a detection rule `writeContentToLog.json` to spot on +behavior using the method that writes contents to the log file. + +Then, we use `methodInstance.getArguments()` to get all parameter values +of this method. And we check if these parameters contain keywords of +APIs for neutralization, such as `escape`, `replace`, `format`, and +`setFilter`. + +If the answer is **YES**, that may result in secret context leakage into +the log file, or the attacker may perform log forging attacks. ## Quark Script CWE-117.py -```python +``` python from quark.script import Rule, runQuarkAnalysis SAMPLE_PATH = "allsafe.apk" @@ -22,9 +32,9 @@ ruleInstance = Rule(RULE_PATH) quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) for logOutputBehavior in quarkResult.behaviorOccurList: - - secondAPIParam = logOutputBehavior.getParamValues()[1] - + + secondAPIParam = logOutputBehavior.secondAPI.getArguments() + isKeywordFound = False for keyword in KEYWORDS_FOR_NEUTRALIZATION: if keyword in secondAPIParam: @@ -32,11 +42,13 @@ for logOutputBehavior in quarkResult.behaviorOccurList: break if not isKeywordFound: - print(f"CWE-117 is detected in method,{secondAPIParam}") + caller = logOutputBehavior.methodCaller.fullName + print(f"CWE-117 is detected in method, {caller}") ``` ## Quark Rule: writeContentToLog.json -```json + +``` json { "crime": "Write contents to the log.", "permission": [], @@ -56,10 +68,12 @@ for logOutputBehavior in quarkResult.behaviorOccurList: "label": [] } ``` + ## Quark Script Result -- **allsafe.apk** -``` +- **allsafe.apk** + +``` TEXT $ python CWE-117.py -CWE-117 is detected in method,Ljava/lang/StringBuilder;->toString()Ljava/lang/String;(Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;(Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;(Ljava/lang/StringBuilder;->()V(Ljava/lang/StringBuilder;),User entered secret: ),Ljava/lang/Object;->toString()Ljava/lang/String;(Lcom/google/android/material/textfield/TextInputEditText;->getText()Landroid/text/Editable;()))) +CWE-117 is detected in method, Linfosecadventures/allsafe/challenges/InsecureLogging; lambda$onCreateView$0 (Lcom/google/android/material/textfield/TextInputEditText; Landroid/widget/TextView; I Landroid/view/KeyEvent;)Z ``` diff --git a/CWE-20/CWE-20.py b/CWE-20/CWE-20.py new file mode 100644 index 0000000..04c072a --- /dev/null +++ b/CWE-20/CWE-20.py @@ -0,0 +1,17 @@ +from quark.script import runQuarkAnalysis, Rule + +SAMPLE_PATH = "diva.apk" +RULE_PATH = "openUrlThatUserInput.json" + +rule = Rule(RULE_PATH) +result = runQuarkAnalysis(SAMPLE_PATH, rule) + +VALIDATE_METHODS = ["contains", "indexOf", "matches", "replaceAll"] + +for openUrl in result.behaviorOccurList: + calledMethods = openUrl.getMethodsInArgs() + + if not any( + method.methodName in VALIDATE_METHODS for method in calledMethods + ): + print(f"CWE-20 is detected in method, {openUrl.methodCaller.fullName}") \ No newline at end of file diff --git a/CWE-20/README.md b/CWE-20/README.md new file mode 100644 index 0000000..9d9e8f4 --- /dev/null +++ b/CWE-20/README.md @@ -0,0 +1,83 @@ +# Detect CWE-20 in Android Application + + +This scenario seeks to find **Improper Input Validation** in the APK +file. + +## CWE-20 Improper Input Validation + +We analyze the definition of CWE-20 and identify its characteristics. + +See [CWE-20](https://cwe.mitre.org/data/definitions/20.html) for more +details. + +![image](https://imgur.com/21CzFUq.jpg) + +## Code of CWE-20 in diva.apk + +We use the [diva.apk](https://github.com/payatu/diva-android) sample to +explain the vulnerability code of CWE-20. + +![image](https://imgur.com/kRIuEHd.jpg) + +## Quark Script CWE-20.py + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +First, we design a detection rule `openUrlThatUserInput.json`, to spot +the behavior of opening the URL that the user inputs. Then, we use API +`behaviorInstance.getMethodsInArgs()` to get a list of methods that the +URL in `loadUrl` passes through. Finally, we check if any validation +method is in the list. If No, the APK does not validate user input. That +causes CWE-20 vulnerability. + +``` python +from quark.script import runQuarkAnalysis, Rule + +SAMPLE_PATH = "diva.apk" +RULE_PATH = "openUrlThatUserInput.json" + +rule = Rule(RULE_PATH) +result = runQuarkAnalysis(SAMPLE_PATH, rule) + +VALIDATE_METHODS = ["contains", "indexOf", "matches", "replaceAll"] + +for openUrl in result.behaviorOccurList: + calledMethods = openUrl.getMethodsInArgs() + + if not any( + method.methodName in VALIDATE_METHODS for method in calledMethods + ): + print(f"CWE-20 is detected in method, {openUrl.methodCaller.fullName}") +``` + +## Quark Rule: openUrlThatUserInput.json + +``` json +{ + "crime": "Open the Url that user input", + "permission": [], + "api": [ + { + "class": "Landroid/widget/EditText;", + "method": "getText", + "descriptor": "()Landroid/text/Editable;" + }, + { + "class": "Landroid/webkit/WebView;", + "method": "loadUrl", + "descriptor": "(Ljava/lang/String;)V" + } + ], + "score": 1, + "label": [] +} +``` + +## Quark Script Result + +``` TEXT +$ python CWE-20.py +CWE-20 is detected in method, Ljakhar/aseem/diva/InputValidation2URISchemeActivity; get (Landroid/view/View;)V +``` diff --git a/CWE-20/openUrlThatUserInput.json b/CWE-20/openUrlThatUserInput.json new file mode 100644 index 0000000..8959e03 --- /dev/null +++ b/CWE-20/openUrlThatUserInput.json @@ -0,0 +1,18 @@ +{ + "crime": "Open the Url that user input", + "permission": [], + "api": [ + { + "class": "Landroid/widget/EditText;", + "method": "getText", + "descriptor": "()Landroid/text/Editable;" + }, + { + "class": "Landroid/webkit/WebView;", + "method": "loadUrl", + "descriptor": "(Ljava/lang/String;)V" + } + ], + "score": 1, + "label": [] +} diff --git a/CWE-22/CWE-22.py b/CWE-22/CWE-22.py index 7151bab..6041c84 100644 --- a/CWE-22/CWE-22.py +++ b/CWE-22/CWE-22.py @@ -16,7 +16,6 @@ quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) for accessExternalDir in quarkResult.behaviorOccurList: - filePath = accessExternalDir.secondAPI.getArguments()[2] if quarkResult.isHardcoded(filePath): @@ -24,9 +23,10 @@ caller = accessExternalDir.methodCaller strMatchingAPIs = [ - api for api in STRING_MATCHING_API if quarkResult.findMethodInCaller( - caller, api) + api + for api in STRING_MATCHING_API + if quarkResult.findMethodInCaller(caller, api) ] if not strMatchingAPIs: - print(f"CWE-22 is detected in method, {caller.fullName}") + print(f"CWE-22 is detected in method, {caller.fullName}") \ No newline at end of file diff --git a/CWE-22/README.md b/CWE-22/README.md index 77c3c7b..2ad37b5 100644 --- a/CWE-22/README.md +++ b/CWE-22/README.md @@ -1,19 +1,44 @@ -# Detect CWE-22 in Android Application (ovaa.apk and InsecureBankv2.apk ) +# Detect CWE-22 in Android Application -This scenario seeks to find **the improper limitation of a pathname to a restricted directory ('Path Traversal')**. See [CWE-22](https://cwe.mitre.org/data/definitions/22.html) for more details. +This scenario seeks to find **the improper limitation of a pathname to a +restricted directory ('Path Traversal')**. -Let’s use [ovaa.apk](https://github.com/oversecured/ovaa), [InsecureBankv2.apk](https://github.com/dineshshetty/Android-InsecureBankv2/releases), and the above APIs to show how the Quark script finds this vulnerability. +## CWE-22: Improper Limitation of a Pathname to a Restricted Directory (\'Path Traversal\') -First, we design a detection rule `accessFileInExternalDir.json` to spot behavior accessing a file in an external directory. +We analyze the definition of CWE-22 and identify its characteristics. -Next, we use API `methodInstance.getArguments()` to get the argument for the file path and use `quarkResultInstance.isHardcoded(argument)` to check if the argument is hardcoded into the APK. If **No**, the argument is from external input. +See [CWE-22](https://cwe.mitre.org/data/definitions/22.html) for more +details. -Finally, we use Quark API `quarkResultInstance.findMethodInCaller(callerMethod, targetMethod)` to check if there are any APIs in the caller method for string matching. If NO, the APK does not neutralize special elements within the argument, which may cause CWE-22 vulnerability. +![image](https://imgur.com/agRPwp8.png) -## Quark Script CWE-22.py -The Quark Script below uses ovaa.apk to demonstrate. You can change the `SAMPLE_PATH` to the sample you want to detect. For example, `SAMPLE_PATH = InsecureBankv2.apk`. +## Code of CWE-22 in ovaa.apk -```python +We use the [ovaa.apk](https://github.com/oversecured/ovaa) sample to +explain the vulnerability code of CWE-22. + +![image](https://imgur.com/WFpfzFk.png) + +## Quark Script: CWE-22.py + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +First, we design a detection rule `accessFileInExternalDir.json` to spot +behavior accessing a file in an external directory. + +Next, we use API `methodInstance.getArguments()` to get the argument for +the file path and use `quarkResultInstance.isHardcoded(argument)` to +check if the argument is hardcoded into the APK. If No, the argument is +from external input. + +Finally, we use Quark API +`quarkResultInstance.findMethodInCaller(callerMethod, targetMethod)` to +check if there are any APIs in the caller method for string matching. If +NO, the APK does not neutralize special elements within the argument, +which may cause CWE-22 vulnerability. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "ovaa.apk" @@ -32,7 +57,6 @@ ruleInstance = Rule(RULE_PATH) quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) for accessExternalDir in quarkResult.behaviorOccurList: - filePath = accessExternalDir.secondAPI.getArguments()[2] if quarkResult.isHardcoded(filePath): @@ -40,17 +64,18 @@ for accessExternalDir in quarkResult.behaviorOccurList: caller = accessExternalDir.methodCaller strMatchingAPIs = [ - api for api in STRING_MATCHING_API if quarkResult.findMethodInCaller( - caller, api) + api + for api in STRING_MATCHING_API + if quarkResult.findMethodInCaller(caller, api) ] if not strMatchingAPIs: print(f"CWE-22 is detected in method, {caller.fullName}") ``` - ## Quark Rule: accessFileInExternalDir.json -```json + +``` json { "crime": "Access a file in an external directory", "permission": [], @@ -71,16 +96,9 @@ for accessExternalDir in quarkResult.behaviorOccurList: } ``` - ## Quark Script Result -+ **ovaa.apk** -``` -$ python3 CWE-22.py -CWE-22 is detected in method, Loversecured/ovaa/providers/TheftOverwriteProvider; openFile (Landroid/net/Uri; Ljava/lang/String;)Landroid/os/ParcelFileDescriptor; -``` -+ **InsecureBankv2.apk** -``` +``` TEXT $ python3 CWE-22.py -CWE-22 is detected in method, Lcom/android/insecurebankv2/ViewStatement; onCreate (Landroid/os/Bundle;)V +CWE-22 is detected in method, Loversecured/ovaa/providers/TheftOverwriteProvider; openFile (Landroid/net/Uri; Ljava/lang/String;)Landroid/os/ParcelFileDescriptor; ``` diff --git a/CWE-23/CWE-23.py b/CWE-23/CWE-23.py index c6631de..1a6870a 100644 --- a/CWE-23/CWE-23.py +++ b/CWE-23/CWE-23.py @@ -9,8 +9,11 @@ ["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;"], + [ + "Ljava/lang/String;", + "replaceAll", + "(Ljava/lang/String; Ljava/lang/String;)Ljava/lang/String;", + ], ] ruleInstance = Rule(RULE_PATH) @@ -25,11 +28,12 @@ caller = accessExternalDir.methodCaller strMatchingAPIs = [ - api for api in STRING_MATCHING_API if quarkResult.findMethodInCaller( - caller, api) + api + for api in STRING_MATCHING_API + if quarkResult.findMethodInCaller(caller, api) ] if not strMatchingAPIs: print(f"CWE-23 is detected in method, {caller.fullName}") elif strMatchingAPIs.find("..") == -1: - print(f"CWE-23 is detected in method, {caller.fullName}") + print(f"CWE-23 is detected in method, {caller.fullName}") \ No newline at end of file diff --git a/CWE-23/README.md b/CWE-23/README.md index a567d84..4570fc8 100644 --- a/CWE-23/README.md +++ b/CWE-23/README.md @@ -1,17 +1,47 @@ -# Detect CWE-23 in Android Application (ovaa.apk and InsecureBankv2.apk ) +# Detect CWE-23 in Android Application -This scenario aims to demonstrate the detection of the **Relative Path Traversal** vulnerability using [ovaa.apk](https://github.com/oversecured/ovaa) and [InsecureBankv2.apk](https://github.com/dineshshetty/Android-InsecureBankv2/releases). See [CWE-23](https://cwe.mitre.org/data/definitions/23.html) for more details. +This scenario aims to demonstrate the detection of the **Relative Path +Traversal** vulnerability. -To begin with, we will create a detection rule named `accessFileInExternalDir.json` to identify behavior that accesses a file in an external directory. +## CWE-23: Relative Path Traversal -Next, we will use `methodInstance.getArguments()` to retrieve the file path argument and check whether it belongs to the APK or not. If it does not belong to the APK, the argument is likely from external input. +We analyze the definition of CWE-23 and identify its characteristics. -Finally, we will use the Quark API `quarkResultInstance.findMethodInCaller(callerMethod, targetMethod)` to search for any APIs in the caller method that match the string. If no matching API is found, the APK does not neutralize special elements within the argument, which may result in the CWE-23 vulnerability. If a matching API is found, we will verify whether it neutralizes the Relative Path string or not. If it does not neutralize it, the APK may still be vulnerable to CWE-23. +See [CWE-23](https://cwe.mitre.org/data/definitions/23.html) for more +details. -## Quark Script CWE-23.py -The Quark Script below uses ovaa.apk to demonstrate. You can change the `SAMPLE_PATH` to the sample you want to detect. For example, `SAMPLE_PATH = "InsecureBankv2.apk"`. +![image](https://imgur.com/YS9umQp.png) -```python +## Code of CWE-23 in ovaa.apk + +We use the [ovaa.apk](https://github.com/oversecured/ovaa) sample to +explain the vulnerability code of CWE-23. + +![image](https://imgur.com/GosANyj.png) + +## Quark Script: CWE-23.py + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +To begin with, we will create a detection rule named +`accessFileInExternalDir.json` to identify behavior that accesses a file +in an external directory. + +Next, we will use `methodInstance.getArguments()` to retrieve the file +path argument and check whether it belongs to the APK or not. If it does +not belong to the APK, the argument is likely from external input. + +Finally, we will use the Quark API +`quarkResultInstance.findMethodInCaller(callerMethod, targetMethod)` to +search for any APIs in the caller method that match the string. If no +matching API is found, the APK does not neutralize special elements +within the argument, which may result in the CWE-23 vulnerability. If a +matching API is found, we will verify whether it neutralizes the +Relative Path string or not. If it does not neutralize it, the APK may +still be vulnerable to CWE-23. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "ovaa.apk" @@ -23,8 +53,11 @@ STRING_MATCHING_API = [ ["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;"], + [ + "Ljava/lang/String;", + "replaceAll", + "(Ljava/lang/String; Ljava/lang/String;)Ljava/lang/String;", + ], ] ruleInstance = Rule(RULE_PATH) @@ -39,8 +72,9 @@ for accessExternalDir in quarkResult.behaviorOccurList: caller = accessExternalDir.methodCaller strMatchingAPIs = [ - api for api in STRING_MATCHING_API if quarkResult.findMethodInCaller( - caller, api) + api + for api in STRING_MATCHING_API + if quarkResult.findMethodInCaller(caller, api) ] if not strMatchingAPIs: @@ -49,38 +83,32 @@ for accessExternalDir in quarkResult.behaviorOccurList: print(f"CWE-23 is detected in method, {caller.fullName}") ``` - ## Quark Rule: accessFileInExternalDir.json -```json + +``` json { "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": "", - "descriptor": "(Ljava/io/File;Ljava/lang/String;)V" - } + { + "class": "Landroid/os/Environment;", + "method": "getExternalStorageDirectory", + "descriptor": "()Ljava/io/File;" + }, + { + "class": "Ljava/io/File;", + "method": "", + "descriptor": "(Ljava/io/File;Ljava/lang/String;)V" + } ], "score": 1, "label": [] } ``` - ## Quark Script Result -- **ovaa.apk** -``` + +``` TEXT $ python3 CWE-23.py CWE-23 is detected in method, Loversecured/ovaa/providers/TheftOverwriteProvider; openFile (Landroid/net/Uri; Ljava/lang/String;)Landroid/os/ParcelFileDescriptor; ``` -- **InsecureBankv2.apk** -``` -$ python3 CWE-23.py -CWE-23 is detected in method, Lcom/android/insecurebankv2/ViewStatement; onCreate (Landroid/os/Bundle;)V -``` diff --git a/CWE-295/CWE-295.py b/CWE-295/CWE-295.py index 771179a..d89588a 100644 --- a/CWE-295/CWE-295.py +++ b/CWE-295/CWE-295.py @@ -15,6 +15,6 @@ for sslProceedCaller in findMethodInAPK(SAMPLE_PATH, TARGET_METHOD): if (sslProceedCaller.name == OVERRIDE_METHOD[1] and - sslProceedCaller.descriptor == OVERRIDE_METHOD[2] and - OVERRIDE_METHOD[0] in sslProceedCaller.findSuperclassHierarchy()): - print(f"CWE-295 is detected in method, {sslProceedCaller.fullName}") + sslProceedCaller.descriptor == OVERRIDE_METHOD[2] and + OVERRIDE_METHOD[0] in sslProceedCaller.findSuperclassHierarchy()): + print(f"CWE-295 is detected in method, {sslProceedCaller.fullName}") \ No newline at end of file diff --git a/CWE-295/README.md b/CWE-295/README.md index 4181971..c0d36cb 100644 --- a/CWE-295/README.md +++ b/CWE-295/README.md @@ -1,26 +1,30 @@ # Detect CWE-295 in Android Application (InsecureShop.apk) -This scenario seeks to find **Improper Certificate Validation**. See [CWE-295](https://cwe.mitre.org/data/definitions/295.html) for more details. +This scenario seeks to find **Improper Certificate Validation**. See +[CWE-295](https://cwe.mitre.org/data/definitions/295.html) for more +details. -Let’s use this [APK](https://github.com/hax0rgb/InsecureShop) and the above APIs to show how the Quark script finds this vulnerability. +Let's use this [APK](https://github.com/hax0rgb/InsecureShop) and the +above APIs to show how the Quark script finds this vulnerability. -We use the API `findMethodInAPK` to locate all `SslErrorHandler.proceed` methods. Then we need to identify whether the method `WebViewClient.onReceivedSslError` is overridden by its subclass. +We use the API `findMethodInAPK(samplePath, targetMethod)` to locate all +`SslErrorHandler.proceed` methods. Then we need to identify whether if +the method `WebViewClient.onReceivedSslError` is overrode by its +subclass. -First, we check and make sure that the `MethodInstance.name` is `onReceivedSslError`, and the `MethodInstance.descriptor` is `(Landroid/webkit/WebView; Landroid/webkit/SslErrorHandler; Landroid/net/http/SslError;)V`. +First, we check and make sure that the `methodInstance.name` is +`onReceivedSslError`, and the `methodInstance.descriptor` is +`(Landroid/webkit/WebView; Landroid/webkit/SslErrorHandler; Landroid/net/http/SslError;)V`. -Then we use the API `MethodInstance.findSuperclassHierarchy` to get the superclass list of the method's caller class. - -Finally, we check the `Landroid/webkit/WebViewClient;` is on the superclass list. If **YES**, that may cause CWE-295 vulnerability. - -## API Spec -**MethodInstance.findSuperclassHierarchy()** -* **Description:** Find all superclasses of this method object. -* **params:** None -* **Return:** Python list contains all superclass names of this method. +Then we use the API `methodInstance.findSuperclassHierarchy()` to get +the superclass list of the method's caller class. +Finally, we check the `Landroid/webkit/WebViewClient;` is on the +superclass list. If **YES**, that may cause CWE-295 vulnerability. ## Quark Script CWE-295.py -```python + +``` python from quark.script import findMethodInAPK SAMPLE_PATH = "insecureShop.apk" @@ -38,14 +42,15 @@ OVERRIDE_METHOD = [ for sslProceedCaller in findMethodInAPK(SAMPLE_PATH, TARGET_METHOD): if (sslProceedCaller.name == OVERRIDE_METHOD[1] and - sslProceedCaller.descriptor == OVERRIDE_METHOD[2] and - OVERRIDE_METHOD[0] in sslProceedCaller.findSuperclassHierarchy()): + sslProceedCaller.descriptor == OVERRIDE_METHOD[2] and + OVERRIDE_METHOD[0] in sslProceedCaller.findSuperclassHierarchy()): print(f"CWE-295 is detected in method, {sslProceedCaller.fullName}") - ``` + ## Quark Script Result -``` -$ python3 CWE-295.py + +``` TEXT +$ python3 CWE-295.py Requested API level 29 is larger than maximum we have, returning API level 28 instead. CWE-295 is detected in method, Lcom/insecureshop/util/CustomWebViewClient; onReceivedSslError (Landroid/webkit/WebView; Landroid/webkit/SslErrorHandler; Landroid/net/http/SslError;)V ``` diff --git a/CWE-312/CWE-312.py b/CWE-312/CWE-312.py index b11ec90..a151adb 100644 --- a/CWE-312/CWE-312.py +++ b/CWE-312/CWE-312.py @@ -3,23 +3,24 @@ APP_PACKAGE_NAME = "oversecured.ovaa" -TARGET_METHOD = "android.app." \ - "SharedPreferencesImpl$EditorImpl." \ - "putString" +TARGET_METHOD = "android.app." "SharedPreferencesImpl$EditorImpl." "putString" -METHOD_PARAM_TYPE = "java.lang.String," \ - "java.lang.String" +METHOD_PARAM_TYPE = "java.lang.String," "java.lang.String" -fridaResult = runFridaHook(APP_PACKAGE_NAME, - TARGET_METHOD, - METHOD_PARAM_TYPE, - secondToWait = 10) +fridaResult = runFridaHook( + APP_PACKAGE_NAME, TARGET_METHOD, METHOD_PARAM_TYPE, secondToWait=10 +) for putString in fridaResult.behaviorOccurList: - firstParam, secondParam = putString.getParamValues() + firstParam = putString.firstAPI.getArguments() + secondParam = putString.secondAPI.getArguments() - if firstParam in ["email", "password"] and \ - secondParam == checkClearText(secondParam): + if firstParam in ["email", "password"] and secondParam == checkClearText( + secondParam + ): - print(f'The CWE-312 vulnerability is found. The cleartext is "{secondParam}"') \ No newline at end of file + print( + "The CWE-312 vulnerability is found. " + f'The cleartext is "{secondParam}"' + ) \ No newline at end of file diff --git a/CWE-312/README.md b/CWE-312/README.md index 5fa4bc4..32aa88a 100644 --- a/CWE-312/README.md +++ b/CWE-312/README.md @@ -1,40 +1,68 @@ -# Detect CWE-312 in Android Application (ovaa.apk) +# Detect CWE-312 in Android Application -This scenario seeks to find cleartext storage of sensitive data in the APK file. See [CWE-312](https://cwe.mitre.org/data/definitions/312.html) for more details. -Let’s use this [APK](https://github.com/oversecured/ovaa) and the above APIs to show how Quark script find this vulnerability. +This scenario seeks to find **cleartext storage of sensitive data** in +the APK file. + +## CWE-312 Cleartext Storage of Sensitive Information + +We analyze the definition of CWE-312 and identify its characteristics. + +See [CWE-312](https://cwe.mitre.org/data/definitions/312.html) for more +details. + +![image](https://i.imgur.com/cy2EiZx.jpg) + +## Code of CWE-312 in ovaa.apk + +We use the [ovaa.apk](https://github.com/oversecured/ovaa) sample to +explain the vulnerability code of CWE-312. + +![image](https://i.imgur.com/KsFsxTu.jpg) -First, we designed a [Frida](https://frida.re/) script `agent.js` to hook the target method and get the arguments when the target method is called. Then we hook the method `putString` to catch its arguments. Finally, we use [Ciphey](https://github.com/Ciphey/Ciphey) to check if the arguments are encrypted. ## Quark Script CWE-312.py -```python + +Let\'s use the above APIs to show how the Quark script finds this +vulnerability. + +First, we designed a [Frida](https://frida.re) script `agent.js` to hook +the target method and get the arguments when the target method is +called. Then we hook the method `putString` to catch its arguments. +Finally, we use [Ciphey](https://github.com/Ciphey/Ciphey) to check if +the arguments are encrypted. + +``` python from quark.script.frida import runFridaHook from quark.script.ciphey import checkClearText APP_PACKAGE_NAME = "oversecured.ovaa" -TARGET_METHOD = "android.app." \ - "SharedPreferencesImpl$EditorImpl." \ - "putString" +TARGET_METHOD = "android.app." "SharedPreferencesImpl$EditorImpl." "putString" -METHOD_PARAM_TYPE = "java.lang.String," \ - "java.lang.String" +METHOD_PARAM_TYPE = "java.lang.String," "java.lang.String" -fridaResult = runFridaHook(APP_PACKAGE_NAME, - TARGET_METHOD, - METHOD_PARAM_TYPE, - secondToWait = 10) +fridaResult = runFridaHook( + APP_PACKAGE_NAME, TARGET_METHOD, METHOD_PARAM_TYPE, secondToWait=10 +) for putString in fridaResult.behaviorOccurList: - firstParam, secondParam = putString.getParamValues() + firstParam = putString.firstAPI.getArguments() + secondParam = putString.secondAPI.getArguments() - if firstParam in ["email", "password"] and \ - secondParam == checkClearText(secondParam): + if firstParam in ["email", "password"] and secondParam == checkClearText( + secondParam + ): - print(f'The CWE-312 vulnerability is found. The cleartext is "{secondParam}"') + print( + "The CWE-312 vulnerability is found. " + f'The cleartext is "{secondParam}"' + ) ``` + ## Frida Script: agent.js -```js + +``` javascript // -*- coding: utf-8 -*- // This file is part of Quark-Engine - https://github.com/quark-engine/quark-engine // See the file 'LICENSE' for copying permission. @@ -94,8 +122,10 @@ function watchMethodCall(classAndMethodName, methodParamTypes) { rpc.exports["watchMethodCall"] = (classAndMethodName, methodParamTypes) => watchMethodCall(classAndMethodName, methodParamTypes); ``` + ## Quark Script Result -``` + +``` TEXT $ python3 CWE-312.py The CWE-312 vulnerability is found. The cleartext is "test@email.com" The CWE-312 vulnerability is found. The cleartext is "password" diff --git a/CWE-319/README.md b/CWE-319/README.md index 6765bdc..8f5a915 100644 --- a/CWE-319/README.md +++ b/CWE-319/README.md @@ -1,13 +1,38 @@ -# Detect CWE-319 in Android Application (ovaa.apk) +# Detect CWE-319 in Android Application -This scenario seeks to find **the Cleartext Transmission of Sensitive Information**. See [CWE-319](https://cwe.mitre.org/data/definitions/319.html) for more details. -Let’s use this [APK](https://github.com/oversecured/ovaa) and the above APIs to show how the Quark script finds this vulnerability. This sample uses the package Retrofit to request Web APIs, but the APIs use cleartext protocols. +This scenario seeks to find **Cleartext Transmission of Sensitive +Information** in the APK file. -We first design a detection rule `setRetrofitBaseUrl.json` to spot on behavior that sets the base URL of the Retrofit instance. Then, we loop through a custom list of cleartext protocol schemes and use API `behaviorInstance.hasString` to filter arguments that are URL strings with cleartext protocol. +## CWE-319 Cleartext Transmission of Sensitive Information -## Quark Script CWE-319.py -```python +We analyze the definition of CWE-319 and identify its characteristics. + +See [CWE-319](https://cwe.mitre.org/data/definitions/319.html) for more +details. + +![image](https://imgur.com/tk8rtYf.jpg) + +## Code of CWE-319 in ovaa.apk + +We use the [ovaa.apk](https://github.com/oversecured/ovaa) sample to +explain the vulnerability code of CWE-319. + +![image](https://imgur.com/Ew4UOAR.jpg) + +## Quark Script: CWE-319.py + +Let\'s use the above APIs to show how the Quark script finds this +vulnerability. This sample uses the package Retrofit to request Web +APIs, but the APIs use cleartext protocols. + +We first design a detection rule `setRetrofitBaseUrl.json` to spot on +behavior that sets the base URL of the Retrofit instance. Then, we loop +through a custom list of cleartext protocol schemes and use API +`behaviorInstance.hasString(pattern, isRegex)` to filter arguments that +are URL strings with cleartext protocol. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "./ovaa.apk" @@ -37,7 +62,7 @@ for setRetrofitBaseUrl in quarkResult.behaviorOccurList: ## Quark Rule: setRetrofitBaseUrl.json -```json +``` json { "crime": "Set Retrofit Base Url", "permission": [], @@ -61,7 +86,7 @@ for setRetrofitBaseUrl in quarkResult.behaviorOccurList: ## Quark Script Result -``` +``` TEXT $ python3 CWE-319.py CWE-319 detected! Here are the found URLs with cleartext protocol: diff --git a/CWE-327/README.md b/CWE-327/README.md index 8d5f17a..c6e137a 100644 --- a/CWE-327/README.md +++ b/CWE-327/README.md @@ -1,13 +1,36 @@ -# Detect CWE-327 in Android Application (InjuredAndroid.apk) +# Detect CWE-327 in Android Application -This scenario seeks to find **the use of a Broken or Risky Cryptographic Algorithm**. See [CWE-327](https://cwe.mitre.org/data/definitions/327.html) for more details. +This scenario seeks to find **Use of a Broken or Risky Cryptographic +Algorithm** in the APK file. -Let’s use this [APK](https://github.com/B3nac/InjuredAndroid) and the above APIs to show how the Quark script finds this vulnerability. +# CWE-327 Use of a Broken or Risky Cryptographic Algorithm -We first design a detection rule `useOfCryptographicAlgo.json` to spot on behavior using cryptographic algorithms. Then, we use API `behaviorInstance.hasString(pattern, isRegex)` with a list to check if the algorithm is risky. If YES, that may cause the exposure of sensitive data. +We analyze the definition of CWE-327 and identify its characteristics. + +See [CWE-327](https://cwe.mitre.org/data/definitions/327.html) for more +details. + +![image](https://imgur.com/VlX7MTc.png) + +## Code of CWE-327 in InjuredAndroid.apk + +We use the [InjuredAndroid.apk](https://github.com/B3nac/InjuredAndroid) +sample to explain the vulnerability code of CWE-327. + +![image](https://imgur.com/XFvu8zb.png) ## Quark Script CWE-327.py -```python + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +We first design a detection rule `useOfCryptographicAlgo.json` to spot +on behavior using cryptographic algorithms. Then, we use API +`behaviorInstance.hasString(pattern, isRegex)` with a list to check if +the algorithm is risky. If YES, that may cause the exposure of sensitive +data. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "InjuredAndroid.apk" @@ -28,7 +51,8 @@ for useCryptoAlgo in quarkResult.behaviorOccurList: ``` ## Quark Rule: useOfCryptographicAlgo.json -```json + +``` json { "crime": "Use of cryptographic algorithm", "permission": [], @@ -47,12 +71,11 @@ for useCryptoAlgo in quarkResult.behaviorOccurList: "score": 1, "label": [] } - ``` - ## Quark Script Result -``` + +``` TEXT $ python3 CWE-327.py CWE-327 is detected in method, Lb3nac/injuredandroid/k; b (Ljava/lang/String;)Ljava/lang/String; CWE-327 is detected in method, Lb3nac/injuredandroid/k; a (Ljava/lang/String;)Ljava/lang/String; diff --git a/CWE-328/CWE-328.py b/CWE-328/CWE-328.py index 02d324c..a392265 100644 --- a/CWE-328/CWE-328.py +++ b/CWE-328/CWE-328.py @@ -1,35 +1,40 @@ from quark.script import findMethodInAPK -SAMPLE_PATHS = [ - "./allsafe.apk", "./ovaa.apk", - "./AndroGoat.apk", "./MSTG-Android-Java.apk" -] +SAMPLE_PATH = "./allsafe.apk" TARGET_METHODS = [ [ - "Ljava/security/MessageDigest;", "getInstance", - "(Ljava/lang/String;)Ljava/security/MessageDigest;" + "Ljava/security/MessageDigest;", + "getInstance", + "(Ljava/lang/String;)Ljava/security/MessageDigest;", ], [ - "Ljavax/crypto/SecretKeyFactory;", "getInstance", - "(Ljava/lang/String;)Ljavax/crypto/SecretKeyFactory;" - ] + "Ljavax/crypto/SecretKeyFactory;", + "getInstance", + "(Ljava/lang/String;)Ljavax/crypto/SecretKeyFactory;", + ], ] HASH_KEYWORDS = [ - "MD2", "MD4", "MD5", "PANAMA", - "SHA0", "SHA1", "HAVAL128", "RIPEMD128" + "MD2", + "MD4", + "MD5", + "PANAMA", + "SHA0", + "SHA1", + "HAVAL128", + "RIPEMD128", ] -for samplePath in SAMPLE_PATHS: - - methodsFound = [] - for target in TARGET_METHODS: - methodsFound += findMethodInAPK(samplePath, target) +methodsFound = [] +for target in TARGET_METHODS: + methodsFound += findMethodInAPK(SAMPLE_PATH, target) - for setHashAlgo in methodsFound: - algoName = setHashAlgo.getArguments()[0].replace("-", "") +for setHashAlgo in methodsFound: + algoName = setHashAlgo.getArguments()[0].replace("-", "") - if any(keyword in algoName for keyword in HASH_KEYWORDS): - print(f"CWE-328 is detected in {samplePath},\n\t" - f"and it occurs in method, {setHashAlgo.fullName}") + if any(keyword in algoName for keyword in HASH_KEYWORDS): + print( + f"CWE-328 is detected in {SAMPLE_PATH},\n\t" + f"and it occurs in method, {setHashAlgo.fullName}" + ) \ No newline at end of file diff --git a/CWE-328/README.md b/CWE-328/README.md index 4829823..09d491b 100644 --- a/CWE-328/README.md +++ b/CWE-328/README.md @@ -1,63 +1,86 @@ -## Detect CWE-328 in Android Application (allsafe.apk) +# Detect CWE-328 in Android Application -This scenario seeks to find **the use of weak Hash**. See [CWE-328](https://cwe.mitre.org/data/definitions/328.html) for more details. -Let’s use [allsafe.apk](https://github.com/t0thkr1s/allsafe), [ovaa.apk](https://github.com/oversecured/ovaa), [AndroGoat.apk](https://github.com/satishpatnayak/AndroGoat), [MSTG-Android-Java.apk](https://github.com/OWASP/MASTG-Hacking-Playground), and the above APIs to show how the Quark script finds this vulnerability. +This scenario seeks to find **the use of weak Hash**. -First, we use API `findMethodInAPK(samplePath, targetMethod)` to find the method `MessageDigest.getInstance()` or `SecretKeyFactory.getInstance()`. Next, we use API `methodInstance.getArguments()` with a list to check if the method uses [weak hashing algorithms](https://en.wikipedia.org/wiki/Hash_function_security_summary). If **YES**, that causes CWE-328 vulnerability. +## CWE-328 Use of Weak Hash -### Quark Script CWE-328.py -```python +We analyze the definition of CWE-328 and identify its characteristics. + +See [CWE-328](https://cwe.mitre.org/data/definitions/328.html) for more +details. + +![image](https://imgur.com/1jkGcSq.png) + +## Code of CWE-328 in allsafe.apk + +We use the [allsafe.apk](https://github.com/t0thkr1s/allsafe) sample to +explain the vulnerability code of CWE-328. + +![image](https://imgur.com/b0yFDht.png) + +## Quark Script: CWE-328.py + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +First, we use API `findMethodInAPK(samplePath, targetMethod)` to find +the method `MessageDigest.getInstance()` or +`SecretKeyFactory.getInstance()`. Next, we use API +`methodInstance.getArguments()` with a list to check if the method uses +weak hashing algorithms. If **YES**, that causes CWE-328 vulnerability. + +``` python from quark.script import findMethodInAPK -SAMPLE_PATHS = [ - "./allsafe.apk", "./ovaa.apk", - "./AndroGoat.apk", "./MSTG-Android-Java.apk" -] +SAMPLE_PATH = "./allsafe.apk" TARGET_METHODS = [ [ - "Ljava/security/MessageDigest;", "getInstance", - "(Ljava/lang/String;)Ljava/security/MessageDigest;" + "Ljava/security/MessageDigest;", + "getInstance", + "(Ljava/lang/String;)Ljava/security/MessageDigest;", ], [ - "Ljavax/crypto/SecretKeyFactory;", "getInstance", - "(Ljava/lang/String;)Ljavax/crypto/SecretKeyFactory;" - ] + "Ljavax/crypto/SecretKeyFactory;", + "getInstance", + "(Ljava/lang/String;)Ljavax/crypto/SecretKeyFactory;", + ], ] HASH_KEYWORDS = [ - "MD2", "MD4", "MD5", "PANAMA", - "SHA0", "SHA1", "HAVAL128", "RIPEMD128" + "MD2", + "MD4", + "MD5", + "PANAMA", + "SHA0", + "SHA1", + "HAVAL128", + "RIPEMD128", ] -for samplePath in SAMPLE_PATHS: - - methodsFound = [] - for target in TARGET_METHODS: - methodsFound += findMethodInAPK(samplePath, target) +methodsFound = [] +for target in TARGET_METHODS: + methodsFound += findMethodInAPK(SAMPLE_PATH, target) - for setHashAlgo in methodsFound: - algoName = setHashAlgo.getArguments()[0].replace("-", "") +for setHashAlgo in methodsFound: + algoName = setHashAlgo.getArguments()[0].replace("-", "") - if any(keyword in algoName for keyword in HASH_KEYWORDS): - print(f"CWE-328 is detected in {samplePath},\n\t" - f"and it occurs in method, {setHashAlgo.fullName}") + if any(keyword in algoName for keyword in HASH_KEYWORDS): + print( + f"CWE-328 is detected in {SAMPLE_PATH},\n\t" + f"and it occurs in method, {setHashAlgo.fullName}" + ) ``` -### Quark Script Result -``` -$ python CWE-328.py +## Quark Script Result + +``` TEXT +$ python3 CWE-328.py CWE-328 is detected in ./allsafe.apk, and it occurs in method, Linfosecadventures/allsafe/challenges/SQLInjection; md5 (Ljava/lang/String;)Ljava/lang/String; -CWE-328 is detected in ./allsafe.apk, - and it occurs in method, Lcom/google/firebase/database/core/utilities/Utilities; sha1HexDigest (Ljava/lang/String;)Ljava/lang/String; CWE-328 is detected in ./allsafe.apk, and it occurs in method, Linfosecadventures/allsafe/challenges/WeakCryptography; md5Hash (Ljava/lang/String;)Ljava/lang/String; -CWE-328 is detected in ./ovaa.apk, - and it occurs in method, Lorg/apache/commons/io/input/MessageDigestCalculatingInputStream; (Ljava/io/InputStream;)V -CWE-328 is detected in ./AndroGoat.apk, - and it occurs in method, Lowasp/sat/agoat/AccessControlIssue1Activity; hashPIN (Ljava/lang/String;)Ljava/lang/String; -CWE-328 is detected in ./MSTG-Android-Java.apk, - and it occurs in method, Lcom/tozny/crypto/android/AesCbcWithIntegrity; generateKeyFromPassword (Ljava/lang/String; [B)Lcom/tozny/crypto/android/AesCbcWithIntegrity$SecretKeys; +CWE-328 is detected in ./allsafe.apk, + and it occurs in method, Lcom/google/firebase/database/core/utilities/Utilities; sha1HexDigest (Ljava/lang/String;)Ljava/lang/String; ``` diff --git a/CWE-338/README.md b/CWE-338/README.md index 905da0f..1d233b6 100644 --- a/CWE-338/README.md +++ b/CWE-338/README.md @@ -1,10 +1,19 @@ # Detect CWE-338 in Android Application (pivva.apk) -This scenario aims to detect the **Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG).** See [CWE-338](https://cwe.mitre.org/data/definitions/338.html) for more details. +This scenario aims to detect the **Use of Cryptographically Weak +Pseudo-Random Number Generator (PRNG).** See +[CWE-338](https://cwe.mitre.org/data/definitions/338.html) for more +details. -To demonstrate how the Quark script finds this vulnerability, we will use the [pivaa](https://github.com/HTBridge/pivaa) APK file and the above APIs. +To demonstrate how the Quark script finds this vulnerability, we will +use the [pivaa](https://github.com/HTBridge/pivaa) APK file and the +above APIs. -First, we design a detection rule useMethodOfPRNG.json to spot on behavior that uses Pseudo Random Number Generator (PRNG). Then, we use API `getXrefFrom()` to get the caller method of PRNG. Finally, we use some keywords such as “token”, “password”, and “encrypt” to check if the PRNG is for credential usage. +First, we design a detection rule `useMethodOfPRNG.json` to spot on +behavior that uses Pseudo Random Number Generator (PRNG). Then, we use +API `methodInstance.getXrefFrom()` to get the caller method of PRNG. +Finally, we use some keywords such as "token", "password", and "encrypt" +to check if the PRNG is for credential usage. ## Quark Script CWE-338.py @@ -25,14 +34,13 @@ quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) for usePRNGMethod in quarkResult.behaviorOccurList: for prngCaller in usePRNGMethod.methodCaller.getXrefFrom(): if any(keyword in prngCaller.fullName - for keyword in CREDENTIAL_KEYWORDS): + for keyword in CREDENTIAL_KEYWORDS): print("CWE-338 is detected in %s" % prngCaller.fullName) - ``` ## useMethodOfPRNG.json -```json +``` json { "crime": "Use method of PRNG", "permission": [], @@ -55,7 +63,7 @@ for usePRNGMethod in quarkResult.behaviorOccurList: ## Quark Script Result -```TEXT -$ python CWE-338.py +``` TEXT +$ python CWE-338.py CWE-338 is detected in Lcom/htbridge/pivaa/EncryptionActivity$2; onClick (Landroid/view/View;)V ``` diff --git a/CWE-489/CWE-489.py b/CWE-489/CWE-489.py index 14738b9..69362bd 100644 --- a/CWE-489/CWE-489.py +++ b/CWE-489/CWE-489.py @@ -3,4 +3,4 @@ SAMPLE_PATH = "allsafe.apk" if getApplication(SAMPLE_PATH).isDebuggable(): - print(f"CWE-489 is detected in {SAMPLE_PATH}.") + print(f"CWE-489 is detected in {SAMPLE_PATH}.") \ No newline at end of file diff --git a/CWE-489/README.md b/CWE-489/README.md index 455e0a9..4261122 100644 --- a/CWE-489/README.md +++ b/CWE-489/README.md @@ -1,17 +1,28 @@ -## Detect CWE-489 in Android Application (allsafe.apk, AndroGoat.apk, pivaa.apk) +# Detect CWE-489 in Android Application (allsafe.apk, AndroGoat.apk, pivaa.apk) -This scenario seeks to find **active debug code** in the APK file. See [CWE-489](https://cwe.mitre.org/data/definitions/489.html) for more details. -Let’s use [allsafe.apk](https://github.com/t0thkr1s/allsafe), [AndroGoat.apk](https://github.com/satishpatnayak/AndroGoat), [pivaa.apk](https://github.com/HTBridge/pivaa), and the above APIs to show how the Quark script finds this vulnerability. +This scenario seeks to find **active debug code** in the APK file. See +[CWE-489](https://cwe.mitre.org/data/definitions/489.html) for more +details. -First, we use Quark API `getApplication` to get the application element in the manifest file. Then we use `applicationInstance.isDebuggable` to check if the application element sets the attribute `android:debuggable` to true. If **Yes**, that causes CWE-489 vulnerabilities. +Let\'s use [allsafe.apk](https://github.com/t0thkr1s/allsafe), +[AndroGoat.apk](https://github.com/satishpatnayak/AndroGoat), +[pivaa.apk](https://github.com/HTBridge/pivaa), and the above APIs to +show how the Quark script finds this vulnerability. +First, we use Quark API `getApplication(samplePath)` to get the +application element in the manifest file. Then we use +`applicationInstance.isDebuggable()` to check if the application element +sets the attribute `android:debuggable` to true. If **Yes**, that causes +CWE-489 vulnerabilities. -### Quark Script CWE-489.py +## Quark Script CWE-489.py -The Quark Script below uses allsafe.apk to demonstrate. You can change the `SAMPLE_PATH` to the sample you want to detect. For example, `SAMPLE_PATH = AndroGoat.apk` or `SAMPLE_PATH = pivaa.apk`. +The Quark Script below uses allsafe.apk to demonstrate. You can change +the `SAMPLE_PATH` to the sample you want to detect. For example, +`SAMPLE_PATH = AndroGoat.apk` or `SAMPLE_PATH = pivaa.apk`. -```python +``` python from quark.script import getApplication SAMPLE_PATH = "allsafe.apk" @@ -20,24 +31,25 @@ if getApplication(SAMPLE_PATH).isDebuggable(): print(f"CWE-489 is detected in {SAMPLE_PATH}.") ``` -### Quark Script Result +## Quark Script Result - **allsafe.apk** -``` +``` TEXT $ python3 CWE-489.py CWE-489 is detected in allsafe.apk ``` - **AndroGoat.apk** -``` +``` TEXT $ python3 CWE-489.py CWE-489 is detected in AndroGoat.apk ``` + - **pivaa.apk** - -``` + +``` TEXT $ python3 CWE-489.py CWE-489 is detected in pivaa.apk ``` diff --git a/CWE-502/CWE-502.py b/CWE-502/CWE-502.py index d082549..b6c6f5f 100644 --- a/CWE-502/CWE-502.py +++ b/CWE-502/CWE-502.py @@ -18,4 +18,4 @@ 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}") + print(f"CWE-502 is detected in method, {caller.fullName}") \ No newline at end of file diff --git a/CWE-502/README.md b/CWE-502/README.md index 0ec186d..1d7ca71 100644 --- a/CWE-502/README.md +++ b/CWE-502/README.md @@ -1,18 +1,41 @@ -# Detect CWE-502 in Android Application (pivaa) -This scenario aims to demonstrate the detection of the **Deserialization of Untrusted Data** vulnerability using [pivaa.apk](https://github.com/htbridge/pivaa). See [CWE-502](https://cwe.mitre.org/data/definitions/502.html) for more details. +# Detect CWE-502 in Android Application -To begin with, we create 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 there are any of the APIs in ``verificationApis`` are found. +This scenario seeks to find **Deserialization of Untrusted Data** in the +APK file. -If **NO**, it could imply that the APK deserializes the untrusted data, potentially leading to a CWE-502 vulnerability. +## CWE-502: Deserialization of Untrusted Data +We analyze the definition of CWE-502 and identify its characteristics. +See [CWE-502](https://cwe.mitre.org/data/definitions/502.html) for more +details. + +![image](https://imgur.com/Zee9kcJ.jpg) + +## Code of CWE-502 in pivaa.apk + +We use the [pivaa.apk](https://github.com/htbridge/pivaa) sample to +explain the vulnerability code of CWE-502. + +![image](https://imgur.com/yZl5XS3.jpg) ## Quark Script CWE-502.py -The Quark Script below uses pivaa.apk to demonstrate. -```python +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 there are any of the APIs in +`verificationApis` are found. + +If **NO**, it could imply that the APK deserializes the untrusted data, +potentially leading to a CWE-502 vulnerability. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "pivaa.apk" @@ -36,11 +59,9 @@ for dataDeserialization in result.behaviorOccurList: print(f"CWE-502 is detected in method, {caller.fullName}") ``` - - ## Quark Rule: deserializeData.json -```json +``` json { "crime": "Deserialize Data", "permission": [], @@ -55,7 +76,7 @@ for dataDeserialization in result.behaviorOccurList: "class": "Ljava/io/ObjectInputStream;", "method": "readObject", "descriptor": "()Ljava/lang/Object;" - } + } ], "score": 1, @@ -64,9 +85,10 @@ for dataDeserialization in result.behaviorOccurList: ``` ## Quark Script Result -- **pivaa.apk** -``` +- **pivaa.apk** + +``` TEXT $ python CWE-502.py CWE-502 is detected in method, Lcom/htbridge/pivaa/handlers/ObjectSerialization; loadObject ()V ``` diff --git a/CWE-532/README.md b/CWE-532/README.md index 0f61e61..8db5c21 100644 --- a/CWE-532/README.md +++ b/CWE-532/README.md @@ -1,14 +1,27 @@ # Detect CWE-532 in Android Application (dvba.apk) -This scenario seeks to find **insertion of sensitive information into Log file**. See [CWE-532](https://cwe.mitre.org/data/definitions/532.html) for more details. +This scenario seeks to find **insertion of sensitive information into +Log file**. See +[CWE-532](https://cwe.mitre.org/data/definitions/532.html) for more +details. -Let’s use this [APK](https://github.com/rewanthtammana/Damn-Vulnerable-Bank) and the above APIs to show how the Quark script finds this vulnerability. +Let's use this +[APK](https://github.com/rewanthtammana/Damn-Vulnerable-Bank) and the +above APIs to show how the Quark script finds this vulnerability. -First, we use API `findMethodInAPK` to locate `log.d` method. Then we use API `methodInstance.getArguments` to get the argument that input to `log.d`. Finally, we use some keywords such as “token”, “password”, and “decrypt” to check if arguments include sensitive data. If the answer is YES, that may cause sensitive data leakage into log file. +First, we use API `findMethodInAPK(samplePath, targetMethod)` to locate +`log.d` method. Then we use API `methodInstance.getArguments()` to get +the argument that input to `log.d`. Finally, we use some keywords such +as \"token\", \"password\", and \"decrypt\" to check if arguments +include sensitive data. If the answer is YES, that may cause sensitive +data leakage into log file. + +You can use your own keywords in the keywords list to detect sensitive +data. -You can use your own keywords in the keywords list to detect sensitive data. ## Quark Script CWE-532.py -```python + +``` python from quark.script import findMethodInAPK SAMPLE_PATH = "dvba.apk" @@ -32,8 +45,10 @@ for debugLogger in methodsFound: if keyword in arguments[1]: print(f"CWE-532 is detected in method, {debugLogger.fullName}") ``` + ## Quark Script Result -``` + +``` TEXT $ python CWE-532.py CWE-532 is detected in method, Lcom/google/firebase/auth/FirebaseAuth; d (Lc/c/b/h/o;)V ``` diff --git a/CWE-601/CWE-601.py b/CWE-601/CWE-601.py index b559ef5..57094f2 100644 --- a/CWE-601/CWE-601.py +++ b/CWE-601/CWE-601.py @@ -3,40 +3,37 @@ SAMPLE_PATH = 'ovaa.apk' # This is the input for findMethodInAPK, formatted as class name, method name, descriptor -TARGET_METHOD = ["", "startActivity", "(Landroid/content/Intent;)V"] +TARGET_METHOD = ["", "startActivity", "(Landroid/content/Intent;)V"] """ -Due to varying descriptors and classes in smali code from different APIs, +Due to varying descriptors and classes in smali code from different APIs, our search relies solely on the consistent method names. """ -EXTERNAL_INPUT_METHODS = [ - "getIntent", - "getQueryParameter" -] +EXTERNAL_INPUT_METHODS = ["getIntent", "getQueryParameter"] INPUT_FILTER_METHODS = [ - "parse", - "isValidUrl", - "Pattern", - "Matcher", - "encode", - "decode", - "escapeHtml", - "HttpURLConnection" + "parse", + "isValidUrl", + "Pattern", + "Matcher", + "encode", + "decode", + "escapeHtml", + "HttpURLConnection", ] redirectMethods = findMethodInAPK(SAMPLE_PATH, TARGET_METHOD) for redirectMethod in redirectMethods: - arguments = redirectMethod.getArguments() - for argument in arguments: - if any(externalInput in argument for - externalInput in EXTERNAL_INPUT_METHODS): - if not any(filterMethod in argument for - filterMethod in INPUT_FILTER_METHODS): - print(f"CWE-601 is detected in {redirectMethod.fullName}") - - - - + arguments = redirectMethod.getArguments() + for argument in arguments: + if any( + externalInput in argument + for externalInput in EXTERNAL_INPUT_METHODS + ): + if not any( + filterMethod in argument + for filterMethod in INPUT_FILTER_METHODS + ): + print(f"CWE-601 is detected in {redirectMethod.fullName}") \ No newline at end of file diff --git a/CWE-601/README.md b/CWE-601/README.md index 41fa5c3..85f745b 100644 --- a/CWE-601/README.md +++ b/CWE-601/README.md @@ -1,71 +1,82 @@ -Detect CWE-601 in Android Application (ovaa) ------------------------------------------------------- +# Detect CWE-601 in Android Application -This scenario aims to demonstrate the detection of the **URL Redirection to Untrusted Site** vulnerability using [ovaa.apk](https://github.com/oversecured/ovaa). See [CWE-601](https://cwe.mitre.org/data/definitions/601.html) for more details. +This scenario seeks to find **URL Redirection to Untrusted Site** in the +APK file. -To detect the vulnerability, we need to find all the caller methods of ``startActivity`` API that might receive external input without input validation. The ``findMethodInAPK`` function finds all the methods in the APK file that call the ``startActivity`` API. Next, we examine the arguments of each method to discover the methods receiving external input. If a method receives external input but lacks of proper input validation, the CWE-601 vulnerability is identified. +## CWE-601: URL Redirection to Untrusted Site (\'Open Redirect\') -Quark Script CWE-601.py -========================== +We analyze the definition of CWE-601 and identify its characteristics. -The Quark Script below uses ovaa.apk to demonstrate. +See [CWE-601](https://cwe.mitre.org/data/definitions/601.html) for more +details. -```python +![image](https://imgur.com/sgRhcel.png) +## Code of CWE-601 in ovaa.apk +We use the [ovaa.apk](https://github.com/oversecured/ovaa) sample to +explain the vulnerability code of CWE-601. + +![image](https://imgur.com/I61pL2m.png) + +## Quark Script: CWE-601.py + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +To detect the vulnerability, we use the API +`findMethodInAPK(samplePath, targetMethod)` to find all the caller +methods of `startActivity`. Next, we examine the arguments of each +method to discover the methods receiving external input. If a method +receives external input but lacks proper input validation, the CWE-601 +vulnerability is identified. + +``` python from quark.script import findMethodInAPK SAMPLE_PATH = 'ovaa.apk' # This is the input for findMethodInAPK, formatted as class name, method name, descriptor -TARGET_METHOD = ["", "startActivity", "(Landroid/content/Intent;)V"] +TARGET_METHOD = ["", "startActivity", "(Landroid/content/Intent;)V"] """ -Due to varying descriptors and classes in smali code from different APIs, +Due to varying descriptors and classes in smali code from different APIs, our search relies solely on the consistent method names. """ -EXTERNAL_INPUT_METHODS = [ - "getIntent", - "getQueryParameter" -] +EXTERNAL_INPUT_METHODS = ["getIntent", "getQueryParameter"] INPUT_FILTER_METHODS = [ - "parse", - "isValidUrl", - "Pattern", - "Matcher", - "encode", - "decode", - "escapeHtml", - "HttpURLConnection" + "parse", + "isValidUrl", + "Pattern", + "Matcher", + "encode", + "decode", + "escapeHtml", + "HttpURLConnection", ] redirectMethods = findMethodInAPK(SAMPLE_PATH, TARGET_METHOD) for redirectMethod in redirectMethods: - arguments = redirectMethod.getArguments() - for argument in arguments: - if any(externalInput in argument for - externalInput in EXTERNAL_INPUT_METHODS): - if not any(filterMethod in argument for - filterMethod in INPUT_FILTER_METHODS): - print(f"CWE-601 is detected in {redirectMethod.fullName}") - - - - - + arguments = redirectMethod.getArguments() + for argument in arguments: + if any( + externalInput in argument + for externalInput in EXTERNAL_INPUT_METHODS + ): + if not any( + filterMethod in argument + for filterMethod in INPUT_FILTER_METHODS + ): + print(f"CWE-601 is detected in {redirectMethod.fullName}") ``` -Quark Script Result -====================== -- **ovaa.apk** - -``` +## Quark Script Result +``` TEXT $ python CWE-601.py CWE-601 is detected in Loversecured/ovaa/activities/DeeplinkActivity; processDeeplink (Landroid/net/Uri;)V CWE-601 is detected in Loversecured/ovaa/activities/LoginActivity; onLoginFinished ()V - -``` \ No newline at end of file +``` diff --git a/CWE-73/CWE-73.py b/CWE-73/CWE-73.py index 4439dfd..c245da7 100644 --- a/CWE-73/CWE-73.py +++ b/CWE-73/CWE-73.py @@ -22,4 +22,4 @@ result = quarkResult.findMethodInCaller(caller, OPEN_FILE_API) if result: - print("CWE-73 is detected in method, ", caller.fullName) + print("CWE-73 is detected in method, ", caller.fullName) \ No newline at end of file diff --git a/CWE-73/README.md b/CWE-73/README.md index 234888a..7aa6052 100644 --- a/CWE-73/README.md +++ b/CWE-73/README.md @@ -1,15 +1,44 @@ -# Detect CWE-73 in Android Application (ovaa.apk) +# Detect CWE-73 in Android Application -This scenario seeks to find **External Control of File Name or Path**. See [CWE-73](https://cwe.mitre.org/data/definitions/73.html) for more details. +This scenario seeks to find **External Control of File Name or Path** in +the APK file. -First, we design a detection rule `accessFileInExternalDir.json` to spot behavior accessing a file in an external directory. +## CWE-73 External Control of File Name or Path -Second, we use API `methodInstance.getArguments()` to get the argument for the file path and use `quarkResultInstance.isHardcoded(argument)` to check if the argument is hardcoded into the APK. If **No**, the argument is from external input. +We analyze the definition of CWE-73 and identify its characteristics. -Finally, we use Quark API `quarkResultInstance.findMethodInCaller(callerMethod, targetMethod)` to check if any APIs in the caller method for opening files. If **YES**, the APK performs file operations using external input as a path, which may cause CWE-73 vulnerability. +See [CWE-73](https://cwe.mitre.org/data/definitions/73.html) for more +details. -## Quark Script CWE-73.py -```python +![image](https://imgur.com/ES7xg5X.png) + +## Code of CWE-73 in ovaa.apk + +We use the [ovaa.apk](https://github.com/oversecured/ovaa) sample to +explain the vulnerability code of CWE-73. + +![image](https://imgur.com/9oa1HIC.png) + +## Quark Script: CWE-73.py + +Let's use the above APIs to show how Quark script find this +vulnerability. + +First, we design a detection rule `accessFileInExternalDir.json` to spot +behavior accessing a file in an external directory. + +Second, we use API `methodInstance.getArguments()` to get the argument +for the file path and use `quarkResultInstance.isHardcoded(argument)` to +check if the argument is hardcoded into the APK. If **No**, the argument +is from external input. + +Finally, we use Quark API +`quarkResultInstance.findMethodInCaller(callerMethod, targetMethod)` to +check if any APIs in the caller method for opening files. If **YES**, +the APK performs file operations using external input as a path, which +may cause CWE-73 vulnerability. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "ovaa.apk" @@ -35,9 +64,11 @@ for accessExternalDir in quarkResult.behaviorOccurList: if result: print("CWE-73 is detected in method, ", caller.fullName) -``` +``` + ## Quark Rule: accessFileInExternalDir.json -```json + +``` json { "crime": "Access a file in an external directory", "permission": [], @@ -57,8 +88,10 @@ for accessExternalDir in quarkResult.behaviorOccurList: "label": [] } ``` + ## Quark Script Result -``` + +``` TEXT $ python CWE-73.py CWE-73 is detected in method, Loversecured/ovaa/providers/TheftOverwriteProvider; openFile (Landroid/net/Uri; Ljava/lang/String;)Landroid/os/ParcelFileDescriptor; ``` diff --git a/CWE-749/CWE-749.py b/CWE-749/CWE-749.py index c0a8ea6..f198b1c 100644 --- a/CWE-749/CWE-749.py +++ b/CWE-749/CWE-749.py @@ -21,4 +21,4 @@ exposeAPI = quarkResult.findMethodInCaller(caller, targetMethod) if enableJS and exposeAPI: - print(f"CWE-749 is detected in method, {caller.fullName}") + print(f"CWE-749 is detected in method, {caller.fullName}") \ No newline at end of file diff --git a/CWE-749/README.md b/CWE-749/README.md index fe2af3a..67fe37f 100644 --- a/CWE-749/README.md +++ b/CWE-749/README.md @@ -1,12 +1,39 @@ -# Detect CWE-749 in Android Application (MSTG-Android-Java.apk) +# Detect CWE-749 in Android Application -This scenario seeks to find **exposed methods or functions** in the APK file. See [CWE-749](https://cwe.mitre.org/data/definitions/749.html) for more details. +This scenario seeks to find **exposed methods or functions** in the APK +file. -Let’s use this [APK](https://github.com/OWASP/MASTG-Hacking-Playground) and the above APIs to show how Quark script find this vulnerability. +## CWE-749 Exposed Dangerous Method or Function + +We analyze the definition of CWE-749 and identify its characteristics. + +See [CWE-749](https://cwe.mitre.org/data/definitions/749.html) for more +details. + +![image](https://imgur.com/hmihGze.png) + +## Code of CWE-749 in MSTG-Android-Java.apk + +We use the +[MSTG-Android-Java.apk](https://github.com/OWASP/MASTG-Hacking-Playground) +sample to explain the vulnerability code of CWE-749. + +![image](https://imgur.com/KiA0vRD.png) -First, we design a detection rule `configureJsExecution.json` to spot on behavior using method `setJavascriptEnabled`. Then, we use API `methodInstance.getArguments` to check if it enables JavaScript execution on websites. Finally, we look for calls to method `addJavaScriptInterface` in the caller method. If **yes**, the APK exposes methods or functions to websites. That causes CWE-749 vulnerability. ## Quark Script CWE-749.py -```python + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +First, we design a detection rule `configureJsExecution.json` to spot on +behavior using the method `setJavascriptEnabled`. Then, we use the API +`methodInstance.getArguments()` to check if it enables JavaScript +execution on websites. Finally, we look for calls to the method +`addJavaScriptInterface` in the caller method. If yes, the APK exposes +dangerous methods or functions to websites. That causes CWE-749 +vulnerability. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "MSTG-Android-Java.apk" @@ -32,8 +59,10 @@ for configureJsExecution in quarkResult.behaviorOccurList: if enableJS and exposeAPI: print(f"CWE-749 is detected in method, {caller.fullName}") ``` + ## Quark Rule: configureJsExecution.json -```json + +``` json { "crime": "Configure JavaScript execution on websites", "permission": [], @@ -53,8 +82,10 @@ for configureJsExecution in quarkResult.behaviorOccurList: "label": [] } ``` + ## Quark Script Result -``` + +``` TEXT $ python3 CWE-749.py CWE-749 is detected in method, Lsg/vp/owasp_mobile/OMTG_Android/OMTG_ENV_005_WebView_Remote; onCreate (Landroid/os/Bundle;)V diff --git a/CWE-78/CWE-78.py b/CWE-78/CWE-78.py index 02a723c..c09362c 100644 --- a/CWE-78/CWE-78.py +++ b/CWE-78/CWE-78.py @@ -28,4 +28,4 @@ if methodCalled.intersection(STRING_MATCHING_API) and not ExternalStringCommand.hasString(specialElementsPattern): continue else: - print(f"CWE-78 is detected in method, {caller.fullName}") + print(f"CWE-78 is detected in method, {caller.fullName}") \ No newline at end of file diff --git a/CWE-78/README.md b/CWE-78/README.md index 34df72c..93fb5e9 100644 --- a/CWE-78/README.md +++ b/CWE-78/README.md @@ -1,22 +1,40 @@ -Detect CWE-78 in Android Application (Vuldroid.apk ) ------------------------------------------------------------------------ -This scenario seeks to find **Improper Neutralization of Special Elements used in an OS Command**. See [CWE-78](https://cwe.mitre.org/data/definitions/78.html) for more details. +# Detect CWE-78 in Android Application -Let’s use this [APK](https://github.com/jaiswalakshansh/Vuldroid) and the above APIs to show how the Quark script finds this vulnerability. +This scenario seeks to find **Improper Neutralization of Special +Elements used in an OS Command** in the APK file. -First, we design a detection rule ``ExternalStringsCommands.json`` to spot on behavior using external strings as commands. +## CWE-78 Improper Neutralization of Special Elements used in an OS Command (\'OS Command Injection\') -Next, we use Quark API ``behaviorInstance.getMethodsInArgs()`` to get the methods that passed the external command. +We analyze the definition of CWE-78 and identify its characteristics. -Then we check if the method neutralizes any special elements found in the argument. +See [CWE-78](https://cwe.mitre.org/data/definitions/78.html) for more +details. -If the neutralization is not complete, then it may cause CWE-78 vulnerability. +![image](https://imgur.com/aUB195P.png) +## Code of CWE-78 in Vuldroid.apk -Quark Script CWE-78.py -======================= +We use the [Vuldroid.apk](https://github.com/jaiswalakshansh/Vuldroid) +sample to explain the vulnerability code of CWE-78. -The Quark Script below uses Vuldroid.apk to demonstrate. +![image](https://imgur.com/hO6m3Bz.png) + +## Quark Script: CWE-78.py + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +First, we design a detection rule `ExternalStringsCommands.json` to spot +on behavior using external strings as commands. + +Next, we use Quark API `behaviorInstance.getMethodsInArgs()` to get the +methods that passed the external command. + +Then we check if the method neutralizes any special elements found in +the argument. + +If the neutralization is not complete, then it may cause CWE-78 +vulnerability. ``` python from quark.script import runQuarkAnalysis, Rule, findMethodInAPK @@ -50,13 +68,11 @@ for ExternalStringCommand in quarkResult.behaviorOccurList: continue else: print(f"CWE-78 is detected in method, {caller.fullName}") - ``` - -Quark Rule: ExternalStringCommand.json -========================================= -```json +## Quark Rule: ExternalStringCommand.json + +``` json { "crime": "Using external strings as commands", "permission": [], @@ -77,11 +93,11 @@ Quark Rule: ExternalStringCommand.json } ``` -Quark Script Result -====================== -- **Vuldroid.apk** +## Quark Script Result -``` +- **Vuldroid.apk** + +``` TEXT $ python3 CWE-78.py CWE-78 is detected in method, Lcom/vuldroid/application/RootDetection; onCreate (Landroid/os/Bundle;)V ``` diff --git a/CWE-780/CWE-780.py b/CWE-780/CWE-780.py index aebe5dd..caeb3a4 100644 --- a/CWE-780/CWE-780.py +++ b/CWE-780/CWE-780.py @@ -7,9 +7,9 @@ quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) for useCryptographicAlgo in quarkResult.behaviorOccurList: - methodCaller = useCryptographicAlgo.methodCaller - if useCryptographicAlgo.hasString("RSA") and \ - not useCryptographicAlgo.hasString("OAEP"): - print(f"CWE-780 is detected in method, {methodCaller.fullName}") + if useCryptographicAlgo.hasString( + "RSA" + ) and not useCryptographicAlgo.hasString("OAEP"): + print(f"CWE-780 is detected in method, {methodCaller.fullName}") \ No newline at end of file diff --git a/CWE-780/README.md b/CWE-780/README.md index 16f714e..4138644 100644 --- a/CWE-780/README.md +++ b/CWE-780/README.md @@ -1,12 +1,39 @@ -# Detect CWE-780 in Android Application (MSTG-Android-Java.apk) +# Detect CWE-780 in Android Application -This scenario seeks to find **the use of the RSA algorithm without Optimal Asymmetric Encryption Padding (OAEP)**. See [CWE-780](https://cwe.mitre.org/data/definitions/780.html) for more details. -Let’s use this [APK](https://github.com/OWASP/MASTG-Hacking-Playground) and the above APIs to show how the Quark script find this vulnerability. +This scenario seeks to find **the use of the RSA algorithm without +Optimal Asymmetric Encryption Padding (OAEP)** in the APK file. -We first design a detection rule `useOfCryptographicAlgo.json` to spot on behavior using the cryptographic algorithm. Then, we use API `behaviorInstance.hasString(pattern, isRegex)` to filter behaviors using the RSA algorithm. Finally, we use the same API to check if the algorithm runs without the OAEP scheme. If the answer is YES, the plaintext is predictable. -## Quark Script CWE-780.py -```python +## CWE-780 Use of RSA Algorithm without OAEP + +We analyze the definition of CWE-780 and identify its characteristics. + +See [CWE-780](https://cwe.mitre.org/data/definitions/780.html) for more +details. + +![image](https://imgur.com/veZNZcg.png) + +## Code of CWE-780 in dvba.apk + +We use the +[MSTG-Android-Java.apk](https://github.com/OWASP/MASTG-Hacking-Playground) +sample to explain the vulnerability code of CWE-780. + +![image](https://imgur.com/c03senv.png) + +## Quark Script: CWE-780.py + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +We first design a detection rule `useOfCryptographicAlgo.json` to spot +on behavior using the cryptographic algorithm. Then, we use API +`behaviorInstance.hasString(pattern, isRegex)` to filter behaviors using +the RSA algorithm. Finally, we use the same API to check if the +algorithm runs without the OAEP scheme. If the answer is YES, the +plaintext is predictable. + +``` python from quark.script import Rule, runQuarkAnalysis SAMPLE_PATH = "MSTG-Android-Java.apk" @@ -25,7 +52,8 @@ for useCryptographicAlgo in quarkResult.behaviorOccurList: ``` ## Quark Rule: useOfCryptographicAlgo.json -```json + +``` json { "crime": "Use of cryptographic algorithm", "permission": [], @@ -47,7 +75,8 @@ for useCryptographicAlgo in quarkResult.behaviorOccurList: ``` ## Quark Script Result -``` + +``` TEXT $ python3 CWE-780.py CWE-780 is detected in method, Lsg/vp/owasp_mobile/OMTG_Android/OMTG_DATAST_001_KeyStore; encryptString (Ljava/lang/String;)V ``` diff --git a/CWE-79/CWE-79.py b/CWE-79/CWE-79.py index eaed7c7..cfa1381 100644 --- a/CWE-79/CWE-79.py +++ b/CWE-79/CWE-79.py @@ -5,27 +5,28 @@ XSS_FILTERS = [ [ - "Lorg/owasp/esapi/Validator;", "getValidSafeHTML", + "Lorg/owasp/esapi/Validator;", + "getValidSafeHTML", "(Ljava/lang/String; Ljava/lang/String; I Z)Ljava/lang/String;", ], [ - "Lorg/owasp/esapi/Encoder;", "encodeForHTML", + "Lorg/owasp/esapi/Encoder;", + "encodeForHTML", "(Ljava/lang/String;)Ljava/lang/String;", ], [ - "Lorg/owasp/esapi/Encoder;", "encodeForJavaScript", + "Lorg/owasp/esapi/Encoder;", + "encodeForJavaScript", "(Ljava/lang/String;)Ljava/lang/String;", ], [ - "Lorg/owasp/html/PolicyFactory;", "sanitize", + "Lorg/owasp/html/PolicyFactory;", + "sanitize", "(Ljava/lang/String;)Ljava/lang/String;", ], ] -targetMethod = [ - "Landroid/webkit/WebSettings;", "setJavaScriptEnabled", - "(Z)V" -] +targetMethod = ["Landroid/webkit/WebSettings;", "setJavaScriptEnabled", "(Z)V"] ruleInstance = Rule(RULE_PATH) quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) @@ -40,8 +41,10 @@ if enableJS: XSSFiltersInCaller = [ - filterAPI for filterAPI in XSS_FILTERS if quarkResult.findMethodInCaller(caller, filterAPI) + filterAPI + for filterAPI in XSS_FILTERS + if quarkResult.findMethodInCaller(caller, filterAPI) ] if not XSSFiltersInCaller: - print(f"CWE-79 is detected in method, {caller.fullName}") + print(f"CWE-79 is detected in method, {caller.fullName}") \ No newline at end of file diff --git a/CWE-79/README.md b/CWE-79/README.md index 2e4d11d..ed35b3a 100644 --- a/CWE-79/README.md +++ b/CWE-79/README.md @@ -1,17 +1,39 @@ -# Detect CWE-79 in Android Application (Vuldroid.apk) +# Detect CWE-79 in Android Application -This scenario seeks to find **Improper Neutralization of Input During Web Page Generation (‘Cross-site Scripting’).** See [CWE-79](https://cwe.mitre.org/data/definitions/79.html) for more details. +This scenario seeks to find **Improper Neutralization of Input During +Web Page Generation ('Cross-site Scripting')** in the APK file. -Let’s use this [APK](https://github.com/jaiswalakshansh/Vuldroid) and the above APIs to show how the Quark script finds this vulnerability. +## CWE-79 Improper Neutralization of Input During Web Page Generation (\'Cross-site Scripting\') -First, we design a detection rule `loadUrlFromIntent.json` to spot on behavior loading URL from intent data to the WebView instance. +We analyze the definition of CWE-79 and identify its characteristics. -Next, we use API `quarkResultInstance.findMethodInCaller(callerMethod, targetMethod)` and `methodInstance.getArguments()` to check if the Javascript execution is enabled in the WebView. Finally, we check if there are any famous XSS filters. If **NO**, that may cause CWE-79 vulnerability. +See [CWE-79](https://cwe.mitre.org/data/definitions/79.html) for more +details. -### Quark Script CWE-79.py +![image](https://imgur.com/jAwgD0x.png) -```python +## Code of CWE-79 in Vuldroid.apk +We use the [Vuldroid.apk](https://github.com/jaiswalakshansh/Vuldroid) +sample to explain the vulnerability code of CWE-79. + +![image](https://imgur.com/lC6EKun.png) + +## Quark Script CWE-79.py + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +First, we design a detection rule `loadUrlFromIntent.json` to spot the +behavior loading URL from intent data to the WebView instance. + +Next, we use API +`quarkResultInstance.findMethodInCaller(callerMethod, targetMethod)` and +`methodInstance.getArguments()` to check if the Javascript execution is +enabled in the WebView. Finally, we check if there are any famous XSS +filters. If NO, that may cause CWE-79 vulnerability. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "Vuldroid.apk" @@ -19,27 +41,28 @@ RULE_PATH = "loadUrlFromIntent.json" XSS_FILTERS = [ [ - "Lorg/owasp/esapi/Validator;", "getValidSafeHTML", + "Lorg/owasp/esapi/Validator;", + "getValidSafeHTML", "(Ljava/lang/String; Ljava/lang/String; I Z)Ljava/lang/String;", ], [ - "Lorg/owasp/esapi/Encoder;", "encodeForHTML", + "Lorg/owasp/esapi/Encoder;", + "encodeForHTML", "(Ljava/lang/String;)Ljava/lang/String;", ], [ - "Lorg/owasp/esapi/Encoder;", "encodeForJavaScript", + "Lorg/owasp/esapi/Encoder;", + "encodeForJavaScript", "(Ljava/lang/String;)Ljava/lang/String;", ], [ - "Lorg/owasp/html/PolicyFactory;", "sanitize", + "Lorg/owasp/html/PolicyFactory;", + "sanitize", "(Ljava/lang/String;)Ljava/lang/String;", ], ] -targetMethod = [ - "Landroid/webkit/WebSettings;", "setJavaScriptEnabled", - "(Z)V" -] +targetMethod = ["Landroid/webkit/WebSettings;", "setJavaScriptEnabled", "(Z)V"] ruleInstance = Rule(RULE_PATH) quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) @@ -54,17 +77,18 @@ for loadUrl in quarkResult.behaviorOccurList: if enableJS: XSSFiltersInCaller = [ - filterAPI for filterAPI in XSS_FILTERS if quarkResult.findMethodInCaller(caller, filterAPI) + filterAPI + for filterAPI in XSS_FILTERS + if quarkResult.findMethodInCaller(caller, filterAPI) ] if not XSSFiltersInCaller: print(f"CWE-79 is detected in method, {caller.fullName}") - ``` -### Quark Rule: loadUrlFromIntent.json +## Quark Rule: loadUrlFromIntent.json -```json +``` json { "crime": "Load URL from intent to WebView", "permission": [], @@ -85,10 +109,9 @@ for loadUrl in quarkResult.behaviorOccurList: } ``` +## Quark Script Result -### Quark Script Result - -``` +``` TEXT $ python CWE-79.py CWE-79 is detected in method, Lcom/vuldroid/application/ForgetPassword; onCreate (Landroid/os/Bundle;)V ``` diff --git a/CWE-798/CWE-798.py b/CWE-798/CWE-798.py index f770ce3..19f9bb2 100644 --- a/CWE-798/CWE-798.py +++ b/CWE-798/CWE-798.py @@ -9,13 +9,11 @@ for secretKeySpec in quarkResult.behaviorOccurList: - allStrings = quarkResult.getAllStrings() - - firstParam = secretKeySpec.getParamValues()[1] - secondParam = secretKeySpec.getParamValues()[2] + firstParam = secretKeySpec.secondAPI.getArguments()[1] + secondParam = secretKeySpec.secondAPI.getArguments()[2] if secondParam == "AES": - AESKey = re.findall(r'\((.*?)\)', firstParam)[1] + AESKey = re.findall(r"\((.*?)\)", firstParam)[1] - if AESKey in allStrings: - print(f"Found hard-coded {secondParam} key {AESKey}") \ No newline at end of file + if quarkResult.isHardcoded(AESKey): + print(f"Found hard-coded {secondParam} key {AESKey}") \ No newline at end of file diff --git a/CWE-798/README.md b/CWE-798/README.md index f05eafe..f16abee 100644 --- a/CWE-798/README.md +++ b/CWE-798/README.md @@ -1,12 +1,36 @@ -# Detect CWE-798 in Android Application (ovaa.apk) +# Detect CWE-798 in Android Application -This scenario seeks to find hard-coded credentials in the APK file. See [CWE-798](https://cwe.mitre.org/data/definitions/798.html) for more details. +This scenario seeks to find hard-coded credentials in the APK file. -Let’s use this [APK](https://github.com/oversecured/ovaa) and the above APIs to show how Quark script find this vulnerability. +## CWE-798 Use of Hard-coded Credentials -First, we design a detection rule `findSecretKeySpec.json` to spot on behavior uses method `SecretKeySpec`. Then, we get all the parameter values that input to this method. From the returned parameter values, we identify it’s a AES key and parse the key out of the values. Finally, we dump all strings in the APK file and check if the AES key is in the strings. If the answer is YES, BINGO!!! We find hard-coded credentials in the APK file. -## Quark Scipt: CWE-798.py -```python +We analyze the definition of CWE-798 and identify its characteristics. + +See [CWE-798](https://cwe.mitre.org/data/definitions/798.html) for more +details. + +![image](https://i.imgur.com/0G9APpf.jpg) + +## Code of CWE-798 in ovaa.apk + +We use the [ovaa.apk](https://github.com/oversecured/ovaa) sample to +explain the vulnerability code of CWE-798. + +![image](https://i.imgur.com/ikaJlDW.jpg) + +## Quark Script: CWE-798.py + +Let\'s use the above APIs to show how the Quark script finds this +vulnerability. + +First, we design a detection rule `findSecretKeySpec.json` to spot on +behavior using the method `SecretKeySpec`. Then, we get all the +parameter values that are input to this method. And we parse the AES key +out of the parameter values. Finally, we check if the AES key is +hardcoded in the APK file. If the answer is YES, BINGO!!! We find +hard-coded credentials in the APK file. + +``` python import re from quark.script import runQuarkAnalysis, Rule @@ -18,20 +42,19 @@ quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) for secretKeySpec in quarkResult.behaviorOccurList: - allStrings = quarkResult.getAllStrings() - - firstParam = secretKeySpec.getParamValues()[1] - secondParam = secretKeySpec.getParamValues()[2] + firstParam = secretKeySpec.secondAPI.getArguments()[1] + secondParam = secretKeySpec.secondAPI.getArguments()[2] if secondParam == "AES": - AESKey = re.findall(r'\((.*?)\)', firstParam)[1] + AESKey = re.findall(r"\((.*?)\)", firstParam)[1] - if AESKey in allStrings: - print(f"Found hard-coded {secondParam} key {AESKey}") + if quarkResult.isHardcoded(AESKey): + print(f"Found hard-coded {secondParam} key {AESKey}") ``` ## Quark Rule: findSecretKeySpec.json -```json + +``` json { "crime": "Detect APK using SecretKeySpec.", "permission": [], @@ -53,21 +76,9 @@ for secretKeySpec in quarkResult.behaviorOccurList: ``` ## Quark Script Result -``` -$ python3 findSecretKeySpec.py - -Found hard-coded AES key 49u5gh249gh24985ghf429gh4ch8f23f -``` - +``` TEXT +$ python3 findSecretKeySpec.py -## Hard-Coded AES key in the APK file -``` -const-string v2, "49u5gh249gh24985ghf429gh4ch8f23f" - -invoke-virtual {v2}, Ljava/lang/String;->getBytes()[B - -move-result-object v2 - -invoke-direct {v1, v2, v0}, Ljavax/crypto/spec/SecretKeySpec;->([BLjava/lang/String;)V +Found hard-coded AES key 49u5gh249gh24985ghf429gh4ch8f23f ``` diff --git a/CWE-88/CWE-88.py b/CWE-88/CWE-88.py index ca21ee8..a1ab9f5 100644 --- a/CWE-88/CWE-88.py +++ b/CWE-88/CWE-88.py @@ -28,4 +28,4 @@ if methodCalled.intersection(STRING_MATCHING_API) and not ExternalStringCommand.hasString(delimeter): continue else: - print(f"CWE-88 is detected in method, {caller.fullName}") + print(f"CWE-88 is detected in method, {caller.fullName}") \ No newline at end of file diff --git a/CWE-88/README.md b/CWE-88/README.md index 73855e1..2331f19 100644 --- a/CWE-88/README.md +++ b/CWE-88/README.md @@ -1,22 +1,40 @@ -Detect CWE-88 in Android Application (Vuldroid.apk ) ------------------------------------------------------------------------ -This scenario seeks to find **Improper Neutralization of Argument Delimiters in a Command**. See [CWE-88](https://cwe.mitre.org/data/definitions/88.html) for more details. +# Detect CWE-88 in Android Application -Let’s use this [APK](https://github.com/jaiswalakshansh/Vuldroid) and the above APIs to show how the Quark script finds this vulnerability. -First, we design a detection rule ``ExternalStringsCommands.json`` to spot on behavior using external strings as commands. +This scenario seeks to find **Argument Injection** in the APK file. -Next, we use Quark API ``behaviorInstance.getMethodsInArgs()`` to get the methods that passed the external command. +## CWE-88 Improper Neutralization of Argument Delimiters in a Command -Then we check if the method neutralizes any special elements found in the argument. +We analyze the definition of CWE-88 and identify its characteristics. -If the neutralization is not complete, then it may cause CWE-88 vulnerability. +See [CWE-88](https://cwe.mitre.org/data/definitions/88.html) for more +details. +![image](https://imgur.com/7EBPGUT.png) -Quark Script CWE-88.py -======================= +## Code of CWE-88 in vuldroid.apk -The Quark Script below uses Vuldroid.apk to demonstrate. +We use the [vuldroid.apk](https://github.com/jaiswalakshansh/Vuldroid) +sample to explain the vulnerability code of CWE-88. + +![image](https://imgur.com/emnvGcE.png) + +## Quark Script: CWE-88.py + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +First, we design a detection rule `ExternalStringsCommands.json` to spot +on behavior using external strings as commands. + +Next, we use Quark API `behaviorInstance.getMethodsInArgs()` to get the +methods that passed the external command. + +Then we check if the method neutralizes any special elements in the +argument. + +If the neutralization is not complete, then it may cause CWE-88 +vulnerability. ``` python from quark.script import runQuarkAnalysis, Rule, findMethodInAPK @@ -50,13 +68,11 @@ for ExternalStringCommand in quarkResult.behaviorOccurList: continue else: print(f"CWE-88 is detected in method, {caller.fullName}") - ``` - -Quark Rule: ExternalStringCommand.json -========================================= -```json +## Quark Rule: ExternalStringCommand.json + +``` json { "crime": "Using external strings as commands", "permission": [], @@ -77,11 +93,9 @@ Quark Rule: ExternalStringCommand.json } ``` -Quark Script Result -====================== -- **Vuldroid.apk** +## Quark Script Result -``` +``` TEXT $ python3 CWE-88.py CWE-88 is detected in method, Lcom/vuldroid/application/RootDetection; onCreate (Landroid/os/Bundle;)V ``` diff --git a/CWE-89/CWE-89.py b/CWE-89/CWE-89.py index 4010de4..bafd9a5 100644 --- a/CWE-89/CWE-89.py +++ b/CWE-89/CWE-89.py @@ -14,6 +14,6 @@ for sqlCommandExecution in quarkResult.behaviorOccurList: if sqlCommandExecution.isArgFromMethod( - targetMethod + targetMethod ): print(f"CWE-89 is detected in {SAMPLE_PATH}") \ No newline at end of file diff --git a/CWE-89/README.md b/CWE-89/README.md index e218c83..e7e7860 100644 --- a/CWE-89/README.md +++ b/CWE-89/README.md @@ -1,12 +1,36 @@ -# Detect CWE-89 in Android Application (AndroGoat.apk) +# Detect CWE-89 in Android Application -This scenario seeks to find SQL injection in the APK file. See [CWE-89](https://cwe.mitre.org/data/definitions/89.html) for more details. +This scenario seeks to find **SQL injection** in the APK file. -Let’s use this [APK](https://github.com/satishpatnayak/AndroGoat) and the above APIs to show how Quark script find this vulnerability. +## CWE-89 Improper Neutralization of Special Elements used in an SQL Command -First, we design a detection rule `executeSQLCommand.json` to spot on behavior using SQL command Execution. Then, we use API `isArgFromMethod` to check if `append` use the value of `getText` as the argument. If yes, we confirmed that the SQL command string is built from user input, which will cause CWE-89 vulnerability. -## Quark Script CWE-89.py -```python +We analyze the definition of CWE-89 and identify its characteristics. + +See [CWE-89](https://cwe.mitre.org/data/definitions/89.html) for more +details. + +![image](https://i.imgur.com/iJ1yIBb.jpg) + +## Code of CWE-89 in androgoat.apk + +We use the [androgoat.apk](https://github.com/satishpatnayak/AndroGoat) +sample to explain the vulnerability code of CWE-89. + +![image](https://i.imgur.com/bdQqWFb.jpg) + +## Quark Script: CWE-89.py + +Let\'s use the above APIs to show how the Quark script finds this +vulnerability. + +First, we design a detection rule `executeSQLCommand.json` to spot on +behavior using SQL command Execution. Then, we use API +`behaviorInstance.isArgFromMethod(targetMethod)` to check if `append` +uses the value of `getText` as the argument. If yes, we confirmed that +the SQL command string is built from user input, which will cause CWE-89 +vulnerability. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "AndroGoat.apk" @@ -29,7 +53,8 @@ for sqlCommandExecution in quarkResult.behaviorOccurList: ``` ## Quark Rule: executeSQLCommand.json -```json + +``` json { "crime": "Execute SQL Command", "permission": [], @@ -52,7 +77,7 @@ for sqlCommandExecution in quarkResult.behaviorOccurList: ## Quark Script Result -``` +``` text $ python3 CWE-89.py CWE-89 is detected in AndroGoat.apk diff --git a/CWE-921/CWE-921.py b/CWE-921/CWE-921.py index 284f1e7..9fba1f1 100644 --- a/CWE-921/CWE-921.py +++ b/CWE-921/CWE-921.py @@ -7,7 +7,7 @@ quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) for existingFile in quarkResult.behaviorOccurList: - filePath = existingFile.getParamValues()[0] + filePath = existingFile.secondAPI.getArguments()[0] if "sdcard" in filePath: print(f"This file is stored inside the SDcard\n") print(f"CWE-921 is detected in {SAMPLE_PATH}.") \ No newline at end of file diff --git a/CWE-921/README.md b/CWE-921/README.md index 952cb58..5315ce4 100644 --- a/CWE-921/README.md +++ b/CWE-921/README.md @@ -1,13 +1,36 @@ -# Detect CWE-921 in Android Application (ovaa.apk) +# Detect CWE-921 in Android Application -This scenario seeks to find unsecure storage mechanism of data in the APK file. See [CWE-921](https://cwe.mitre.org/data/definitions/921.html) for more details. +This scenario seeks to find the **unsecured storage mechanism of +sensitive data** in the APK file. -Let’s use this [APK](https://github.com/oversecured/ovaa) and the above APIs to show how Quark script find this vulnerability. +## CWE-921 Storage of Sensitive Data in a Mechanism without Access Control -First, we design a detection rule `checkFileExistence.json` to spot on behavior that checks if a file exist on given storage mechanism. Then, we use API `getParamValues()` to get the file path. Finally, CWE-921 is found if the file path contains keyword `sdcard`. +We analyze the definition of CWE-921 and identify its characteristics. -## Quark Script CWE-921.py -```python +See [CWE-921](https://cwe.mitre.org/data/definitions/921.html) for more +details. + +![image](https://imgur.com/ihtjGAu.jpg) + +## Code of CWE-921 in ovaa.apk + +We use the [ovaa.apk](https://github.com/oversecured/ovaa) sample to +explain the vulnerability code of CWE-921. + +![image](https://imgur.com/ACzJct8.jpg) + +## Quark Script: CWE-921.py + +Let's use the above APIs to show how the Quark script finds this +vulnerability. + +First, we design a detection rule `checkFileExistence.json` to spot on +behavior that checks if a file exists on a given storage mechanism. +Then, we use API `methodInstance.getArguments()` to get the file path. +Finally, CWE-921 is found if the file path contains the keyword +`sdcard`. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "ovaa.apk" @@ -17,14 +40,15 @@ ruleInstance = Rule(RULE_PATH) quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) for existingFile in quarkResult.behaviorOccurList: - filePath = existingFile.getParamValues()[0] + filePath = existingFile.secondAPI.getArguments()[0] if "sdcard" in filePath: print(f"This file is stored inside the SDcard\n") print(f"CWE-921 is detected in {SAMPLE_PATH}.") ``` ## Quark Rule: checkFileExistence.json -```json + +``` json { "crime": "Check file existence", "permission": [], @@ -46,7 +70,8 @@ for existingFile in quarkResult.behaviorOccurList: ``` ## Quark Script Result -``` + +``` TEXT $ python3 CWE-921.py This file is stored inside the SDcard diff --git a/CWE-925/CWE-925.py b/CWE-925/CWE-925.py index 4cc7117..f35bf7f 100644 --- a/CWE-925/CWE-925.py +++ b/CWE-925/CWE-925.py @@ -1,6 +1,6 @@ from quark.script import checkMethodCalls, getReceivers -SAMPLE_PATHS = ["AndroGoat.apk", "InsecureBankv2.apk"] +sample_path = "InsecureBankv2.apk" TARGET_METHOD = [ '', @@ -12,12 +12,10 @@ ['Landroid/content/Intent;', 'getAction', '()Ljava/lang/String;'] ] -for filepath in SAMPLE_PATHS: - receivers = getReceivers(filepath) - for receiver in receivers: - if receiver.isExported(): - className = "L"+str(receiver).replace('.', '/')+';' - TARGET_METHOD[0] = className - if not checkMethodCalls(filepath, TARGET_METHOD, CHECK_METHODS): - print(f"CWE-925 is detected in method, {className}") - +receivers = getReceivers(sample_path) +for receiver in receivers: + if receiver.isExported(): + className = "L"+str(receiver).replace('.', '/')+';' + TARGET_METHOD[0] = className + if not checkMethodCalls(sample_path, TARGET_METHOD, CHECK_METHODS): + print(f"CWE-925 is detected in method, {className}") \ No newline at end of file diff --git a/CWE-925/README.md b/CWE-925/README.md index a8fd690..d9bbe96 100644 --- a/CWE-925/README.md +++ b/CWE-925/README.md @@ -1,46 +1,43 @@ -# Detect CWE-925 in Android Application (InsecureBankv2, AndroGoat) +# Detect CWE-925 in Android Application -This scenario seeks to find **Improper Verification of Intent by Broadcast Receiver**. See [CWE-925](https://cwe.mitre.org/data/definitions/925.html) for more details. -Let’s use both two of apks ([InsecureBankv2](https://github.com/dineshshetty/Android-InsecureBankv2) and [AndroGoat](https://github.com/satishpatnayak/AndroGoat)) to show how the Quark script finds this vulnerability. +This scenario seeks to find **Improper Verification of Intent by +Broadcast Receiver** in the APK file. -In the first step, we use the `getReceivers` API to find all `Receiver` components defined in the Android application. Then, we exclude any receivers that are not exported. +## CWE-925 Improper Verification of Intent by Broadcast Receiver -In the second step, our goal is to verify the **intentAction** is properly validated in each receiver which is identified in the previous step. To do this, we use the `checkMethodCalls` function. +We analyze the definition of CWE-925 and identify its characteristics. -Finally, if any receiver's **onReceive** method exhibits improper verification on **intentAction**, it could indicate a potential CWE-925 vulnerability. +See [CWE-925](https://cwe.mitre.org/data/definitions/925.html) for more +details. -## API Spec -**receiverInstance.hasIntentFilter()** -* **Description:** Check if the receiver has an intent-filter. -* **params:** None -* **Return:** True/False +![image](https://imgur.com/fMZ2bMN.jpg) -**receiverInstance.isExported()** -* **Description:** Check if the receiver is exported. -* **params:** None -* **Return:** True/False +## Code of CWE-925 in InsecureBankv2.apk -**getReceivers(samplePath)** -* **Description:** Get receivers from a target sample. -* **params:** - * samplePath: target file -* **Return:** python list containing receivers - -**checkMethodCalls(samplePath, targetMethod, checkMethods)** -* **Description:** Check if any of the specific methods shown in the `targetMethod` -* **params:** - * samplePath: target file - * targetMethod: python list contains the class name,method name, and descriptor of the target method or a Method Object. - * checkMethods: python list contains the class name, method name, and descriptor of the target method. -* **Return:** bool that indicate specific methods can be called or defined within a `target method` or not. +We use the +[InsecureBankv2.apk](https://github.com/dineshshetty/Android-InsecureBankv2) +sample to explain the vulnerability code of CWE-925. +![image](https://imgur.com/V7VtL3x.jpg) ## Quark Script CWE-925.py -```python + +First, we use API `getReceivers(samplePath)` and +`receiverInstance.isExported()` to find all the exported receivers +defined in the APK. + +Second, we use API +`checkMethodCalls(samplePath, targetMethod, checkMethods)` to check if +the `onReceive` method of every exported receiver obtains intent action. + +If **No**, it could imply that the APK does not verify intent properly, +potentially leading to a CWE-925 vulnerability. + +``` python from quark.script import checkMethodCalls, getReceivers -SAMPLE_PATHS = ["AndroGoat.apk", "InsecureBankv2.apk"] +sample_path = "InsecureBankv2.apk" TARGET_METHOD = [ '', @@ -52,19 +49,18 @@ CHECK_METHODS = [ ['Landroid/content/Intent;', 'getAction', '()Ljava/lang/String;'] ] -for filepath in SAMPLE_PATHS: - receivers = getReceivers(filepath) - for receiver in receivers: - if receiver.isExported(): - className = "L"+str(receiver).replace('.', '/')+';' - TARGET_METHOD[0] = className - if not checkMethodCalls(filepath, TARGET_METHOD, CHECK_METHODS): - print(f"CWE-925 is detected in method, {className}") - +receivers = getReceivers(sample_path) +for receiver in receivers: + if receiver.isExported(): + className = "L"+str(receiver).replace('.', '/')+';' + TARGET_METHOD[0] = className + if not checkMethodCalls(sample_path, TARGET_METHOD, CHECK_METHODS): + print(f"CWE-925 is detected in method, {className}") ``` + ## Quark Script Result -``` + +``` TEXT $ python CWE-925.py -CWE-925 is detected in method, Lowasp/sat/agoat/ShowDataReceiver; CWE-925 is detected in method, Lcom/android/insecurebankv2/MyBroadCastReceiver; ``` diff --git a/CWE-926/README.md b/CWE-926/README.md index 076ed23..51fc359 100644 --- a/CWE-926/README.md +++ b/CWE-926/README.md @@ -1,12 +1,40 @@ -# Detect CWE-926 in Android Application (dvba.apk) +# Detect CWE-926 in Android Application -This scenario seeks to find **improper export of Android application components** in the APK file. See [CWE-926](https://cwe.mitre.org/data/definitions/926.html) for more details. -Let’s use this [APK](https://github.com/rewanthtammana/Damn-Vulnerable-Bank) and the above APIs to show how Quark script find this vulnerability. +This scenario seeks to find **Improper Export of Android Application +Components** in the APK file. -First, we use Quark API `getActivities` to get all activity data in the manifest. Then we use `activityInstance.hasIntentFilter` to check if the activities have `intent-filter`. Also, we use `activityInstance.isExported` to check if the activities set the attribute `android:exported=true`. If both are **true**, then the APK exports the component for use by other applications. That may cause CWE-926 vulnerabilities. -## Quark Script CWE-926.py -```python +## CWE-926 Improper Export of Android Application Components + +We analyze the definition of CWE-926 and identify its characteristics. + +See [CWE-926](https://cwe.mitre.org/data/definitions/926.html) for more +details. + +![image](https://imgur.com/Km8wtGs.jpg) + +## Code of CWE-926 in dvba.apk + +We use the +[dvba.apk](https://github.com/rewanthtammana/Damn-Vulnerable-Bank) +sample to explain the vulnerability code of CWE-926. + +![image](https://imgur.com/KoOt5ii.jpg) + +## Quark Script: CWE-926.py + +Let\'s use the above APIs to show how the Quark script finds this +vulnerability. + +First, we use Quark API `getActivities(samplePath)` to get all activity +data in the manifest. Then, we use `activityInstance.hasIntentFilter()` +to check if the activities have `intent-filter`. Also, we use +`activityInstance.isExported()` to check if the activities set the +attribute `android:exported=true`. If both are **true**, then the APK +exports the component for use by other applications. That may cause +CWE-926 vulnerabilities. + +``` python from quark.script import * SAMPLE_PATH = "dvba.apk" @@ -16,10 +44,11 @@ for activityInstance in getActivities(SAMPLE_PATH): if activityInstance.hasIntentFilter() and activityInstance.isExported(): print(f"CWE-926 is detected in the activity, {activityInstance}") ``` + ## Quark Script Result -``` -$ python3 CWE-926.py -CWE-926 is found in the activity, com.app.damnvulnerablebank.CurrencyRates -CWE-926 is found in the activity, com.app.damnvulnerablebank.SplashScreen +``` TEXT +$ python3 CWE-926.py +CWE-926 is detected in the activity, com.app.damnvulnerablebank.CurrencyRates +CWE-926 is detected in the activity, com.app.damnvulnerablebank.SplashScreen ``` diff --git a/CWE-94/CWE-94.py b/CWE-94/CWE-94.py index f8e103d..5ae4cf0 100644 --- a/CWE-94/CWE-94.py +++ b/CWE-94/CWE-94.py @@ -4,10 +4,10 @@ RULE_PATH = "loadExternalCode.json" targetMethod = [ - "Landroid/content/pm/PackageManager;", - "checkSignatures", - "(Ljava/lang/String;Ljava/lang/String;)I" - ] + "Landroid/content/pm/PackageManager;", + "checkSignatures", + "(Ljava/lang/String;Ljava/lang/String;)I" +] ruleInstance = Rule(RULE_PATH) quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) @@ -15,11 +15,11 @@ for ldExternalCode in quarkResult.behaviorOccurList: callerMethod = [ - ldExternalCode.methodCaller.className, - ldExternalCode.methodCaller.methodName, - ldExternalCode.methodCaller.descriptor - ] + ldExternalCode.methodCaller.className, + ldExternalCode.methodCaller.methodName, + ldExternalCode.methodCaller.descriptor + ] if not quarkResult.findMethodInCaller(callerMethod, targetMethod): - print(f"\nMethod: {targetMethod[1]} not found!") + print(f"Method: {targetMethod[1]} not found!") print(f"CWE-94 is detected in {SAMPLE_PATH}") \ No newline at end of file diff --git a/CWE-94/README.md b/CWE-94/README.md index a544acc..b6d2640 100644 --- a/CWE-94/README.md +++ b/CWE-94/README.md @@ -1,23 +1,46 @@ -# Detect CWE-94 in Android Application (ovaa.apk) +# Detect CWE-94 in Android Application -This scenario seeks to find code injection in the APK file. See [CWE-94](https://cwe.mitre.org/data/definitions/94.html) for more details. -Let’s use this [APK](https://github.com/oversecured/ovaa) and the above APIs to show how the Quark script finds this vulnerability. +This scenario seeks to find **code injection** in the APK file. -First, we design a detection rule `loadExternalCode.json` to spot on behavior using the method `createPackageContext`. Then, we find the caller method that calls the `createPackageContext`. Finally, we check if the method `checkSignatures` is called in the caller method for verification. +## CWE-94 Improper Control of Generation of Code + +We analyze the definition of CWE-94 and identify its characteristics. + +See [CWE-94](https://cwe.mitre.org/data/definitions/94.html) for more +details. + +![image](https://imgur.com/faWwd3p.jpg) + +## Code of CWE-94 in ovaa.apk + +We use the [ovaa.apk](https://github.com/oversecured/ovaa) sample to +explain the vulnerability code of CWE-94. + +![image](https://imgur.com/duobWF2.jpg) ## Quark Script: CWE-94.py -```python + +Let\'s use the above APIs to show how the Quark script finds this +vulnerability. + +First, we design a detection rule `loadExternalCode.json` to spot on +behavior using the method `createPackageContext`. Then, we find the +caller method that calls the `createPackageContext`. Finally, we check +if the method `checkSignatures` is called in the caller method for +verification. + +``` python from quark.script import runQuarkAnalysis, Rule SAMPLE_PATH = "ovaa.apk" RULE_PATH = "loadExternalCode.json" targetMethod = [ - "Landroid/content/pm/PackageManager;", - "checkSignatures", - "(Ljava/lang/String;Ljava/lang/String;)I" - ] + "Landroid/content/pm/PackageManager;", + "checkSignatures", + "(Ljava/lang/String;Ljava/lang/String;)I" + ] ruleInstance = Rule(RULE_PATH) quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) @@ -25,18 +48,19 @@ quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) for ldExternalCode in quarkResult.behaviorOccurList: callerMethod = [ - ldExternalCode.methodCaller.className, - ldExternalCode.methodCaller.methodName, - ldExternalCode.methodCaller.descriptor - ] + ldExternalCode.methodCaller.className, + ldExternalCode.methodCaller.methodName, + ldExternalCode.methodCaller.descriptor + ] if not quarkResult.findMethodInCaller(callerMethod, targetMethod): - print(f"\nMethod: {targetMethod[1]} not found!") + print(f"Method: {targetMethod[1]} not found!") print(f"CWE-94 is detected in {SAMPLE_PATH}") ``` ## Quark Rule: loadExternalCode.json -```json + +``` json { "crime": "Load external code from other APK.", "permission": [], @@ -58,9 +82,9 @@ for ldExternalCode in quarkResult.behaviorOccurList: ``` ## Quark Script Result -``` -$ python3 CWE-94.py +``` TEXT +$ python3 CWE-94.py Method: checkSignatures not found! CWE-94 is detected in ovaa.apk ``` diff --git a/CWE-940/CWE-940.py b/CWE-940/CWE-940.py index c75603c..7628fca 100644 --- a/CWE-940/CWE-940.py +++ b/CWE-940/CWE-940.py @@ -24,4 +24,4 @@ if verifiedMethodCandidates == []: caller = behaviorInstance.methodCaller.fullName - print(f"cwe-940 is detected in method, {caller}") + print(f"cwe-940 is detected in method, {caller}") \ No newline at end of file diff --git a/CWE-940/README.md b/CWE-940/README.md index 542363d..43aeb93 100644 --- a/CWE-940/README.md +++ b/CWE-940/README.md @@ -1,78 +1,86 @@ -Detect CWE-940 in Android Application (ovaa,Vuldroid) ------------------------------------------------------- -This scenario aims to demonstrate the detection of the **Improper Verification of Source of a Communication Channel** vulnerability using [ovaa.apk](https://github.com/oversecured/ovaa) and [Vuldroid.apk](https://github.com/jaiswalakshansh/Vuldroid). See [CWE-940](https://cwe.mitre.org/data/definitions/940.html) for more details. - -To begin with, we create a detection rule named ``LoadUrlFromIntent.json`` to identify behavior that loads url from intent data to the WebView. - -Next, we retrieve the methods that pass the url. Following this, we check if these methods are only for setting intent, such as findViewById, getStringExtra, or getIntent. - -If **NO**, it could imply that the APK uses communication channels without proper verification, which may cause CWE-940 vulnerability. - -Quark Script CWE-940.py -========================== - -The Quark Script below uses ovaa.apk to demonstrate. You can change the ``SAMPLE_PATH`` to the sample you want to detect. For example, ``SAMPLE_PATH = "Vuldroid.apk"``. - - -```python - from quark.script import runQuarkAnalysis, Rule - - SAMPLE_PATH = "ovaa.apk" - RULE_PATH = "LoadUrlFromIntent.json" - - INTENT_SETTING_METHODS = [ - "findViewById", - "getStringExtra", - "getIntent", - ] - - ruleInstance = Rule(RULE_PATH) - - quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) - - for behaviorInstance in quarkResult.behaviorOccurList: - methodsInArgs = behaviorInstance.getMethodsInArgs() - - verifiedMethodCandidates = [] - - for method in methodsInArgs: - if method.methodName not in INTENT_SETTING_METHODS: - verifiedMethodCandidates.append(method) - - if verifiedMethodCandidates == []: - caller = behaviorInstance.methodCaller.fullName - print(f"cwe-940 is detected in method, {caller}") -``` +# Detect CWE-940 in Android Application (ovaa,Vuldroid) + +This scenario aims to demonstrate the detection of the **Improper +Verification of Source of a Communication Channel** vulnerability using +[ovaa.apk](https://github.com/oversecured/ovaa) and +[Vuldroid.apk](https://github.com/jaiswalakshansh/Vuldroid). See +[CWE-940](https://cwe.mitre.org/data/definitions/940.html) for more +details. + +To begin with, we create a detection rule named `LoadUrlFromIntent.json` +to identify behavior that loads url from intent data to the WebView. + +Next, we retrieve the methods that pass the url. Following this, we +check if these methods are only for setting intent, such as +`findViewById`, `getStringExtra`, or `getIntent`. + +If **NO**, it could imply that the APK uses communication channels +without proper verification, which may cause CWE-940 vulnerability. + +# Quark Script CWE-940.py + +The Quark Script below uses ovaa.apk to demonstrate. You can change the +`SAMPLE_PATH` to the sample you want to detect. For example, +`SAMPLE_PATH = "Vuldroid.apk"`. + +``` python +from quark.script import runQuarkAnalysis, Rule + +SAMPLE_PATH = "ovaa.apk" +RULE_PATH = "LoadUrlFromIntent.json" -Quark Rule: LoadUrlFromIntent.json -============================================== - -```json - { - "crime": "Load Url from Intent and open WebView", - "permission": [], - "api": [ - { - "class": "Landroid/content/Intent;", - "method": "getStringExtra", - "descriptor": "(Ljava/lang/String;)Ljava/lang/String" - }, - { - "class": "Landroid/webkit/WebView;", - "method": "loadUrl", - "descriptor": "(Ljava/lang/String;)V" - } - ], - "score": 1, - "label": [] - } +INTENT_SETTING_METHODS = [ + "findViewById", + "getStringExtra", + "getIntent", +] + +ruleInstance = Rule(RULE_PATH) + +quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance) + +for behaviorInstance in quarkResult.behaviorOccurList: + methodsInArgs = behaviorInstance.getMethodsInArgs() + + verifiedMethodCandidates = [] + + for method in methodsInArgs: + if method.methodName not in INTENT_SETTING_METHODS: + verifiedMethodCandidates.append(method) + + if verifiedMethodCandidates == []: + caller = behaviorInstance.methodCaller.fullName + print(f"cwe-940 is detected in method, {caller}") ``` -Quark Script Result -====================== -- **ovaa.apk** +## Quark Rule: LoadUrlFromIntent.json +``` json +{ + "crime": "Load Url from Intent and open WebView", + "permission": [], + "api": [ + { + "class": "Landroid/content/Intent;", + "method": "getStringExtra", + "descriptor": "(Ljava/lang/String;)Ljava/lang/String" + }, + { + "class": "Landroid/webkit/WebView;", + "method": "loadUrl", + "descriptor": "(Ljava/lang/String;)V" + } + ], + "score": 1, + "label": [] +} ``` - $ python CWE-940.py - CWE-940 is detected in method, Loversecured/ovaa/activities/WebViewActivity; onCreate (Landroid/os/Bundle;)V + +## Quark Script Result + +- **ovaa.apk** + +``` TEXT +$ python CWE-940.py +CWE-940 is detected in method, Loversecured/ovaa/activities/WebViewActivity; onCreate (Landroid/os/Bundle;)V ```