Abusar de Cloudflare Workers como pass-through proxies (rotación de IP, estilo FireProx)
Tip
Aprende y practica AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Aprende y practica GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Aprende y practica Az Hacking:HackTricks Training Azure Red Team Expert (AzRTE)
Apoya a HackTricks
- Consulta los subscription plans!
- Únete al 💬 Discord group o al telegram group o síguenos en Twitter 🐦 @hacktricks_live.
- Comparte trucos de hacking enviando PRs a los HackTricks y HackTricks Cloud github repos.
Cloudflare Workers pueden desplegarse como proxies HTTP transparentes de pass-through donde la URL objetivo upstream la suministra el cliente. Las solicitudes salen desde la red de Cloudflare, por lo que el objetivo observa las IPs de Cloudflare en lugar de las del cliente. Esto refleja la conocida técnica FireProx en AWS API Gateway, pero usando Cloudflare Workers.
Key capabilities
- Soporta todos los métodos HTTP (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD)
- La URL de destino puede suministrarse mediante un parámetro de consulta (?url=…), un encabezado (X-Target-URL), o incluso codificada en la ruta (p.ej., /https://target)
- Los headers y el body se proxian a través con filtrado de hop-by-hop/encabezados según sea necesario
- Las respuestas se relayan de vuelta, preservando el código de estado y la mayoría de los encabezados
- Suplantación opcional de X-Forwarded-For (si el Worker lo establece desde un encabezado controlado por el usuario)
- Rotación extremadamente rápida/fácil desplegando múltiples endpoints de Worker y repartiendo las solicitudes
How it works (flow)
- El cliente envía una petición HTTP a una URL de Worker (
<name>.<account>.workers.devo una ruta de dominio personalizado). - El Worker extrae la URL de destino desde un parámetro de consulta (?url=…), el encabezado X-Target-URL, o un segmento de la ruta si está implementado.
- El Worker reenvía el método, los encabezados y el body entrantes a la URL upstream especificada (filtrando encabezados problemáticos).
- La respuesta del upstream se transmite de vuelta al cliente a través de Cloudflare; el origen ve las IPs de salida de Cloudflare.
### Worker implementation example
- Lee la URL de destino desde el parámetro de consulta, un encabezado o la ruta
- Copia un subconjunto seguro de encabezados y reenvía el método/body original
- Opcionalmente establece X-Forwarded-For usando un encabezado controlado por el usuario (X-My-X-Forwarded-For) o una IP aleatoria
- Añade CORS permisivo y gestiona preflight
Ejemplo de Worker (JavaScript) para pass-through proxying
```javascript /** * Minimal Worker pass-through proxy * - Target URL from ?url=, X-Target-URL, or /https://... * - Proxies method/headers/body to upstream; relays response */ addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) })async function handleRequest(request) { try { const url = new URL(request.url) const targetUrl = getTargetUrl(url, request.headers)
if (!targetUrl) { return errorJSON(‘No target URL specified’, 400, { usage: { query_param: ‘?url=https://example.com’, header: ‘X-Target-URL: https://example.com’, path: ‘/https://example.com’ } }) }
let target try { target = new URL(targetUrl) } catch (e) { return errorJSON(‘Invalid target URL’, 400, { provided: targetUrl }) }
// Forward original query params except control ones const passthru = new URLSearchParams() for (const [k, v] of url.searchParams) { if (![‘url’, ‘_cb’, ‘_t’].includes(k)) passthru.append(k, v) } if (passthru.toString()) target.search = passthru.toString()
// Build proxied request const proxyReq = buildProxyRequest(request, target) const upstream = await fetch(proxyReq)
return buildProxyResponse(upstream, request.method) } catch (error) { return errorJSON(‘Proxy request failed’, 500, { message: error.message, timestamp: new Date().toISOString() }) } }
function getTargetUrl(url, headers) { let t = url.searchParams.get(‘url’) || headers.get(‘X-Target-URL’) if (!t && url.pathname !== ‘/’) { const p = url.pathname.slice(1) if (p.startsWith(‘http’)) t = p } return t }
function buildProxyRequest(request, target) { const h = new Headers() const allow = [ ‘accept’,‘accept-language’,‘accept-encoding’,‘authorization’, ‘cache-control’,‘content-type’,‘origin’,‘referer’,‘user-agent’ ] for (const [k, v] of request.headers) { if (allow.includes(k.toLowerCase())) h.set(k, v) } h.set(‘Host’, target.hostname)
// Optional: spoof X-Forwarded-For if provided const spoof = request.headers.get(‘X-My-X-Forwarded-For’) h.set(‘X-Forwarded-For’, spoof || randomIP())
return new Request(target.toString(), { method: request.method, headers: h, body: [‘GET’,‘HEAD’].includes(request.method) ? null : request.body }) }
function buildProxyResponse(resp, method) { const h = new Headers() for (const [k, v] of resp.headers) { if (![‘content-encoding’,‘content-length’,‘transfer-encoding’].includes(k.toLowerCase())) { h.set(k, v) } } // Permissive CORS for tooling convenience h.set(‘Access-Control-Allow-Origin’, ‘’) h.set(‘Access-Control-Allow-Methods’, ‘GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD’) h.set(‘Access-Control-Allow-Headers’, ‘’)
if (method === ‘OPTIONS’) return new Response(null, { status: 204, headers: h }) return new Response(resp.body, { status: resp.status, statusText: resp.statusText, headers: h }) }
function errorJSON(msg, status=400, extra={}) { return new Response(JSON.stringify({ error: msg, …extra }), { status, headers: { ‘Content-Type’: ‘application/json’ } }) }
function randomIP() { return [1,2,3,4].map(() => Math.floor(Math.random()*255)+1).join(‘.’) }
</details>
### Automatizando despliegue y rotación con FlareProx
FlareProx es una herramienta en Python que usa la Cloudflare API para desplegar muchos Worker endpoints y rotar entre ellos. Esto proporciona rotación de IP estilo FireProx desde la red de Cloudflare.
Configuración
1) Crea un Cloudflare API Token usando la plantilla “Edit Cloudflare Workers” y obtén tu Account ID desde el panel de control.
2) Configura FlareProx:
```bash
git clone https://github.com/MrTurvey/flareprox
cd flareprox
pip install -r requirements.txt
Crear archivo de configuración flareprox.json:
{
"cloudflare": {
"api_token": "your_cloudflare_api_token",
"account_id": "your_cloudflare_account_id"
}
}
Uso de la CLI
- Crear N Worker proxies:
python3 flareprox.py create --count 2
- Listar endpoints:
python3 flareprox.py list
- Prueba de salud endpoints:
python3 flareprox.py test
- Eliminar todos los endpoints:
python3 flareprox.py cleanup
Enrutando tráfico a través de un Worker
- Formulario de parámetros de consulta:
curl "https://your-worker.account.workers.dev?url=https://httpbin.org/ip"
- Formulario de encabezado:
curl -H "X-Target-URL: https://httpbin.org/ip" https://your-worker.account.workers.dev
- Formato de path (si está implementado):
curl https://your-worker.account.workers.dev/https://httpbin.org/ip
- Ejemplos de métodos:
# GET
curl "https://your-worker.account.workers.dev?url=https://httpbin.org/get"
# POST (form)
curl -X POST -d "username=admin" \
"https://your-worker.account.workers.dev?url=https://httpbin.org/post"
# PUT (JSON)
curl -X PUT -d '{"username":"admin"}' -H "Content-Type: application/json" \
"https://your-worker.account.workers.dev?url=https://httpbin.org/put"
# DELETE
curl -X DELETE \
"https://your-worker.account.workers.dev?url=https://httpbin.org/delete"
Control de X-Forwarded-For
Si el Worker respeta X-My-X-Forwarded-For, puedes influir en el valor upstream de X-Forwarded-For:
curl -H "X-My-X-Forwarded-For: 203.0.113.10" \
"https://your-worker.account.workers.dev?url=https://httpbin.org/headers"
Uso programático
Usa la biblioteca FlareProx para crear/listar/probar endpoints y enrutar solicitudes desde Python.
Ejemplo en Python: Enviar un POST a través de un endpoint aleatorio de Worker
```python #!/usr/bin/env python3 from flareprox import FlareProx, FlareProxError import jsonInitialize
flareprox = FlareProx(config_file=“flareprox.json”) if not flareprox.is_configured: print(“FlareProx not configured. Run: python3 flareprox.py config”) exit(1)
Ensure endpoints exist
endpoints = flareprox.sync_endpoints() if not endpoints: print(“Creating proxy endpoints…”) flareprox.create_proxies(count=2)
Make a POST request through a random endpoint
try: post_data = json.dumps({ “username”: “testuser”, “message”: “Hello from FlareProx!”, “timestamp”: “2025-01-01T12:00:00Z” })
headers = { “Content-Type”: “application/json”, “User-Agent”: “FlareProx-Client/1.0” }
response = flareprox.redirect_request( target_url=“https://httpbin.org/post”, method=“POST”, headers=headers, data=post_data )
if response.status_code == 200: result = response.json() print(“✓ POST successful via FlareProx”) print(f“Origin IP: {result.get(‘origin’, ‘unknown’)}“) print(f“Posted data: {result.get(‘json’, {})}”) else: print(f“Request failed with status: {response.status_code}“)
except FlareProxError as e: print(f“FlareProx error: {e}“) except Exception as e: print(f“Request error: {e}”)
</details>
**Integración con Burp/Scanner**
- Apunta las herramientas (por ejemplo, Burp Suite) a la URL del Worker.
- Proporciona el upstream real usando ?url= o X-Target-URL.
- La semántica HTTP (methods/headers/body) se preserva mientras enmascaras tu IP de origen detrás de Cloudflare.
**Notas operativas y límites**
- Cloudflare Workers Free plan allows roughly 100,000 requests/day per account; use multiple endpoints to distribute traffic if needed.
- Workers run on Cloudflare’s network; many targets will only see Cloudflare IPs/ASN, which can bypass naive IP allow/deny lists or geo heuristics.
- Usa responsablemente y solo con autorización. Respeta ToS y robots.txt.
## Referencias
- [FlareProx (Cloudflare Workers pass-through/rotation)](https://github.com/MrTurvey/flareprox)
- [Cloudflare Workers fetch() API](https://developers.cloudflare.com/workers/runtime-apis/fetch/)
- [Cloudflare Workers pricing and free tier](https://developers.cloudflare.com/workers/platform/pricing/)
- [FireProx (AWS API Gateway)](https://github.com/ustayready/fireprox)
> [!TIP]
> Aprende y practica AWS Hacking:<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://hacktricks-training.com/courses/arte)<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> Aprende y practica GCP Hacking: <img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training GCP Red Team Expert (GRTE)**](https://hacktricks-training.com/courses/grte)<img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> Aprende y practica Az Hacking: <img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training Azure Red Team Expert (AzRTE)**](https://hacktricks-training.com/courses/azrte)<img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
>
> <details>
>
> <summary>Apoya a HackTricks</summary>
>
> - Consulta los [**subscription plans**](https://github.com/sponsors/carlospolop)!
> - **Únete al** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) o al [**telegram group**](https://t.me/peass) o **síguenos** en **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
> - **Comparte trucos de hacking enviando PRs a los** [**HackTricks**](https://github.com/carlospolop/hacktricks) y [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
>
> </details>
HackTricks Cloud

