Skip to content
This repository was archived by the owner on Nov 1, 2023. It is now read-only.

Manage invalid IP address in X-Forwarded-For header #152

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions WebApiThrottle.Tests/IpAddressUtilTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,13 @@ public void IsPrivateIpAddress_PublicIpAddressWithInitialSpace_ReturnsFalse()

Assert.Equal(false, result);
}

[Fact]
public void IsPrivateIpAddress_InvalidAddress_ReturnsTrue()
{
bool result = IpAddressUtil.IsPrivateIpAddress("INVALIDIP");

Assert.True(result);
}
}
}
9 changes: 7 additions & 2 deletions WebApiThrottle/Net/IpAddressUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public static bool ContainsIp(List<string> ipRules, string clientIp, out string
return false;
}

private static readonly IPAddress _defaultIPAddress = new IPAddress(new byte[] { 169, 254, 0, 0 });

public static IPAddress ParseIp(string ipAddress)
{
ipAddress = ipAddress.Trim();
Expand All @@ -59,7 +61,10 @@ public static IPAddress ParseIp(string ipAddress)
ipAddress = ipAddress.Substring(0, portDelimiterPos);
}

return IPAddress.Parse(ipAddress);
// If IPAddress can not be parsed, we return a default Link-local address.
// Sometimes, X-Forwarded-For headers have non valid IP Address
IPAddress address;
return (IPAddress.TryParse(ipAddress, out address) ? address : _defaultIPAddress);
}

public static bool IsPrivateIpAddress(string ipAddress)
Expand Down Expand Up @@ -97,4 +102,4 @@ public static bool IsPrivateIpAddress(string ipAddress)
}
}
}
}
}