Skip to content

Walk backwards through the ip list to avoid mocking by the client #6

@nickveenhof

Description

@nickveenhof

https://husobee.github.io/golang/ip-address/2015/12/17/remote-ip-go.html mentions:

Instead of walking from the left to right, walk backwards through the number of ip addresses by the number of proxies you have in your environment to the internet. That way, you will be adverse to any mucking with the X-Forwarded-For header by the client.

So the code that he/she suggests is the following:

func getIPAdress(r *http.Request) string {
    for _, h := range []string{"X-Forwarded-For", "X-Real-Ip"} {
        addresses := strings.Split(r.Header.Get(h), ",")
        // march from right to left until we get a public address
        // that will be the address right before our proxy.
        for i := len(addresses) -1 ; i >= 0; i-- {
            ip := addresses[i]
            // header can contain spaces too, strip those out.
            realIP := net.ParseIP(strings.Replace(ip, " ", "", -1))
            if !realIP.IsGlobalUnicast() && !isPrivateSubnet(realIP) {
                // bad address, go to next
                continue
            }
            return ip
        }
    }
    return ""
}

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions