# Abusing Cloudflare Workers as pass-through proxies (IP rotation, FireProx-style)

{{#include ../../banners/hacktricks-training.md}}

Cloudflare Workers can be deployed as transparent HTTP pass-through proxies where the upstream target URL is supplied by the client. Requests egress from Cloudflare's network so the target observes Cloudflare IPs instead of the client's. This mirrors the well-known FireProx technique on AWS API Gateway, but uses Cloudflare Workers.

### Key capabilities
- Support for all HTTP methods (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD)
- Target can be supplied via query parameter (?url=...), a header (X-Target-URL), or even encoded in the path (e.g., /https://target)
- Headers and body are proxied through with hop-by-hop/header filtering as needed
- Responses are relayed back, preserving status code and most headers
- Optional spoofing of X-Forwarded-For (if the Worker sets it from a user-controlled header)
- Extremely fast/easy rotation by deploying multiple Worker endpoints and fanning out requests

### How it works (flow)
1) Client sends an HTTP request to a Worker URL (`<name>.<account>.workers.dev` or a custom domain route).
2) Worker extracts the target from either a query parameter (?url=...), the X-Target-URL header, or a path segment if implemented.
3) Worker forwards the incoming method, headers, and body to the specified upstream URL (filtering problematic headers).
4) Upstream response is streamed back to the client through Cloudflare; the origin sees Cloudflare egress IPs.

### Worker implementation example
- Reads target URL from query param, header, or path
- Copies a safe subset of headers and forwards the original method/body
- Optionally sets X-Forwarded-For using a user-controlled header (X-My-X-Forwarded-For) or a random IP
- Adds permissive CORS and handles preflight

<details>
<summary>Example Worker (JavaScript) for pass-through proxying</summary>

```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>

### Automating deployment and rotation with FlareProx

FlareProx is a Python tool that uses the Cloudflare API to deploy many Worker endpoints and rotate across them. This provides FireProx-like IP rotation from Cloudflare’s network.

Setup
1) Create a Cloudflare API Token using the “Edit Cloudflare Workers” template and get your Account ID from the dashboard.
2) Configure FlareProx:

```bash
git clone https://github.com/MrTurvey/flareprox
cd flareprox
pip install -r requirements.txt
```

**Create config file flareprox.json:**

```json
{
  "cloudflare": {
    "api_token": "your_cloudflare_api_token",
    "account_id": "your_cloudflare_account_id"
  }
}
```

**CLI usage**

- Create N Worker proxies:
```bash
python3 flareprox.py create --count 2
```
- List endpoints:
```bash
python3 flareprox.py list
```
- Health-test endpoints:
```bash
python3 flareprox.py test
```
- Delete all endpoints:
```bash
python3 flareprox.py cleanup
```

**Routing traffic through a Worker**
- Query parameter form:
```bash
curl "https://your-worker.account.workers.dev?url=https://httpbin.org/ip"
```
- Header form:
```bash
curl -H "X-Target-URL: https://httpbin.org/ip" https://your-worker.account.workers.dev
```
- Path form (if implemented):
```bash
curl https://your-worker.account.workers.dev/https://httpbin.org/ip
```
- Method examples:
```bash
# 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"
```

**`X-Forwarded-For` control**

If the Worker honors `X-My-X-Forwarded-For`, you can influence the upstream `X-Forwarded-For` value:
```bash
curl -H "X-My-X-Forwarded-For: 203.0.113.10" \
     "https://your-worker.account.workers.dev?url=https://httpbin.org/headers"
```

**Programmatic usage**

Use the FlareProx library to create/list/test endpoints and route requests from Python.

<details>
<summary>Python example: Send a POST via a random Worker endpoint</summary>

```python
#!/usr/bin/env python3
from flareprox import FlareProx, FlareProxError
import json

# Initialize
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>

**Burp/Scanner integration**
- Point tooling (for example, Burp Suite) at the Worker URL.
- Supply the real upstream using ?url= or X-Target-URL.
- HTTP semantics (methods/headers/body) are preserved while masking your source IP behind Cloudflare.

**Operational notes and limits**
- 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.
- Use responsibly and only with authorization. Respect ToS and robots.txt.

## References
- [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)

{{#include ../../banners/hacktricks-training.md}}
