Skip to content

Instantly share code, notes, and snippets.

@jjxtra
Created September 10, 2019 00:17
Show Gist options
  • Save jjxtra/def8cb95ecac8f88eda826ef8b4131c5 to your computer and use it in GitHub Desktop.
Save jjxtra/def8cb95ecac8f88eda826ef8b4131c5 to your computer and use it in GitHub Desktop.
Cloudflare IApplicationBuilder forward header and proxy security
private static string[] GetStrings(string url)
{
return new WebClient().DownloadString(url).Split('\n').Select(s => s.Trim()).ToArray();
}
private static string[] GetCloudflareIP()
{
try
{
return GetStrings("https://www.cloudflare.com/ips-v4").Union(GetStrings("https://www.cloudflare.com/ips-v6")).ToArray();
}
catch
{
return @"173.245.48.0/20
103.21.244.0/22
103.22.200.0/22
103.31.4.0/22
141.101.64.0/18
108.162.192.0/18
190.93.240.0/20
188.114.96.0/20
197.234.240.0/22
198.41.128.0/17
162.158.0.0/15
104.16.0.0/12
172.64.0.0/13
131.0.72.0/22
2400:cb00::/32
2606:4700::/32
2803:f800::/32
2405:b500::/32
2405:8100::/32
2a06:98c0::/29
2c0f:f248::/32
".Split('\n').Select(s => s.Trim()).ToArray();
}
}
/// <summary>
/// Add cloudflare forward header options
/// </summary>
/// <param name="builder">Application builder</param>
public static void UseCloudflareForwardHeaderOptions(this IApplicationBuilder builder)
{
ForwardedHeadersOptions options = new ForwardedHeadersOptions
{
ForwardedForHeaderName = "CF_CONNECTING_IP",
ForwardedHeaders = ForwardedHeaders.All
};
try
{
ICollection<string> urls = builder.ServerFeatures.Get<IServerAddressesFeature>().Addresses;
if (urls != null && urls.Count != 0)
{
string[] cloudFlareIP = GetCloudflareIP();
foreach (string line in cloudFlareIP)
{
if (IPAddressRange.TryParse(line, out IPAddressRange range))
{
options.KnownNetworks.Add(new IPNetwork(range.Begin, range.GetPrefixLength()));
}
}
}
}
catch
{
}
builder.UseForwardedHeaders(options);
}
@jjxtra
Copy link
Author

jjxtra commented Sep 10, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment