正确使用 HTTP X FORWARDED FOR

鉴于最新的 httpoxy 漏洞,还有另一个变量,它被广泛滥用。

HTTP_X_FORWARDED_FOR 通常用于检测客户端 IP 地址,但无需任何额外检查,这可能会导致安全问题,尤其是当此 IP 稍后用于身份验证或 SQL 查询而不进行清理时。

大多数可用的代码样本忽略了 HTTP_X_FORWARDED_FOR 实际上可以被视为客户端本身提供的信息这一事实,因此不是检测客户端 IP 地址的可靠来源。一些示例确实添加了关于可能的误用的警告,但仍然没有对代码本身进行任何额外的检查。

这里有一个用 PHP 编写的函数示例,如何检测客户端 IP 地址,如果你知道客户端可能在代理后面,并且你知道该代理可以信任。如果你不知道任何可信代理,则可以使用 REMOTE_ADDR

function get_client_ip()
{
    // Nothing to do without any reliable information
    if (!isset($_SERVER['REMOTE_ADDR'])) {
        return NULL;
    }
    
    // Header that is used by the trusted proxy to refer to
    // the original IP
    $proxy_header = "HTTP_X_FORWARDED_FOR";

    // List of all the proxies that are known to handle 'proxy_header'
    // in known, safe manner
    $trusted_proxies = array("2001:db8::1", "192.168.50.1");

    if (in_array($_SERVER['REMOTE_ADDR'], $trusted_proxies)) {
        
        // Get IP of the client behind trusted proxy
        if (array_key_exists($proxy_header, $_SERVER)) {

            // Header can contain multiple IP-s of proxies that are passed through.
            // Only the IP added by the last proxy (last IP in the list) can be trusted.
            $client_ip = trim(end(explode(",", $_SERVER[$proxy_header])));

            // Validate just in case
            if (filter_var($client_ip, FILTER_VALIDATE_IP)) {
                return $client_ip;
            } else {
                // Validation failed - beat the guy who configured the proxy or
                // the guy who created the trusted proxy list?
                // TODO: some error handling to notify about the need of punishment
            }
        }
    }

    // In all other cases, REMOTE_ADDR is the ONLY IP we can trust.
    return $_SERVER['REMOTE_ADDR'];
}

print get_client_ip();