hacktricks/network-services-pentesting/pentesting-web/nginx.md

279 lines
15 KiB
Markdown
Raw Normal View History

2022-05-08 23:13:03 +00:00
# Nginx
2022-04-28 16:01:33 +00:00
<details>
2023-12-31 01:24:39 +00:00
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
2022-04-28 16:01:33 +00:00
2023-12-31 01:24:39 +00:00
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)
2023-12-31 01:24:39 +00:00
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
2024-02-09 07:15:24 +00:00
* **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)**.**
2023-12-31 01:24:39 +00:00
* **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.
2022-04-28 16:01:33 +00:00
</details>
2022-04-28 16:01:33 +00:00
2024-01-11 13:23:18 +00:00
<figure><img src="/.gitbook/assets/image (2).png" alt=""><figcaption></figcaption></figure>
2022-04-28 16:01:33 +00:00
2024-01-11 13:23:18 +00:00
**Instantly available setup for vulnerability assessment & penetration testing**. Run a full pentest from anywhere with 20+ tools & features that go from recon to reporting. We don't replace pentesters - we develop custom tools, detection & exploitation modules to give them back some time to dig deeper, pop shells, and have fun.
2022-04-28 16:01:33 +00:00
2024-01-11 13:23:18 +00:00
{% embed url="https://pentest-tools.com/" %}
2022-04-28 16:01:33 +00:00
2022-05-08 23:13:03 +00:00
## Missing root location <a href="#missing-root-location" id="missing-root-location"></a>
2024-02-08 21:36:15 +00:00
## **Essentials of Configuring Nginx Root Directory**
When configuring the Nginx server, the **root directive** plays a critical role by defining the base directory from which files are served. Consider the example below:
```bash
server {
root /etc/nginx;
location /hello.txt {
try_files $uri $uri/ =404;
proxy_pass http://127.0.0.1:8080/;
}
}
```
2024-02-08 21:36:15 +00:00
In this configuration, `/etc/nginx` is designated as the root directory. This setup allows access to files within the specified root directory, such as `/hello.txt`. However, it's crucial to note that only a specific location (`/hello.txt`) is defined. There's no configuration for the root location (`location / {...}`). This omission means that the root directive applies globally, enabling requests to the root path `/` to access files under `/etc/nginx`.
2024-02-08 21:36:15 +00:00
A critical security consideration arises from this configuration. A simple `GET` request, like `GET /nginx.conf`, could expose sensitive information by serving the Nginx configuration file located at `/etc/nginx/nginx.conf`. Setting the root to a less sensitive directory, like `/etc`, could mitigate this risk, yet it still may allow unintended access to other critical files, including other configuration files, access logs, and even encrypted credentials used for HTTP basic authentication.
2022-05-08 23:13:03 +00:00
## Alias LFI Misconfiguration <a href="#alias-lfi-misconfiguration" id="alias-lfi-misconfiguration"></a>
2024-02-08 21:36:15 +00:00
In the configuration files of Nginx, a close inspection is warranted for the "location" directives. A vulnerability known as Local File Inclusion (LFI) can be inadvertently introduced through a configuration that resembles the following:
```
location /imgs {
alias /path/images/;
}
```
2024-02-08 21:36:15 +00:00
This configuration is prone to LFI attacks due to the server interpreting requests like `/imgs../flag.txt` as an attempt to access files outside the intended directory, effectively resolving to `/path/images/../flag.txt`. This flaw allows attackers to retrieve files from the server's filesystem that should not be accessible via the web.
2024-02-08 21:36:15 +00:00
To mitigate this vulnerability, the configuration should be adjusted to:
```
location /imgs/ {
alias /path/images/;
}
```
More info: [https://www.acunetix.com/vulnerabilities/web/path-traversal-via-misconfigured-nginx-alias/](https://www.acunetix.com/vulnerabilities/web/path-traversal-via-misconfigured-nginx-alias/)
Accunetix tests:
```
alias../ => HTTP status code 403
alias.../ => HTTP status code 404
alias../../ => HTTP status code 403
alias../../../../../../../../../../../ => HTTP status code 400
alias../ => HTTP status code 403
```
## Unsafe path restriction <a href="#unsafe-variable-use" id="unsafe-variable-use"></a>
Check the following page to learn how to bypass directives like:
```plaintext
location = /admin {
deny all;
}
location = /admin/ {
deny all;
}
```
{% content-ref url="../../pentesting-web/proxy-waf-protections-bypass.md" %}
[proxy-waf-protections-bypass.md](../../pentesting-web/proxy-waf-protections-bypass.md)
{% endcontent-ref %}
2022-05-08 23:13:03 +00:00
## Unsafe variable use <a href="#unsafe-variable-use" id="unsafe-variable-use"></a>
2024-02-08 21:36:15 +00:00
A vulnerability in Nginx configuration is demonstrated by the example below:
```
location / {
return 302 https://example.com$uri;
}
```
2024-02-08 21:36:15 +00:00
The characters \r (Carriage Return) and \n (Line Feed) signify new line characters in HTTP requests, and their URL-encoded forms are represented as `%0d%0a`. Including these characters in a request (e.g., `http://localhost/%0d%0aDetectify:%20clrf`) to a misconfigured server results in the server issuing a new header named `Detectify`. This happens because the $uri variable decodes the URL-encoded new line characters, leading to an unexpected header in the response:
```
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.19.3
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: https://example.com/
Detectify: clrf
```
2022-05-08 23:13:03 +00:00
Learn more about the risks of CRLF injection and response splitting at [https://blog.detectify.com/2019/06/14/http-response-splitting-exploitations-and-mitigations/](https://blog.detectify.com/2019/06/14/http-response-splitting-exploitations-and-mitigations/).
2022-05-08 23:13:03 +00:00
### Any variable
2024-02-08 21:36:15 +00:00
It was discovered that **user-supplied data** might be treated as an **Nginx variable** under certain circumstances. The cause of this behavior remains somewhat elusive, yet it's not rare nor straightforward to verify. This anomaly was highlighted in a security report on HackerOne, which can be viewed [here](https://hackerone.com/reports/370094). Further investigation into the error message led to the identification of its occurrence within the [SSI filter module of Nginx's codebase](https://github.com/nginx/nginx/blob/2187586207e1465d289ae64cedc829719a048a39/src/http/modules/ngx_http_ssi_filter_module.c#L365), pinpointing Server Side Includes (SSI) as the root cause.
2024-02-08 21:36:15 +00:00
To **detect this misconfiguration**, the following command can be executed, which involves setting a referer header to test for variable printing:
2024-02-08 21:36:15 +00:00
```bash
$ curl -H Referer: bar http://localhost/foo$http_referer | grep foobar
```
2024-02-08 21:36:15 +00:00
Scans for this misconfiguration across systems revealed multiple instances where Nginx variables could be printed by a user. However, a decrease in the number of vulnerable instances suggests that efforts to patch this issue have been somewhat successful.
2022-05-08 23:13:03 +00:00
## Raw backend response reading
2024-02-08 21:36:15 +00:00
Nginx offers a feature through `proxy_pass` that allows for the interception of errors and HTTP headers produced by the backend, aiming to hide internal error messages and headers. This is accomplished by Nginx serving custom error pages in response to backend errors. However, challenges arise when Nginx encounters an invalid HTTP request. Such a request gets forwarded to the backend as received, and the backend's raw response is then directly sent to the client without Nginx's intervention.
Consider an example scenario involving a uWSGI application:
2022-04-11 23:27:21 +00:00
```python
def application(environ, start_response):
2024-02-08 21:36:15 +00:00
start_response('500 Error', [('Content-Type', 'text/html'), ('Secret-Header', 'secret-info')])
return [b"Secret info, should not be visible!"]
```
2024-02-08 21:36:15 +00:00
To manage this, specific directives in the Nginx configuration are used:
```
http {
2024-02-08 21:36:15 +00:00
error_page 500 /html/error.html;
proxy_intercept_errors on;
proxy_hide_header Secret-Header;
}
```
2024-02-08 21:36:15 +00:00
- **[proxy_intercept_errors](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_intercept_errors)**: This directive enables Nginx to serve a custom response for backend responses with a status code greater than 300. It ensures that, for our example uWSGI application, a `500 Error` response is intercepted and handled by Nginx.
- **[proxy_hide_header](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_hide_header)**: As the name suggests, this directive hides specified HTTP headers from the client, enhancing privacy and security.
2024-02-08 21:36:15 +00:00
When a valid `GET` request is made, Nginx processes it normally, returning a standard error response without revealing any secret headers. However, an invalid HTTP request bypasses this mechanism, resulting in the exposure of raw backend responses, including secret headers and error messages.
2022-05-08 23:13:03 +00:00
## merge\_slashes set to off
2024-02-08 21:36:15 +00:00
By default, Nginx's **`merge_slashes` directive** is set to **`on`**, which compresses multiple forward slashes in a URL into a single slash. This feature, while streamlining URL processing, can inadvertently conceal vulnerabilities in applications behind Nginx, particularly those prone to local file inclusion (LFI) attacks. Security experts **Danny Robinson and Rotem Bar** have highlighted the potential risks associated with this default behavior, especially when Nginx acts as a reverse-proxy.
2024-02-08 21:36:15 +00:00
To mitigate such risks, it is recommended to **turn the `merge_slashes` directive off** for applications susceptible to these vulnerabilities. This ensures that Nginx forwards requests to the application without altering the URL structure, thereby not masking any underlying security issues.
2022-04-11 23:27:21 +00:00
2024-02-08 21:36:15 +00:00
For more information check [Danny Robinson and Rotem Bar](https://medium.com/appsflyer/nginx-may-be-protecting-your-applications-from-traversal-attacks-without-you-even-knowing-b08f882fd43d).
2022-04-11 23:27:21 +00:00
2024-02-08 21:36:15 +00:00
### **Default Value in Map Directive**
2022-04-11 23:27:21 +00:00
2024-02-08 21:36:15 +00:00
In the **Nginx configuration**, the `map` directive often plays a role in **authorization control**. A common mistake is not specifying a **default** value, which could lead to unauthorized access. For instance:
```yaml
2022-04-11 23:27:21 +00:00
http {
map $uri $mappocallow {
/map-poc/private 0;
/map-poc/secret 0;
/map-poc/public 1;
}
}
```
2024-02-08 21:36:15 +00:00
```yaml
2022-04-11 23:27:21 +00:00
server {
location /map-poc {
if ($mappocallow = 0) {return 403;}
return 200 "Hello. It is private area: $mappocallow";
}
}
```
2024-02-08 21:36:15 +00:00
Without a `default`, a **malicious user** can bypass security by accessing an **undefined URI** within `/map-poc`. [The Nginx manual](https://nginx.org/en/docs/http/ngx_http_map_module.html) advises setting a **default value** to avoid such issues.
2022-04-11 23:27:21 +00:00
2024-02-08 21:36:15 +00:00
### **DNS Spoofing Vulnerability**
2022-04-11 23:27:21 +00:00
2024-02-08 21:36:15 +00:00
DNS spoofing against Nginx is feasible under certain conditions. If an attacker knows the **DNS server** used by Nginx and can intercept its DNS queries, they can spoof DNS records. This method, however, is ineffective if Nginx is configured to use **localhost (127.0.0.1)** for DNS resolution. Nginx allows specifying a DNS server as follows:
2022-04-11 23:27:21 +00:00
2024-02-08 21:36:15 +00:00
```yaml
resolver 8.8.8.8;
2022-04-11 23:27:21 +00:00
```
2024-02-08 21:36:15 +00:00
### **`proxy_pass` and `internal` Directives**
2022-04-11 23:27:21 +00:00
2024-02-08 21:36:15 +00:00
The **`proxy_pass`** directive is utilized for redirecting requests to other servers, either internally or externally. The **`internal`** directive ensures that certain locations are only accessible within Nginx. While these directives are not vulnerabilities by themselves, their configuration requires careful examination to prevent security lapses.
2022-06-19 13:37:58 +00:00
## proxy\_set\_header Upgrade & Connection
If the nginx server is configured to pass the Upgrade and Connection headers an [**h2c Smuggling attack**](../../pentesting-web/h2c-smuggling.md) could be performed to access protected/internal endpoints.
{% hint style="danger" %}
This vulnerability would allow an attacker to **stablish a direct connection with the `proxy_pass` endpoint** (`http://backend:9999` in this case) that whose content is not going to be checked by nginx.
{% endhint %}
Example of vulnerable configuration to steal `/flag` from [here](https://bishopfox.com/blog/h2c-smuggling-request):
```
server {
listen 443 ssl;
server_name localhost;
ssl_certificate /usr/local/nginx/conf/cert.pem;
ssl_certificate_key /usr/local/nginx/conf/privkey.pem;
location / {
proxy_pass http://backend:9999;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
}
location /flag {
deny all;
}
```
{% hint style="warning" %}
Note that even if the `proxy_pass` was pointing to a specific **path** such as `http://backend:9999/socket.io` the connection will be stablished with `http://backend:9999` so you can **contact any other path inside that internal endpoint. So it doesn't matter if a path is specified in the URL of proxy\_pass.**
{% endhint %}
2022-05-08 23:13:03 +00:00
## Try it yourself
Detectify has created a GitHub repository where you can use Docker to set up your own vulnerable Nginx test server with some of the misconfigurations discussed in this article and try finding them yourself!
[https://github.com/detectify/vulnerable-nginx](https://github.com/detectify/vulnerable-nginx)
2022-05-08 23:13:03 +00:00
## Static Analyzer tools
2022-05-08 23:13:03 +00:00
### [GIXY](https://github.com/yandex/gixy)
Gixy is a tool to analyze Nginx configuration. The main goal of Gixy is to prevent security misconfiguration and automate flaw detection.
2022-04-11 23:27:21 +00:00
2022-07-24 19:52:09 +00:00
### [Nginxpwner](https://github.com/stark0de/nginxpwner)
Nginxpwner is a simple tool to look for common Nginx misconfigurations and vulnerabilities.
2022-05-08 23:13:03 +00:00
## References
2022-04-11 23:27:21 +00:00
2022-05-08 23:13:03 +00:00
* [**https://blog.detectify.com/2020/11/10/common-nginx-misconfigurations/**](https://blog.detectify.com/2020/11/10/common-nginx-misconfigurations/)
* [**http://blog.zorinaq.com/nginx-resolver-vulns/**](http://blog.zorinaq.com/nginx-resolver-vulns/)
* [**https://github.com/yandex/gixy/issues/115**](https://github.com/yandex/gixy/issues/115)
2022-04-28 16:01:33 +00:00
2024-01-11 13:23:18 +00:00
<figure><img src="/.gitbook/assets/image (2).png" alt=""><figcaption></figcaption></figure>
2022-04-28 16:01:33 +00:00
2024-01-11 13:23:18 +00:00
**Instantly available setup for vulnerability assessment & penetration testing**. Run a full pentest from anywhere with 20+ tools & features that go from recon to reporting. We don't replace pentesters - we develop custom tools, detection & exploitation modules to give them back some time to dig deeper, pop shells, and have fun.
2022-04-28 16:01:33 +00:00
2024-01-11 13:23:18 +00:00
{% embed url="https://pentest-tools.com/" %}
2022-04-28 16:01:33 +00:00
<details>
2022-04-28 16:01:33 +00:00
2023-12-31 01:24:39 +00:00
<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
2022-04-28 16:01:33 +00:00
2023-12-31 01:24:39 +00:00
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)
2023-12-31 01:24:39 +00:00
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
2024-02-09 07:15:24 +00:00
* **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)**.**
2023-12-31 01:24:39 +00:00
* **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.
2022-04-28 16:01:33 +00:00
</details>