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
- Configure IIS to Read the Remote IP from a Specific Header (Not Recommended):
- Open IIS Manager.
- Select your server in the Connections pane.
- Double-click “Server Farms” in the Features View.
- Select the relevant site.
- In the Actions pane, click “Edit Feature Settings…”
- Under “HTTP Response Headers”, find “Remote IP Address”.
- Change the header name to
X-Forwarded-For(or whatever your proxy uses).
Warning: This is highly insecure. It’s easily bypassed and should only be used for testing or in very controlled environments.
- This is the correct approach. Configure your proxy (e.g., Nginx, Apache, Azure Load Balancer) to forward the real client IP address in a trusted header.
- Ensure the proxy adds/updates the
X-Forwarded-Forheader correctly and that IIS trusts only this proxy’s IP.
Example Nginx configuration:
proxy_set_header X-Real-IP $remote_addr;
- A WAF (e.g., Azure WAF, Cloudflare) sits in front of your IIS server and inspects traffic before it reaches the server.
- WAFs can reliably identify and block malicious IPs based on various criteria, including IP reputation and patterns.
- They also handle header spoofing attacks effectively.
- Open IIS Manager.
- Select your server.
- Double-click “IP Address and Domain Restrictions” in the Features View.
- Click “Add Allow Entry…” to allow trusted proxy IPs.
- 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.