-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathTrustedProxiesFetcher.cs
More file actions
84 lines (64 loc) · 2.4 KB
/
TrustedProxiesFetcher.cs
File metadata and controls
84 lines (64 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using IPNetwork = Microsoft.AspNetCore.HttpOverrides.IPNetwork;
namespace OpenShock.Common.Utils;
public static class TrustedProxiesFetcher
{
private static readonly HttpClient Client = new();
public static readonly string[] PrivateNetworks =
[
// Loopback
"127.0.0.0/8",
"::1/128",
"::ffff:127.0.0.0/8",
// Private IPv4
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
// Private IPv6
"fc00::/7",
"fe80::/10",
];
private static readonly IPNetwork[] PrivateNetworksParsed = [.. PrivateNetworks.Select(x => IPNetwork.Parse(x))];
private static readonly char[] NewLineSeperators = ['\r', '\n', '\t'];
private static async Task<IReadOnlyList<IPNetwork>> FetchCloudflareIPs(Uri uri, CancellationToken ct)
{
using var response = await Client.GetAsync(uri, ct);
var stringResponse = await response.Content.ReadAsStringAsync(ct);
return ParseNetworks(stringResponse);
}
private static IPNetwork[] ParseNetworks(string response)
{
var lines = response.Split(NewLineSeperators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var networks = new IPNetwork[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
networks[i] = IPNetwork.Parse(lines[i]);
}
return networks;
}
private static async Task<IPNetwork[]?> FetchCloudflareIPs()
{
try
{
using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); // Don't want to make application startup slow
var ct = cts.Token;
var v4Task = FetchCloudflareIPs(new Uri("https://www.cloudflare.com/ips-v4"), ct);
var v6Task = FetchCloudflareIPs(new Uri("https://www.cloudflare.com/ips-v6"), ct);
await Task.WhenAll(v4Task, v6Task);
return [.. v4Task.Result, .. v6Task.Result];
}
catch (Exception)
{
return null;
}
}
public static async Task<IPNetwork[]> GetTrustedNetworksAsync(bool fetch = true)
{
IPNetwork[]? cfProxies = null;
if (fetch)
{
cfProxies = await FetchCloudflareIPs();
}
cfProxies ??= ParseNetworks(File.ReadAllText("cloudflare-ips.txt"));
return [.. PrivateNetworksParsed, .. cfProxies];
}
}