Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Improve favicon extractor request handling (#1225)

Leendert de Borst4b706f466f1a
diff --git a/apps/server/Tests/AliasVault.UnitTests/Utilities/FaviconExtractorTests.cs b/apps/server/Tests/AliasVault.UnitTests/Utilities/FaviconExtractorTests.cs
index 606eaacd0..64a1bb383 100644
--- a/apps/server/Tests/AliasVault.UnitTests/Utilities/FaviconExtractorTests.cs
+++ b/apps/server/Tests/AliasVault.UnitTests/Utilities/FaviconExtractorTests.cs
@@ -22,4 +22,73 @@ public class FaviconExtractorTests
var faviconBytes = await FaviconExtractor.FaviconExtractor.GetFaviconAsync("https://adsense.google.com/start/");
Assert.That(faviconBytes, Is.Not.Null);
}
+
+ /// <summary>
+ /// Test that localhost URLs are blocked (SSRF protection).
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task BlockLocalhostUrls()
+ {
+ var localhostUrls = new[]
+ {
+ "http://localhost/favicon.ico",
+ "http://127.0.0.1/favicon.ico",
+ "http://[::1]/favicon.ico",
+ "http://localhost:8080/favicon.ico",
+ "https://localhost/favicon.ico",
+ };
+
+ foreach (var url in localhostUrls)
+ {
+ var faviconBytes = await FaviconExtractor.FaviconExtractor.GetFaviconAsync(url);
+ Assert.That(faviconBytes, Is.Null, $"Should block localhost URL: {url}");
+ }
+ }
+
+ /// <summary>
+ /// Test that private IP ranges are blocked (SSRF protection).
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task BlockPrivateIpRanges()
+ {
+ var privateIpUrls = new[]
+ {
+ "http://10.0.0.1/favicon.ico",
+ "http://10.100.0.1/favicon.ico",
+ "http://192.168.1.1/favicon.ico",
+ "http://172.16.0.1/favicon.ico",
+ "http://169.254.169.254/latest/meta-data/", // AWS metadata endpoint
+ "http://[fc00::1]/favicon.ico", // IPv6 private
+ "http://[fe80::1]/favicon.ico", // IPv6 link-local
+ };
+
+ foreach (var url in privateIpUrls)
+ {
+ var faviconBytes = await FaviconExtractor.FaviconExtractor.GetFaviconAsync(url);
+ Assert.That(faviconBytes, Is.Null, $"Should block private IP URL: {url}");
+ }
+ }
+
+ /// <summary>
+ /// Test that non-standard ports are blocked.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [Test]
+ public async Task BlockNonStandardPorts()
+ {
+ var nonStandardPortUrls = new[]
+ {
+ "http://example.com:8080/favicon.ico",
+ "https://example.com:8443/favicon.ico",
+ "http://example.com:3000/favicon.ico",
+ };
+
+ foreach (var url in nonStandardPortUrls)
+ {
+ var faviconBytes = await FaviconExtractor.FaviconExtractor.GetFaviconAsync(url);
+ Assert.That(faviconBytes, Is.Null, $"Should block non-standard port URL: {url}");
+ }
+ }
}
diff --git a/apps/server/Utilities/AliasVault.FaviconExtractor/FaviconExtractor.cs b/apps/server/Utilities/AliasVault.FaviconExtractor/FaviconExtractor.cs
index b1df2bc63..55568b1ce 100644
--- a/apps/server/Utilities/AliasVault.FaviconExtractor/FaviconExtractor.cs
+++ b/apps/server/Utilities/AliasVault.FaviconExtractor/FaviconExtractor.cs
@@ -9,7 +9,9 @@ namespace AliasVault.FaviconExtractor;
using System;
using System.Linq;
+using System.Net;
using System.Net.Http;
+using System.Net.Sockets;
using System.Threading.Tasks;
using HtmlAgilityPack;
using SkiaSharp;
@@ -40,63 +42,37 @@ public static class FaviconExtractor
using HttpClient client = CreateHttpClient();
- // First attempt
- var result = await TryGetFaviconAsync(client, uri);
- if (result != null)
+ // Attempt the operation up to two times to handle common cookiewall redirects or transient issues.
+ for (int attempt = 0; attempt < 2; attempt++)
{
- return result;
- }
-
- return await TryGetFaviconAsync(client, uri);
- }
-
- /// <summary>
- /// Normalizes the URL by adding a scheme if it is missing.
- /// </summary>
- /// <param name="url">The URL to normalize.</param>
- /// <returns>The normalized URL.</returns>
- private static string NormalizeUrl(string url)
- {
- if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
- {
- return "https://" + url;
+ var result = await TryGetFaviconAsync(client, uri);
+ if (result != null)
+ {
+ return result;
+ }
}
- return url;
+ // Return null if the favicon extraction failed.
+ return null;
}
/// <summary>
- /// Checks if the URI is valid.
+ /// Tries to get the favicon from the URL.
/// </summary>
- /// <param name="uri">The URI to check.</param>
- /// <returns>True if the URI is valid, false otherwise.</returns>
- private static bool IsValidUri(Uri uri)
+ /// <param name="client">The HTTP client.</param>
+ /// <param name="uri">The URI to get the favicon from.</param>
+ /// <returns>The favicon bytes.</returns>
+ private static async Task<byte[]?> TryGetFaviconAsync(HttpClient client, Uri uri)
{
- return _allowedSchemes.Contains(uri.Scheme) && uri.IsDefaultPort;
- }
+ var response = await FollowRedirectsAsync(client, uri);
- /// <summary>
- /// Creates a new HTTP client with default headers.
- /// </summary>
- /// <returns>The HTTP client.</returns>
- private static HttpClient CreateHttpClient()
- {
- var client = new HttpClient(new HttpClientHandler
- {
- AllowAutoRedirect = true,
- MaxAutomaticRedirections = 10,
- })
+ if (response == null || !response.IsSuccessStatusCode)
{
- Timeout = TimeSpan.FromSeconds(5),
- };
-
- client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
- client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
- client.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.5");
- client.DefaultRequestHeaders.Add("Connection", "keep-alive");
- client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
+ return null;
+ }
- return client;
+ var faviconNodes = await GetFaviconNodesFromHtml(response, uri);
+ return await TryExtractFaviconFromNodes(faviconNodes, client, uri);
}
/// <summary>
@@ -114,6 +90,7 @@ public static class FaviconExtractor
var defaultFavicon = new HtmlNode(HtmlNodeType.Element, htmlDoc, 0);
defaultFavicon.Attributes.Add("href", $"{uri.GetLeftPart(UriPartial.Authority)}/favicon.ico");
+ // Get the favicon nodes from the HTML, in order of preference.
HtmlNodeCollection?[] nodeArray =
[
htmlDoc.DocumentNode.SelectNodes("//link[@rel='icon' and @type='image/svg+xml']"),
@@ -131,18 +108,13 @@ public static class FaviconExtractor
return nodeArray.Where(x => x != null).Cast<HtmlNodeCollection>().ToArray();
}
- private static async Task<byte[]?> TryGetFaviconAsync(HttpClient client, Uri uri)
- {
- HttpResponseMessage response = await client.GetAsync(uri);
- if (!response.IsSuccessStatusCode)
- {
- return null;
- }
-
- var faviconNodes = await GetFaviconNodesFromHtml(response, uri);
- return await TryExtractFaviconFromNodes(faviconNodes, client, uri);
- }
-
+ /// <summary>
+ /// Tries to extract the favicon from the nodes.
+ /// </summary>
+ /// <param name="faviconNodes">The favicon nodes.</param>
+ /// <param name="client">The HTTP client.</param>
+ /// <param name="baseUri">The base URI.</param>
+ /// <returns>The favicon bytes.</returns>
private static async Task<byte[]?> TryExtractFaviconFromNodes(HtmlNodeCollection[] faviconNodes, HttpClient client, Uri baseUri)
{
foreach (var nodeCollection in faviconNodes)
@@ -186,8 +158,16 @@ public static class FaviconExtractor
{
try
{
- var response = await client.GetAsync(url);
- if (!response.IsSuccessStatusCode)
+ // Validate the favicon URL before fetching
+ if (!Uri.TryCreate(url, UriKind.Absolute, out var faviconUri) || !IsValidUri(faviconUri))
+ {
+ return null;
+ }
+
+ // Follow redirects with validation
+ var response = await FollowRedirectsAsync(client, faviconUri);
+
+ if (response == null || !response.IsSuccessStatusCode)
{
return null;
}
@@ -223,6 +203,128 @@ public static class FaviconExtractor
}
}
+ /// <summary>
+ /// Creates a new HTTP client with basic configuration.
+ /// </summary>
+ /// <returns>The HTTP client.</returns>
+ private static HttpClient CreateHttpClient()
+ {
+ var handler = new HttpClientHandler
+ {
+ AllowAutoRedirect = false, // Handle redirects manually
+ };
+
+ var client = new HttpClient(handler)
+ {
+ Timeout = TimeSpan.FromSeconds(5),
+ };
+
+ client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
+ client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
+ client.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.5");
+ client.DefaultRequestHeaders.Add("Connection", "keep-alive");
+ client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
+
+ return client;
+ }
+
+ /// <summary>
+ /// Normalizes the URL by adding a scheme if it is missing.
+ /// </summary>
+ /// <param name="url">The URL to normalize.</param>
+ /// <returns>The normalized URL.</returns>
+ private static string NormalizeUrl(string url)
+ {
+ if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
+ {
+ return "https://" + url;
+ }
+
+ return url;
+ }
+
+ /// <summary>
+ /// Checks if the URI is valid and not pointing to internal/private IPs.
+ /// </summary>
+ /// <param name="uri">The URI to check.</param>
+ /// <returns>True if the URI is valid and safe, false otherwise.</returns>
+ private static bool IsValidUri(Uri uri)
+ {
+ // Check scheme and port
+ if (!_allowedSchemes.Contains(uri.Scheme) || !uri.IsDefaultPort)
+ {
+ return false;
+ }
+
+ // Resolve hostname to IP and validate
+ try
+ {
+ var addresses = Dns.GetHostAddresses(uri.Host);
+ foreach (var address in addresses)
+ {
+ if (!IPAddressValidator.IsPublicIPAddress(address))
+ {
+ return false;
+ }
+ }
+ }
+ catch
+ {
+ // If DNS resolution fails, block the request
+ return false;
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Handles HTTP redirects with validation to prevent SSRF attacks.
+ /// </summary>
+ /// <param name="client">The HTTP client.</param>
+ /// <param name="uri">The initial URI to request.</param>
+ /// <returns>The final HTTP response after following redirects, or null if blocked/failed.</returns>
+ private static async Task<HttpResponseMessage?> FollowRedirectsAsync(HttpClient client, Uri uri)
+ {
+ var currentUri = uri;
+ int redirectCount = 0;
+ const int maxRedirects = 5;
+
+ while (redirectCount < maxRedirects)
+ {
+ var response = await client.GetAsync(currentUri);
+
+ if ((int)response.StatusCode >= 300 && (int)response.StatusCode < 400)
+ {
+ var location = response.Headers.Location;
+ if (location == null)
+ {
+ return null;
+ }
+
+ // Resolve relative URLs
+ if (!location.IsAbsoluteUri)
+ {
+ location = new Uri(currentUri, location);
+ }
+
+ // Validate the redirect target
+ if (!IsValidUri(location))
+ {
+ return null; // Block redirect to internal IPs
+ }
+
+ currentUri = location;
+ redirectCount++;
+ }
+ else
+ {
+ return response;
+ }
+ }
+
+ return null; // Too many redirects
+ }
+
/// <summary>
/// Resizes the image to the target width.
/// </summary>
diff --git a/apps/server/Utilities/AliasVault.FaviconExtractor/IPAddressValidator.cs b/apps/server/Utilities/AliasVault.FaviconExtractor/IPAddressValidator.cs
new file mode 100644
index 000000000..d0ce68939
--- /dev/null
+++ b/apps/server/Utilities/AliasVault.FaviconExtractor/IPAddressValidator.cs
@@ -0,0 +1,170 @@
+//-----------------------------------------------------------------------
+// <copyright file="IPAddressValidator.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.FaviconExtractor;
+
+using System;
+using System.Net;
+using System.Net.Sockets;
+
+/// <summary>
+/// Validates IP addresses for public accessibility to prevent SSRF attacks.
+/// </summary>
+internal static class IPAddressValidator
+{
+ /// <summary>
+ /// Private IPv4 blocks.
+ /// </summary>
+ private static readonly (byte[] Net, int Prefix)[] PrivateV4Blocks = new[]
+ {
+ (new byte[] { 10, 0, 0, 0 }, 8), // private
+ (new byte[] { 172, 16, 0, 0 }, 12), // private
+ (new byte[] { 192, 168, 0, 0 }, 16), // private
+ (new byte[] { 169, 254, 0, 0 }, 16), // link-local
+ (new byte[] { 100, 64, 0, 0 }, 10), // CGNAT
+ (new byte[] { 192, 0, 0, 0 }, 24), // IETF Protocol Assignments
+ (new byte[] { 192, 0, 2, 0 }, 24), // TEST-NET-1
+ (new byte[] { 198, 18, 0, 0 }, 15), // benchmarking
+ (new byte[] { 198, 51, 100, 0 }, 24), // TEST-NET-2
+ (new byte[] { 203, 0, 113, 0 }, 24), // TEST-NET-3
+ (new byte[] { 224, 0, 0, 0 }, 4), // multicast
+ (new byte[] { 240, 0, 0, 0 }, 4), // reserved
+ (new byte[] { 0, 0, 0, 0 }, 8), // local
+ };
+
+ /// <summary>
+ /// Private IPv6 blocks.
+ /// </summary>
+ private static readonly (byte[] Net, int Prefix)[] PrivateV6Blocks = new[]
+ {
+ (new byte[] { 0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 7), // ULA
+ (new byte[] { 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 32), // documentation
+ };
+
+ /// <summary>
+ /// Checks if an IP address is public (routable on the internet).
+ /// </summary>
+ /// <param name="address">The IP address to check.</param>
+ /// <returns>True if the IP is publicly routable, false otherwise.</returns>
+ public static bool IsPublicIPAddress(IPAddress address)
+ {
+ if (address is null)
+ {
+ throw new ArgumentNullException(nameof(address));
+ }
+
+ // Normalize IPv4-mapped IPv6 addresses to IPv4 for simpler handling.
+ if (address.AddressFamily == AddressFamily.InterNetworkV6 && address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ // Loopback / unspecified (0.0.0.0 or ::) are not public.
+ if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.None) || address.Equals(IPAddress.IPv6None))
+ {
+ return false;
+ }
+
+ // IPv4 checks.
+ if (address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ return IsPublicIPv4Address(address);
+ }
+
+ // IPv6 checks.
+ if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ return IsPublicIPv6Address(address);
+ }
+
+ // Unknown family -> treat as non-public.
+ return false;
+ }
+
+ /// <summary>
+ /// Checks if an IPv4 address is public.
+ /// </summary>
+ /// <param name="address">The IPv4 address to check.</param>
+ /// <returns>True if the IP is publicly routable, false otherwise.</returns>
+ private static bool IsPublicIPv4Address(IPAddress address)
+ {
+ var bytes = address.GetAddressBytes();
+
+ // Broadcast 255.255.255.255
+ if (bytes[0] == 255 && bytes[1] == 255 && bytes[2] == 255 && bytes[3] == 255)
+ {
+ return false;
+ }
+
+ // Check if the IP address is in any of the private IPv4 block.
+ foreach (var (net, prefix) in PrivateV4Blocks)
+ {
+ if (IsInPrefix(bytes, net, prefix))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Checks if an IPv6 address is public.
+ /// </summary>
+ /// <param name="address">The IPv6 address to check.</param>
+ /// <returns>True if the IP is publicly routable, false otherwise.</returns>
+ private static bool IsPublicIPv6Address(IPAddress address)
+ {
+ // Built-in flags for common non-routable addresses
+ if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal || address.IsIPv6Multicast)
+ {
+ return false;
+ }
+
+ var bytes = address.GetAddressBytes();
+
+ // Check if the IP address is in any of the private IPv6 block.
+ foreach (var (net, prefix) in PrivateV6Blocks)
+ {
+ if (IsInPrefix(bytes, net, prefix))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Checks if an address is within a CIDR prefix.
+ /// </summary>
+ /// <param name="address">The address bytes to check.</param>
+ /// <param name="network">The network prefix bytes.</param>
+ /// <param name="prefixLength">The prefix length in bits.</param>
+ /// <returns>True if the address is within the prefix, false otherwise.</returns>
+ private static bool IsInPrefix(byte[] address, byte[] network, int prefixLength)
+ {
+ int fullBytes = prefixLength / 8;
+ int remainingBits = prefixLength % 8;
+
+ for (int i = 0; i < fullBytes; i++)
+ {
+ if (address[i] != network[i])
+ {
+ return false;
+ }
+ }
+
+ if (remainingBits == 0)
+ {
+ return true;
+ }
+
+ int mask = 0xFF << (8 - remainingBits) & 0xFF;
+ return (address[fullBytes] & mask) == (network[fullBytes] & mask);
+ }
+}