CloudFlare, HAProxy and ACLs : how to protect your origin

I'm now using CloudFlare (a CDN service) for which provides various features (Antispam, Web Application Firewall...).

CloudFlare powered

One cool thing : they provide the full IP ranges of their platform so you can easily lock down your origin to only accept connections coming from the CloudFlare network.
Unfortunately, I'm hosting websites that don't use CloudFlare, so I can't put these restrictions directly in my firewall ... so let's have some fun at L7 with HAProxy & ACL feature.

The use of Access Control Lists (ACL) provides a flexible solution to perform content switching and generally to take decisions based on content extracted from the request, the response or any environmental status. You can combine them to decide what to do with an incoming request (block, pass to a backend server ...).
In my case, I want to block all requests not targetted to the hosting platform which are not coming through the CloudFlare network, see below for the corresponding HAProxy configuration section :

frontend HTTP
	# Block all requests not coming from CloudFlare Network
	acl cloudflare_valid_ip src -f /etc/haproxy/cloudflareIPs
	block if !host_hdr_hosting !cloudflare_valid_ip

	use_backend if host_hdr_tuxz
	use_backend if host_hdr_hosting

The "/etc/haproxy/cloudflareIPs" is basically a local copy of, which is updated each time a new IP Range is added. Don't forget to follow updates !

Apache : Inject HTTP response header in a rewrited URL using environment variable

I've spent a few hours looking for a way to inject HTTP response headers in a rewrited URL directly from the Apache configuration.

Here's the trick, in the RewriteRule just set a environment variable, ie: "addheader".
But unfortunately, this one can't be used as-is as a condition in the "Header" directive. In this case you'll need to rely on the presence / absence of the "REDIRECT_addheader" :

RewriteEngine On
RewriteRule ^([A-Z]{2})_([a-z]{2})$  /rewrite.php?a=$1&b=$2 [L,E=addheader:1]
Header set my-header "myvalue" env=REDIRECT_addheader

Puppet Talk @ Journées du Logiciel Libre 2011

Here are the slides of the talk I've given at Journées du Logiciel Libre yesterday in Lyon (Download)