Skip to content

Commit 6ff6fde

Browse files
BornToBeRootclaude
andcommitted
Feature: Secure RDAP referrals and validate the query per type
- The referral to the registrar (and its redirects) is only followed via HTTPS and not to local or private addresses, since the URL is sent by the registry. A skipped referral is logged and shown as status message. - New RDAPQueryValidator validates the query depending on the query type (domain, TLD, IP address/CIDR, ASN, entity) while typing, in the RDAP tool and in the profile dialog, and validates again if the type changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4375594 commit 6ff6fde

10 files changed

Lines changed: 199 additions & 11 deletions

File tree

‎Source/NETworkManager.Localization/Resources/Strings.Designer.cs‎

Lines changed: 18 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Source/NETworkManager.Localization/Resources/Strings.resx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4694,4 +4694,10 @@ Cloudflare may log your IP address and network information. See Cloudflare's pri
46944694
<data name="UpdateNow" xml:space="preserve">
46954695
<value>Update now</value>
46964696
</data>
4697+
<data name="RDAPReferralInsecureX" xml:space="preserve">
4698+
<value>The referral to the RDAP server of the registrar was not followed, because it does not use a secure connection (HTTPS): {0}</value>
4699+
</data>
4700+
<data name="RDAPReferralPrivateAddressX" xml:space="preserve">
4701+
<value>The referral to the RDAP server of the registrar was not followed, because it points to a local or private address: {0}</value>
4702+
</data>
46974703
</root>

‎Source/NETworkManager.Models/RDAP/RDAPClient.cs‎

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Net;
66
using System.Net.Http;
77
using System.Net.Http.Headers;
8+
using System.Net.Sockets;
89
using System.Threading;
910
using System.Threading.Tasks;
1011
using log4net;
@@ -149,11 +150,14 @@ private async Task FollowReferralAsync(RDAPResult result, TimeSpan timeout, Canc
149150

150151
try
151152
{
152-
result.Referral = await GetAsync(result.Query, referralUrl, timeout, cancellationToken)
153+
result.Referral = await GetAsync(result.Query, referralUrl, timeout, cancellationToken, true)
153154
.ConfigureAwait(false);
154155
}
155156
catch (RDAPException ex)
156157
{
158+
if (ex.Kind is RDAPErrorKind.InsecureReferral or RDAPErrorKind.PrivateAddress)
159+
Log.Warn($"Referral to the registrar not followed ({ex.Kind}): {ex.RequestUrl}");
160+
157161
// The registry response is still valid if the registrar fails.
158162
result.ReferralError = ex;
159163
}
@@ -162,8 +166,16 @@ private async Task FollowReferralAsync(RDAPResult result, TimeSpan timeout, Canc
162166
/// <summary>
163167
/// Sends a GET request, follows redirects and parses the response.
164168
/// </summary>
169+
/// <param name="query">Query.</param>
170+
/// <param name="url">URL to request.</param>
171+
/// <param name="timeout">Timeout for each request.</param>
172+
/// <param name="cancellationToken">Cancellation token.</param>
173+
/// <param name="isReferral">
174+
/// The URL comes from a response (registrar referral) and is untrusted: only HTTPS and no local or private
175+
/// addresses are allowed, for the referral and each redirect.
176+
/// </param>
165177
private async Task<RDAPResult> GetAsync(RDAPQuery query, string url, TimeSpan timeout,
166-
CancellationToken cancellationToken)
178+
CancellationToken cancellationToken, bool isReferral = false)
167179
{
168180
var visited = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
169181
var currentUrl = new Uri(url);
@@ -173,6 +185,9 @@ private async Task<RDAPResult> GetAsync(RDAPQuery query, string url, TimeSpan ti
173185
if (!visited.Add(currentUrl.AbsoluteUri) || redirects > MaxRedirects)
174186
throw new RDAPException(RDAPErrorKind.TooManyRedirects) { RequestUrl = currentUrl.AbsoluteUri };
175187

188+
if (isReferral)
189+
await ValidateReferralTargetAsync(currentUrl, cancellationToken).ConfigureAwait(false);
190+
176191
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
177192
timeoutSource.CancelAfter(timeout);
178193

@@ -220,6 +235,67 @@ private async Task<RDAPResult> GetAsync(RDAPQuery query, string url, TimeSpan ti
220235
}
221236
}
222237

238+
/// <summary>
239+
/// Checks the target of a referral, which is sent by the registry and therefore untrusted. Only HTTPS is allowed
240+
/// (no downgrade to plain text) and the host must not resolve to a local or private address, so a response
241+
/// cannot make the client send requests into the local network.
242+
/// </summary>
243+
private static async Task ValidateReferralTargetAsync(Uri url, CancellationToken cancellationToken)
244+
{
245+
if (url.Scheme != Uri.UriSchemeHttps)
246+
throw new RDAPException(RDAPErrorKind.InsecureReferral, url.AbsoluteUri) { RequestUrl = url.AbsoluteUri };
247+
248+
IPAddress[] addresses;
249+
250+
if (url.IsLoopback)
251+
{
252+
addresses = [IPAddress.Loopback];
253+
}
254+
else if (IPAddress.TryParse(url.DnsSafeHost, out var ipAddress))
255+
{
256+
addresses = [ipAddress];
257+
}
258+
else
259+
{
260+
try
261+
{
262+
addresses = await Dns.GetHostAddressesAsync(url.DnsSafeHost, cancellationToken).ConfigureAwait(false);
263+
}
264+
catch (SocketException)
265+
{
266+
// The request itself fails with a proper network error.
267+
return;
268+
}
269+
}
270+
271+
if (addresses.Any(IsLocalOrPrivateAddress))
272+
throw new RDAPException(RDAPErrorKind.PrivateAddress, url.AbsoluteUri) { RequestUrl = url.AbsoluteUri };
273+
}
274+
275+
/// <summary>
276+
/// Loopback, private (RFC 1918, RFC 4193), shared (RFC 6598), link-local, unspecified and multicast addresses.
277+
/// </summary>
278+
private static bool IsLocalOrPrivateAddress(IPAddress address)
279+
{
280+
if (address.IsIPv4MappedToIPv6)
281+
address = address.MapToIPv4();
282+
283+
if (IPAddress.IsLoopback(address))
284+
return true;
285+
286+
var bytes = address.GetAddressBytes();
287+
288+
if (address.AddressFamily == AddressFamily.InterNetwork)
289+
return bytes[0] is 0 or 10 or >= 224 ||
290+
bytes[0] == 172 && (bytes[1] & 0xF0) == 16 ||
291+
bytes[0] == 192 && bytes[1] == 168 ||
292+
bytes[0] == 169 && bytes[1] == 254 ||
293+
bytes[0] == 100 && (bytes[1] & 0xC0) == 64;
294+
295+
return address.Equals(IPAddress.IPv6Any) || address.IsIPv6LinkLocal || address.IsIPv6SiteLocal ||
296+
address.IsIPv6Multicast || (bytes[0] & 0xFE) == 0xFC;
297+
}
298+
223299
private static bool IsRedirect(HttpStatusCode statusCode)
224300
{
225301
return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther

‎Source/NETworkManager.Models/RDAP/RDAPException.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,16 @@ public enum RDAPErrorKind
4747
/// </summary>
4848
InsecureRedirect,
4949

50+
/// <summary>
51+
/// The referral to the registrar was not followed, because it does not use HTTPS.
52+
/// </summary>
53+
InsecureReferral,
54+
55+
/// <summary>
56+
/// The referral to the registrar was not followed, because it points to a local or private address.
57+
/// </summary>
58+
PrivateAddress,
59+
5060
/// <summary>
5161
/// Too many redirects or a redirect loop.
5262
/// </summary>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using System.Windows;
2+
using NETworkManager.Models.RDAP;
3+
4+
namespace NETworkManager.Validators;
5+
6+
public class RDAPQueryDependencyObjectWrapper : DependencyObject
7+
{
8+
public static readonly DependencyProperty QueryTypeProperty = DependencyProperty.Register("QueryType",
9+
typeof(RDAPQueryType),
10+
typeof(RDAPQueryDependencyObjectWrapper));
11+
12+
public RDAPQueryType QueryType
13+
{
14+
get => (RDAPQueryType)GetValue(QueryTypeProperty);
15+
set => SetValue(QueryTypeProperty, value);
16+
}
17+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
using System.Globalization;
2+
using System.Windows.Controls;
3+
using NETworkManager.Localization.Resources;
4+
using NETworkManager.Models.RDAP;
5+
6+
namespace NETworkManager.Validators;
7+
8+
/// <summary>
9+
/// Validates an RDAP query (domain, TLD, IP address/CIDR, AS number or entity handle) depending on the query type.
10+
/// </summary>
11+
public class RDAPQueryValidator : ValidationRule
12+
{
13+
public RDAPQueryDependencyObjectWrapper Wrapper { get; set; }
14+
15+
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
16+
{
17+
var error = RDAPQueryParser.TryParse(Wrapper?.QueryType ?? RDAPQueryType.Domain, value as string, out _);
18+
19+
return error == RDAPQueryParseError.None
20+
? ValidationResult.ValidResult
21+
: new ValidationResult(false, GetErrorMessage(error));
22+
}
23+
24+
/// <summary>
25+
/// Gets the localized error message for an invalid RDAP query.
26+
/// </summary>
27+
/// <param name="error">Error returned by <see cref="RDAPQueryParser" />.</param>
28+
/// <returns>Localized error message.</returns>
29+
public static string GetErrorMessage(RDAPQueryParseError error)
30+
{
31+
return error switch
32+
{
33+
RDAPQueryParseError.InvalidDomain => Strings.EnterValidDomain,
34+
RDAPQueryParseError.InvalidTLD => Strings.EnterValidTLD,
35+
RDAPQueryParseError.InvalidIPAddress => Strings.EnterValidIPAddressOrCIDR,
36+
RDAPQueryParseError.InvalidASN => Strings.EnterValidASN,
37+
_ => Strings.EnterValidEntityHandle
38+
};
39+
}
40+
}

‎Source/NETworkManager/ViewModels/ProfileViewModel.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2856,6 +2856,9 @@ public RDAPQueryType RDAP_QueryType
28562856

28572857
field = value;
28582858
OnPropertyChanged();
2859+
2860+
// Validate the query again for the new type.
2861+
OnPropertyChanged(nameof(RDAP_Query));
28592862
}
28602863
}
28612864

‎Source/NETworkManager/ViewModels/RDAPViewModel.cs‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using NETworkManager.Models.RDAP;
1010
using NETworkManager.Settings;
1111
using NETworkManager.Utilities;
12+
using NETworkManager.Validators;
1213
using NETworkManager.Views;
1314
using System;
1415
using System.Collections.Generic;
@@ -63,6 +64,9 @@ public RDAPQueryType QueryType
6364
field = value;
6465
OnPropertyChanged();
6566
OnPropertyChanged(nameof(QueryWatermark));
67+
68+
// Validate the query again for the new type.
69+
OnPropertyChanged(nameof(Query));
6670
}
6771
}
6872

@@ -296,7 +300,7 @@ private async Task RunQuery()
296300

297301
if (parseError != RDAPQueryParseError.None)
298302
{
299-
ShowStatusMessage(GetParseErrorMessage(parseError));
303+
ShowStatusMessage(RDAPQueryValidator.GetErrorMessage(parseError));
300304
IsRunning = false;
301305

302306
return;
@@ -324,7 +328,7 @@ private async Task RunQuery()
324328
IsResultVisible = true;
325329

326330
if (_result.ReferralError != null)
327-
ShowStatusMessage(string.Format(Strings.RDAPReferralFailedX, GetErrorMessage(_result.ReferralError, query)));
331+
ShowStatusMessage(GetReferralErrorMessage(_result.ReferralError, query));
328332

329333
AddQueryToHistory(Query);
330334
}
@@ -353,15 +357,13 @@ private void ShowStatusMessage(string message)
353357
IsStatusMessageDisplayed = true;
354358
}
355359

356-
private static string GetParseErrorMessage(RDAPQueryParseError error)
360+
private static string GetReferralErrorMessage(RDAPException ex, RDAPQuery query)
357361
{
358-
return error switch
362+
return ex.Kind switch
359363
{
360-
RDAPQueryParseError.InvalidDomain => Strings.EnterValidDomain,
361-
RDAPQueryParseError.InvalidTLD => Strings.EnterValidTLD,
362-
RDAPQueryParseError.InvalidIPAddress => Strings.EnterValidIPAddressOrCIDR,
363-
RDAPQueryParseError.InvalidASN => Strings.EnterValidASN,
364-
_ => Strings.EnterValidEntityHandle
364+
RDAPErrorKind.InsecureReferral => string.Format(Strings.RDAPReferralInsecureX, ex.RequestUrl),
365+
RDAPErrorKind.PrivateAddress => string.Format(Strings.RDAPReferralPrivateAddressX, ex.RequestUrl),
366+
_ => string.Format(Strings.RDAPReferralFailedX, GetErrorMessage(ex, query))
365367
};
366368
}
367369

