Blog | G5 Cyber Security

IIS: Block Real IP with X-Forwarded-For

TL;DR

You can’t reliably block a true IP address using only the X-Forwarded-For header in IIS. Attackers can easily spoof this header. You need to configure your server and/or load balancer to handle the actual client IP, or use a Web Application Firewall (WAF).

Understanding the Problem

The X-Forwarded-For header is added by proxies (like reverse proxies or load balancers) to indicate the original client’s IP address. IIS sees the proxy’s IP, not the user’s. Blocking based on X-Forwarded-For alone is insecure because anyone can set that header.

Solution Steps

  1. Configure IIS to Read the Remote IP from a Specific Header (Not Recommended):

Warning: This is highly insecure. It’s easily bypassed and should only be used for testing or in very controlled environments.

  • Configure Your Proxy/Load Balancer to Pass the Real IP:
  • Example Nginx configuration:

    proxy_set_header X-Real-IP $remote_addr;
  • Use a Web Application Firewall (WAF):
  • IP Restriction in IIS (After Correct Proxy Configuration):
    1. Open IIS Manager.
    2. Select your server.
    3. Double-click “IP Address and Domain Restrictions” in the Features View.
    4. Click “Add Allow Entry…” to allow trusted proxy IPs.
    5. Click “Add Deny Entry…” to block specific IP addresses or ranges.

    Important: Only block IPs after you’ve verified that IIS is receiving the correct client IP address from your trusted proxy.

    Code Example (Checking Remote IP in Application Code)

    You can check the remote IP within your application code. This assumes your proxy has correctly set X-Forwarded-For and you’ve configured IIS to read it (though, again, this is not a secure solution on its own).

    // C# example
    string ipAddress = Request.Headers["X-Forwarded-For"];
    if (string.IsNullOrEmpty(ipAddress)) {
        ipAddress = Request.RemoteAddr;
    }
    

    Summary

    Blocking based on X-Forwarded-For alone is insecure. The best approach is to configure your proxy/load balancer correctly and use a WAF for robust protection against IP spoofing and other attacks.

    Exit mobile version