Repository navigation
Expand file tree
/
Copy pathRDAPClient.cs
More file actions
492 lines (408 loc) · 19.4 KB
/
Copy pathRDAPClient.cs
File metadata and controls
492 lines (408 loc) · 19.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using NETworkManager.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace NETworkManager.Models.RDAP;
/// <summary>
/// Client for the Registration Data Access Protocol (RDAP, RFC 7480, RFC 9082, RFC 9083, RFC 9224).
/// </summary>
public class RDAPClient : SingletonBase<RDAPClient>
{
#region Variables
private static readonly ILog Log = LogManager.GetLogger(typeof(RDAPClient));
private const string RDAPMediaType = "application/rdap+json";
/// <summary>
/// Maximum number of redirects to follow for one request.
/// </summary>
private const int MaxRedirects = 5;
/// <summary>
/// Maximum size of a response (after decompression). Real RDAP responses are well below 1 MB. Larger responses
/// are rejected, so a broken or malicious server (e.g. a referral target) cannot exhaust the memory.
/// </summary>
public const long MaxResponseSize = 10 * 1024 * 1024;
private static readonly JsonSerializerSettings SerializerSettings = new()
{
// Keep dates as strings. Newtonsoft would otherwise convert them to DateTime and lose the offset.
DateParseHandling = DateParseHandling.None,
MissingMemberHandling = MissingMemberHandling.Ignore,
Converters = [new RDAPStringListConverter()],
// Ignore members with an unexpected type (e.g. a number sent as string) instead of failing the whole response.
Error = (_, args) => args.ErrorContext.Handled = true
};
private readonly HttpClient _client;
/// <summary>
/// Client for registrar referrals. The URL is sent by the registry and therefore untrusted. Direct connections
/// are only made to the addresses that were checked when connecting (no second DNS lookup, see
/// <see cref="ConnectToPublicAddressAsync" />), which prevents DNS rebinding to local or private addresses.
/// </summary>
private readonly HttpClient _referralClient;
#endregion
#region Constructor
public RDAPClient()
{
// Redirects are followed manually to limit the hops, detect loops and prevent HTTPS to HTTP downgrades.
_client = new HttpClient(new HttpClientHandler
{
AllowAutoRedirect = false,
AutomaticDecompression = DecompressionMethods.All
})
{
Timeout = Timeout.InfiniteTimeSpan
};
_referralClient = new HttpClient(new SocketsHttpHandler
{
AllowAutoRedirect = false,
AutomaticDecompression = DecompressionMethods.All,
ConnectCallback = ConnectToPublicAddressAsync
})
{
Timeout = Timeout.InfiniteTimeSpan
};
foreach (var client in new[] { _client, _referralClient })
{
client.MaxResponseContentBufferSize = MaxResponseSize;
client.DefaultRequestHeaders.UserAgent.ParseAdd("NETworkManager");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(RDAPMediaType));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
#endregion
#region Public methods
/// <summary>
/// Executes an RDAP query.
/// </summary>
/// <param name="query">Query to execute (see <see cref="RDAPQueryParser" />).</param>
/// <param name="cacheDirectory">Directory where the IANA bootstrap files are cached.</param>
/// <param name="timeout">Timeout for each request.</param>
/// <param name="followReferral">Follow the referral to the registrar's RDAP record (domain queries only).</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Result of the query.</returns>
/// <exception cref="RDAPException">If the query fails.</exception>
public async Task<RDAPResult> QueryAsync(RDAPQuery query, string cacheDirectory, TimeSpan timeout,
bool followReferral, CancellationToken cancellationToken = default)
{
var bootstrapService = RDAPBootstrapService.GetInstance();
// TLD queries go directly to IANA and don't need the bootstrap files.
if (query.Type != RDAPQueryType.TLD)
await bootstrapService.EnsureUpToDateAsync(cacheDirectory, cancellationToken).ConfigureAwait(false);
var baseUrls = bootstrapService.GetBaseUrls(query);
RDAPException lastNetworkError = null;
// Try the next server only on network errors. Any HTTP answer is authoritative for the query.
foreach (var baseUrl in baseUrls)
{
try
{
var result = await GetAsync(query, baseUrl + query.PathSegment, timeout, cancellationToken)
.ConfigureAwait(false);
if (followReferral && query.Type == RDAPQueryType.Domain)
await FollowReferralAsync(result, timeout, cancellationToken).ConfigureAwait(false);
return result;
}
catch (RDAPException ex) when (ex.Kind == RDAPErrorKind.Network)
{
Log.Warn($"RDAP request to {ex.RequestUrl} failed: {ex.Message}");
lastNetworkError = ex;
}
}
throw lastNetworkError ?? new RDAPException(RDAPErrorKind.NoServer);
}
/// <summary>
/// Gets the link to the registrar's RDAP record from a domain response. Links with "rel" containing "related"
/// and an RDAP media type are preferred, otherwise "related" links that look like an RDAP URL are used. Links
/// pointing to the response itself are skipped (some registries add a "related" link to themselves).
/// </summary>
/// <param name="response">Domain response.</param>
/// <param name="requestUrl">URL of the request that returned the response.</param>
/// <returns>URL of the referral, or null if there is none.</returns>
public static string GetReferralUrl(RDAPResponse response, string requestUrl)
{
var selfUrls = new List<string> { requestUrl };
selfUrls.AddRange(response.Links?.Where(x => HasRel(x, "self")).Select(x => x.Href) ?? []);
var candidates = response.Links?
.Where(x => HasRel(x, "related") && IsHttpUrl(x.Href) &&
!selfUrls.Any(self => UrlEquals(self, x.Href)))
.ToList() ?? [];
return (candidates.FirstOrDefault(x => IsRDAPMediaType(x.Type)) ??
candidates.FirstOrDefault(x => string.IsNullOrEmpty(x.Type) && HasRDAPPath(x.Href)))?.Href;
}
#endregion
#region Methods
private async Task FollowReferralAsync(RDAPResult result, TimeSpan timeout, CancellationToken cancellationToken)
{
var referralUrl = GetReferralUrl(result.Response, result.RequestUrl);
if (referralUrl == null)
return;
try
{
result.Referral = await GetAsync(result.Query, referralUrl, timeout, cancellationToken, true)
.ConfigureAwait(false);
}
catch (RDAPException ex)
{
if (ex.Kind is RDAPErrorKind.InsecureReferral or RDAPErrorKind.PrivateAddress)
Log.Warn($"Referral to the registrar not followed ({ex.Kind}): {ex.RequestUrl}");
// The registry response is still valid if the registrar fails.
result.ReferralError = ex;
}
}
/// <summary>
/// Sends a GET request, follows redirects and parses the response.
/// </summary>
/// <param name="query">Query.</param>
/// <param name="url">URL to request.</param>
/// <param name="timeout">Timeout for each request.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="isReferral">
/// The URL comes from a response (registrar referral) and is untrusted: only HTTPS and no local or private
/// addresses are allowed, for the referral and each redirect.
/// </param>
private async Task<RDAPResult> GetAsync(RDAPQuery query, string url, TimeSpan timeout,
CancellationToken cancellationToken, bool isReferral = false)
{
var visited = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var currentUrl = new Uri(url);
for (var redirects = 0; ; redirects++)
{
if (!visited.Add(currentUrl.AbsoluteUri) || redirects > MaxRedirects)
throw new RDAPException(RDAPErrorKind.TooManyRedirects) { RequestUrl = currentUrl.AbsoluteUri };
if (isReferral)
await ValidateReferralTargetAsync(currentUrl, cancellationToken).ConfigureAwait(false);
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutSource.CancelAfter(timeout);
HttpResponseMessage response;
string body;
try
{
response = await (isReferral ? _referralClient : _client).GetAsync(currentUrl, timeoutSource.Token)
.ConfigureAwait(false);
body = await response.Content.ReadAsStringAsync(timeoutSource.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (HttpRequestException ex) when (ex.InnerException is RDAPException inner)
{
// Blocked by ConnectToPublicAddressAsync.
throw new RDAPException(inner.Kind, inner.Message, ex) { RequestUrl = currentUrl.AbsoluteUri };
}
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException)
{
var message = ex is OperationCanceledException ? $"Timeout after {timeout.TotalSeconds} s." : ex.Message;
throw new RDAPException(RDAPErrorKind.Network, message, ex) { RequestUrl = currentUrl.AbsoluteUri };
}
using (response)
{
if (IsRedirect(response.StatusCode) && response.Headers.Location != null)
{
// The server returns the complete URL of the query (RFC 7480 5.2).
var location = response.Headers.Location.IsAbsoluteUri
? response.Headers.Location
: new Uri(currentUrl, response.Headers.Location);
if (currentUrl.Scheme == Uri.UriSchemeHttps && location.Scheme != Uri.UriSchemeHttps)
throw new RDAPException(RDAPErrorKind.InsecureRedirect, location.AbsoluteUri)
{ RequestUrl = currentUrl.AbsoluteUri };
currentUrl = location;
continue;
}
if (response.StatusCode != HttpStatusCode.OK)
throw CreateHttpException(response, body, currentUrl.AbsoluteUri);
return CreateResult(query, currentUrl.AbsoluteUri, body);
}
}
}
/// <summary>
/// Checks the target of a referral, which is sent by the registry and therefore untrusted. Only HTTPS is allowed
/// (no downgrade to plain text) and the host must not resolve to a local or private address, so a response
/// cannot make the client send requests into the local network.
/// </summary>
private static async Task ValidateReferralTargetAsync(Uri url, CancellationToken cancellationToken)
{
if (url.Scheme != Uri.UriSchemeHttps)
throw new RDAPException(RDAPErrorKind.InsecureReferral, url.AbsoluteUri) { RequestUrl = url.AbsoluteUri };
IPAddress[] addresses;
if (url.IsLoopback)
{
addresses = [IPAddress.Loopback];
}
else if (IPAddress.TryParse(url.DnsSafeHost, out var ipAddress))
{
addresses = [ipAddress];
}
else
{
try
{
addresses = await Dns.GetHostAddressesAsync(url.DnsSafeHost, cancellationToken).ConfigureAwait(false);
}
catch (SocketException ex)
{
// Fail closed: a referral is only followed if its address could be checked.
throw new RDAPException(RDAPErrorKind.Network, ex.Message, ex) { RequestUrl = url.AbsoluteUri };
}
}
if (addresses.Any(IsLocalOrPrivateAddress))
throw new RDAPException(RDAPErrorKind.PrivateAddress, url.AbsoluteUri) { RequestUrl = url.AbsoluteUri };
}
/// <summary>
/// Connect callback of the referral client: resolves the host once, checks all addresses and connects to exactly
/// these addresses, so a second DNS answer (DNS rebinding) cannot redirect the connection to a local or private
/// address. TLS still validates the certificate against the host name. If a proxy is used, the connection goes to
/// the proxy, which resolves the target itself; in this case the check in
/// <see cref="ValidateReferralTargetAsync" /> applies.
/// </summary>
private static async ValueTask<Stream> ConnectToPublicAddressAsync(SocketsHttpConnectionContext context,
CancellationToken cancellationToken)
{
var endPoint = context.DnsEndPoint;
// A tunnel (CONNECT) to the configured proxy. Referrals only use HTTPS, so a proxied connection is always a
// tunnel.
var isProxy = context.InitialRequestMessage.Method == HttpMethod.Connect;
var addresses = IPAddress.TryParse(endPoint.Host, out var ipAddress)
? [ipAddress]
: await Dns.GetHostAddressesAsync(endPoint.Host, cancellationToken).ConfigureAwait(false);
if (!isProxy && (addresses.Length == 0 || addresses.Any(IsLocalOrPrivateAddress)))
throw new RDAPException(RDAPErrorKind.PrivateAddress, endPoint.Host);
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
try
{
await socket.ConnectAsync(addresses, endPoint.Port, cancellationToken).ConfigureAwait(false);
return new NetworkStream(socket, true);
}
catch
{
socket.Dispose();
throw;
}
}
/// <summary>
/// Loopback, private (RFC 1918, RFC 4193), shared (RFC 6598), link-local, unspecified and multicast addresses.
/// </summary>
private static bool IsLocalOrPrivateAddress(IPAddress address)
{
if (address.IsIPv4MappedToIPv6)
address = address.MapToIPv4();
if (IPAddress.IsLoopback(address))
return true;
var bytes = address.GetAddressBytes();
if (address.AddressFamily == AddressFamily.InterNetwork)
return bytes[0] is 0 or 10 or >= 224 ||
bytes[0] == 172 && (bytes[1] & 0xF0) == 16 ||
bytes[0] == 192 && bytes[1] == 168 ||
bytes[0] == 169 && bytes[1] == 254 ||
bytes[0] == 100 && (bytes[1] & 0xC0) == 64;
return address.Equals(IPAddress.IPv6Any) || address.IsIPv6LinkLocal || address.IsIPv6SiteLocal ||
address.IsIPv6Multicast || (bytes[0] & 0xFE) == 0xFC;
}
private static bool IsRedirect(HttpStatusCode statusCode)
{
return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther
or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect;
}
private static RDAPResult CreateResult(RDAPQuery query, string url, string body)
{
RDAPResponse response;
string formattedJson;
try
{
using var reader = new JsonTextReader(new StringReader(body))
{
DateParseHandling = DateParseHandling.None,
FloatParseHandling = FloatParseHandling.Decimal
};
var token = JToken.ReadFrom(reader);
if (token is not JObject)
throw new JsonException("The response is not a JSON object.");
formattedJson = token.ToString(Formatting.Indented);
response = JsonConvert.DeserializeObject<RDAPResponse>(body, SerializerSettings);
}
catch (JsonException ex)
{
throw new RDAPException(RDAPErrorKind.InvalidResponse, ex.Message, ex) { RequestUrl = url };
}
return new RDAPResult
{
Query = query,
RequestUrl = url,
RawJson = body,
FormattedJson = formattedJson,
Response = response
};
}
private static RDAPException CreateHttpException(HttpResponseMessage response, string body, string url)
{
var kind = response.StatusCode switch
{
HttpStatusCode.NotFound => RDAPErrorKind.NotFound,
HttpStatusCode.BadRequest => RDAPErrorKind.BadRequest,
HttpStatusCode.TooManyRequests => RDAPErrorKind.RateLimited,
HttpStatusCode.NotImplemented => RDAPErrorKind.NotImplemented,
_ => RDAPErrorKind.HttpError
};
// Use the RDAP error response (RFC 9083 6), if the server sent one.
RDAPResponse error = null;
try
{
if (!string.IsNullOrWhiteSpace(body) && body.TrimStart().StartsWith('{'))
error = JsonConvert.DeserializeObject<RDAPResponse>(body, SerializerSettings);
}
catch (JsonException)
{
// Not an RDAP error response (e.g. an HTML error page).
}
var description = error?.Description?.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
return new RDAPException(kind, $"{(int)response.StatusCode} {response.ReasonPhrase}")
{
StatusCode = (int)response.StatusCode,
ErrorTitle = error?.Title,
ErrorDescription = description is { Count: > 0 } ? string.Join(" ", description) : null,
RetryAfter = GetRetryAfter(response.Headers.RetryAfter),
RequestUrl = url
};
}
private static TimeSpan? GetRetryAfter(RetryConditionHeaderValue retryAfter)
{
if (retryAfter?.Delta != null)
return retryAfter.Delta;
if (retryAfter?.Date != null && retryAfter.Date > DateTimeOffset.Now)
return retryAfter.Date - DateTimeOffset.Now;
return null;
}
private static bool HasRel(RDAPLink link, string rel)
{
// "rel" can contain multiple space-separated relation types.
return link.Rel?.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Any(x => x.Equals(rel, StringComparison.OrdinalIgnoreCase)) == true;
}
private static bool IsRDAPMediaType(string type)
{
return type != null && type.Split(';')[0].Trim().Equals(RDAPMediaType, StringComparison.OrdinalIgnoreCase);
}
private static bool IsHttpUrl(string url)
{
return Uri.TryCreate(url, UriKind.Absolute, out var uri) &&
(uri.Scheme == Uri.UriSchemeHttps || uri.Scheme == Uri.UriSchemeHttp);
}
private static bool HasRDAPPath(string url)
{
return new[] { "/domain/", "/ip/", "/autnum/", "/entity/", "/nameserver/" }
.Any(x => url.Contains(x, StringComparison.OrdinalIgnoreCase));
}
private static bool UrlEquals(string a, string b)
{
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b))
return false;
return string.Equals(a.TrimEnd('/'), b.TrimEnd('/'), StringComparison.OrdinalIgnoreCase);
}
#endregion
}