‎Source/NETworkManager/Views/ProfileChildWindow.xaml‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4007,6 +4007,9 @@
40074007
<TextBox x:Name="TextBoxRDAPQuery" Grid.Column="2" Grid.Row="2"
40084008
IsEnabled="{Binding RDAP_InheritHost, Converter={StaticResource BooleanReverseConverter}}"
40094009
mah:TextBoxHelper.Watermark="{x:Static localization:StaticStrings.ExampleDomain}">
4010+
<TextBox.Resources>
4011+
<wpfHelpers:BindingProxy x:Key="BindingProxy" Data="{Binding}" />
4012+
</TextBox.Resources>
40104013
<TextBox.Style>
40114014
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource DefaultTextBox}">
40124015
<Style.Triggers>
@@ -4026,6 +4029,13 @@
40264029
<Binding.ValidationRules>
40274030
<validators:EmptyValidator
40284031
ValidatesOnTargetUpdated="True" />
4032+
<validators:RDAPQueryValidator
4033+
ValidatesOnTargetUpdated="True">
4034+
<validators:RDAPQueryValidator.Wrapper>
4035+
<validators:RDAPQueryDependencyObjectWrapper
4036+
QueryType="{Binding Data.RDAP_QueryType, Source={StaticResource BindingProxy}}" />
4037+
</validators:RDAPQueryValidator.Wrapper>
4038+
</validators:RDAPQueryValidator>
40294039
</Binding.ValidationRules>
40304040
</Binding>
40314041
</Setter.Value>

‎Source/NETworkManager/Views/RDAPView.xaml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,12 @@
218218
<Binding Path="Query" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
219219
<Binding.ValidationRules>
220220
<validators:EmptyValidator ValidatesOnTargetUpdated="True" />
221+
<validators:RDAPQueryValidator ValidatesOnTargetUpdated="True">
222+
<validators:RDAPQueryValidator.Wrapper>
223+
<validators:RDAPQueryDependencyObjectWrapper
224+
QueryType="{Binding Data.QueryType, Source={StaticResource BindingProxy}}" />
225+
</validators:RDAPQueryValidator.Wrapper>
226+
</validators:RDAPQueryValidator>
221227
</Binding.ValidationRules>
222228
</Binding>
223229
</ComboBox.Text>

0 commit comments

Comments
 (0)