Created
June 12, 2012 15:06
-
-
Save qerub/2918060 to your computer and use it in GitHub Desktop.
[Clojure] Ring middleware for `X-Forwarded-For` [:remote-addr rewrite]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (ns ring.middleware.x-forwarded-for | |
| (:use [clojure.string :only (split)])) | |
| (defn wrap-x-forwarded-for [handler] | |
| (fn [request] | |
| (if-let [xff (get-in request [:headers "x-forwarded-for"])] | |
| (handler (assoc request :remote-addr (last (split xff #"\s*,\s*")))) | |
| (handler request)))) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@kaiwaldron: Thanks, that's a good warning.
X-Forwarded-Foris tricky since it's an in-band signal about an out-of-band/meta concept (the client IP address of the HTTP request). I think I choselastand notfirstwhen I created this gist 9 years ago because it contains the address added by the last proxy server in the chain that is often a reverse proxy just in front of the application and the only one that can be trusted. One risk of just switching tofirstis that a malicious client might send aX-Forwarded-Forwith a fake address that propagates all the way to the application that then trusts the fake address. Ideally your edge proxy server should stripX-Forwarded-Forcoming from the internet (as you can't trust it). Many web framework's include a configuration parameter to control which proxy servers (identified by IP address) to trust, e.g.server.tomcat.remoteip.internal-proxiesin Spring Boot. I'm writing this just to make sure that nobody reads your tip and switches tofirstwithout having the full picture and investigating how their proxy servers behave.