正確使用 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();