Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update CWE showcases #43

Merged
merged 1 commit into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions CWE-117/CWE-117.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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}")
42 changes: 28 additions & 14 deletions CWE-117/README.md
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -22,21 +32,23 @@ 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:
isKeywordFound = True
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": [],
Expand All @@ -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;-><init>()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
```
17 changes: 17 additions & 0 deletions CWE-20/CWE-20.py
Original file line number Diff line number Diff line change
@@ -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}")
83 changes: 83 additions & 0 deletions CWE-20/README.md
Original file line number Diff line number Diff line change
@@ -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
```
18 changes: 18 additions & 0 deletions CWE-20/openUrlThatUserInput.json
Original file line number Diff line number Diff line change
@@ -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": []
}
8 changes: 4 additions & 4 deletions CWE-22/CWE-22.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,17 @@
quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance)

for accessExternalDir in quarkResult.behaviorOccurList:

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

if quarkResult.isHardcoded(filePath):
continue

caller = accessExternalDir.methodCaller
strMatchingAPIs = [
api for api in STRING_MATCHING_API if quarkResult.findMethodInCaller(
caller, api)
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}")
64 changes: 41 additions & 23 deletions CWE-22/README.md
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -32,25 +57,25 @@ ruleInstance = Rule(RULE_PATH)
quarkResult = runQuarkAnalysis(SAMPLE_PATH, ruleInstance)

for accessExternalDir in quarkResult.behaviorOccurList:

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

if quarkResult.isHardcoded(filePath):
continue

caller = accessExternalDir.methodCaller
strMatchingAPIs = [
api for api in STRING_MATCHING_API if quarkResult.findMethodInCaller(
caller, api)
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": [],
Expand All @@ -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;
```
14 changes: 9 additions & 5 deletions CWE-23/CWE-23.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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}")
Loading
Loading