.NET Development
IDN homograph domains in .NET: see the real host and detect lookalikes
"Can you tell tubanco.mx from tubаnco.mx?" asked a recent LinkedIn post by Miguel R. (in Spanish). In the second one, the fourth letter is a Cyrillic "а" (U+0430), and the browser actually goes to xn--tubnco-5nf.mx. That's a homograph attack: a domain written with letters from another script so it looks like a known one. Miguel covered it from the user's side and from IT's side. This guide covers the .NET developer's side.
The browser protects what the user sees in the address bar, but an application that receives links decides with no browser involved. Here you'll see where Uri keeps the real form of the host, why its ASCII form changes with the globalization mode, how to detect mixed scripts and confusable characters with the Unicode data, and a link checker that puts it all together. The outputs come from .NET 10.0.14 (SDK 10.0.403) on Windows 11.
Comparing strings tells you nothing
new IdnMapping().GetAscii("tub\u0430nco.mx") returns xn--tubnco-5nf.mx, exactly what Miguel described, and GetUnicode turns it back into tubаnco.mx. The xn-- form is Punycode; RFC 3492 says "It uniquely and reversibly transforms a Unicode string into an ASCII string."
What doesn't help is comparing strings. Against tubanco.mx, Ordinal, OrdinalIgnoreCase and InvariantCultureIgnoreCase return False, and CompareInfo.Compare with IgnoreNonSpace | IgnoreCase doesn't return 0 (it returns -1 with tubanco.mx as the first argument). They all say "different"; none says "looks alike", which is what matters. That takes UTS #39, the Unicode security standard, and .NET doesn't ship it.
Host vs IdnHost: where Uri keeps the real form
With https://tubаnco.mx/login, Host, DnsSafeHost, AbsoluteUri and ToString() all show tubаnco.mx with the Cyrillic letter. Only IdnHost returns xn--tubnco-5nf.mx. This post's program prints:
Host: tubаnco.mx
IdnHost: xn--tubnco-5nf.mx
AbsoluteUri: https://tubаnco.mx/login
Host equals tubanco.mx (OrdinalIgnoreCase): False
The docs say so in two places. For Host: "Non-ASCII characters are returned as-is and aren't punycode encoded." And DnsSafeHost is legacy: "For new code, prefer IdnHost, which is configuration-independent and produces a value suitable for DNS resolution."
Uri.IdnHost, not Host or AbsoluteUri: both show the host with the Cyrillic letter, which looks just like the real one.Casing has a catch. Uri lowercases ASCII hosts (TUBANCO.MX becomes tubanco.mx) on purpose. IdnMapping.GetAscii("TUBANCO.MX"), on the other hand, returns TUBANCO.MX unchanged, because IdnMapping.cs returns the original string when the output only differs in case. If you call GetAscii yourself, lowercase the result.
Same domain, different ASCII form, depending on the globalization mode
IdnMapping doesn't do the conversion itself: it calls a different library depending on the globalization mode. In the normal mode (ICU, the default on Linux and on Windows versions that ship ICU, such as Windows 11), pal_idna.c opens uidna_openUTS46 with UIDNA_CHECK_CONTEXTJ and UIDNA_NONTRANSITIONAL_TO_ASCII: UTS #46 without transitional processing, which the standard marks as deprecated. The IdnMapping page still describes .NET Framework 4.5 and Windows 8, so trust the source over that page.
With DOTNET_SYSTEM_GLOBALIZATION_USENLS=1, or on Windows without ICU, .NET calls Windows' IdnToAscii (NLS). With DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 there's no UTS #46 mapping and no normalization; the invariant mode design doc warns: "IDN support will be incorrect if the input IDN string is not normalized since normalization is not supported in invariant mode." Here is the GetAscii output measured in all three modes:
| Input | ICU | NLS | Invariant |
|---|---|---|---|
TUBANCO.MX | TUBANCO.MX | TUBANCO.MX | TUBANCO.MX |
tubanco.mx | tubanco.mx | tubanco.mx | xn--mi7cbe7bgzh.xn--yi7cwa |
tubanco。mx | tubanco.mx | tubanco.mx | tubanco.mx |
tuba\u00ADnco.mx | tubanco.mx | tubanco.mx | xn--tubanco-oka.mx |
tuba\u200Bnco.mx | tubanco.mx | tubanco.mx | xn--tubanco-3z6c.mx |
tuba\u200Dnco.mx | ArgumentException | tubanco.mx | xn--tubanco-k06c.mx |
ⓣⓤⓑⓐⓝⓒⓞ.mx | tubanco.mx | tubanco.mx | xn--vuhbe7bgzh.mx |
straße.de | xn--strae-oqa.de | strasse.de | xn--strae-oqa.de |
STRAẞE.DE | xn--strae-oqa.de | strasse.de | xn--strae-301b.de |
münchen.de | xn--mnchen-3ya.de | xn--mnchen-3ya.de | xn--mnchen-3ya.de |
mu\u0308nchen.de | xn--mnchen-3ya.de | xn--mnchen-3ya.de | xn--munchen-gie.de |
Three things stand out. straße.de becomes two different domains: xn--strae-oqa.de under ICU and strasse.de under NLS. NLS accepts the ZERO WIDTH JOINER (U+200D) that ICU rejects. And in invariant mode, fullwidth letters, the SOFT HYPHEN and the combining diaeresis produce xn-- domains unrelated to tubanco.mx or münchen.de. Miguel's example comes out the same in all three modes, which the doc anticipates: "Some basic IDN strings will still produce correct values."
This matters for containers. The official runtime-deps 10.0 Dockerfiles for chiseled, Alpine and Azure Linux distroless set DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true, with the comment "Set the invariant mode since ICU package isn't included". The -extra variants of all three (noble-chiseled-extra, alpine3.24-extra and azurelinux3.0-distroless-extra) and the full noble image install ICU and don't set invariant mode. I didn't run this in a container or on Linux: the invariant column was simulated with the environment variable on Windows.
-extra suffix start in invariant mode, where IdnMapping doesn't apply UTS #46. If your code converts hosts, use an -extra variant or noble, which ship ICU.The other side of the table is good news. Under ICU, fullwidth letters, the ideographic full stop 。, the SOFT HYPHEN, the ZERO WIDTH SPACE and circled letters (ⓣⓤⓑⓐⓝⓒⓞ.mx) all give tubanco.mx, because UTS #46 maps each character through its table and normalizes: "Normalize the domain_name string to Unicode Normalization Form C." So tubanco.mx is tubanco.mx. Comparing the ASCII form is right because that's what DNS receives.
UseStd3AsciiRules is off by default
From the docs: "By default, the value of the UseStd3AsciiRules property is false, and an expanded subset of ASCII characters is permitted in a label." Measured with a default IdnMapping and one with UseStd3AsciiRules = true:
| Input | Default | UseStd3AsciiRules = true | new Uri(…).IdnHost |
|---|---|---|---|
tu_banco.mx | tu_banco.mx | ArgumentException | tu_banco.mx |
tu banco.mx | tu banco.mx | ArgumentException | UriFormatException |
tu*banco.mx | tu*banco.mx | ArgumentException | UriFormatException |
-tubanco.mx | ArgumentException | ArgumentException | -tubanco.mx |
a℀b.mx | aa/cb.mx | ArgumentException | UriFormatException |
In the last column, tu banco.mx and tu*banco.mx already fail when the Uri is created; a℀b.mx only fails when IdnHost is read. The odd one is a℀b.mx: U+2100 (ACCOUNT OF) maps to a/c, so the host ends up with a slash in it. Uri.TryCreate accepts it, but reading IdnHost throws UriFormatException; its source explains the risk: "This means that a host containing Unicode characters can be normalized to contain URI reserved characters, changing the meaning of a URI only when certain properties such as IdnHost are accessed." That's why LinkChecker catches that exception.
IdnMapping directly, turn on UseStd3AsciiRules: by default, a℀b.mx becomes aa/cb.mx, with a slash inside the host.Mixed scripts: what .NET doesn't ship
.NET converts between the Unicode form and the xn-- form, but it has nothing to tell you a character's script or which characters are confusable. That lives in UTS #39 and its data files. Section 5 defines the resolved script set: "Define the resolved script set for a string to be the intersection of the augmented script sets over all characters in the string." If the intersection is empty, the string is mixed-script. Common and Inherited characters (digits, hyphen, dot) count as every script, the Script_Extensions property is used, and the writing systems Hanb, Hntl, Jpan and Kore are added. Those writing systems are why tokyo東京 doesn't count as mixed. ScriptAnalysis.cs:
namespace HomographGuard;
public enum RestrictionLevel
{
AsciiOnly,
SingleScript,
HighlyRestrictive,
ModeratelyRestrictive,
MinimallyRestrictive,
}
// UTS #39 section 5: resolved script set, mixed-script detection and restriction level.
// Simplification: we do not apply an identifier profile (levels 5 and 6 merge),
// and the "Recommended scripts" check of Moderately Restrictive is not applied.
public static class ScriptAnalysis
{
// null means ALL scripts (a string made only of Common/Inherited characters).
public static HashSet<string>? ResolvedScriptSet(UnicodeSecurityData data, string text)
{
HashSet<string>? resolved = null;
foreach (var rune in text.EnumerateRunes())
{
var augmented = AugmentedScriptSet(data, rune.Value);
if (augmented is null) continue;
if (resolved is null) resolved = augmented;
else resolved.IntersectWith(augmented);
}
return resolved;
}
public static bool IsMixedScript(UnicodeSecurityData data, string text) =>
ResolvedScriptSet(data, text) is { Count: 0 };
public static RestrictionLevel GetRestrictionLevel(UnicodeSecurityData data, string text)
{
if (text.All(char.IsAscii)) return RestrictionLevel.AsciiOnly;
// SOSS: the set of augmented script sets, without Common/Inherited.
var soss = text.EnumerateRunes()
.Select(r => AugmentedScriptSet(data, r.Value))
.OfType<HashSet<string>>()
.ToList();
if (soss.Count == 0 || Intersect(soss).Count > 0) return RestrictionLevel.SingleScript;
var withoutLatin = soss.Where(s => !s.Contains("Latn")).ToList();
if (withoutLatin.Count == 0) return RestrictionLevel.SingleScript;
foreach (var system in new[] { "Kore", "Hanb", "Jpan" })
if (withoutLatin.All(s => s.Contains(system))) return RestrictionLevel.HighlyRestrictive;
var common = Intersect(withoutLatin);
if (common.Any(s => s is not ("Cyrl" or "Grek")))
return RestrictionLevel.ModeratelyRestrictive;
return RestrictionLevel.MinimallyRestrictive;
}
// Script_Extensions plus the writing systems Hanb, Hntl, Jpan and Kore.
private static HashSet<string>? AugmentedScriptSet(UnicodeSecurityData data, int codePoint)
{
var scx = data.ScriptExtensions(codePoint);
if (scx.Contains("Zyyy") || scx.Contains("Zinh")) return null;
var set = new HashSet<string>(scx, StringComparer.Ordinal);
if (set.Contains("Hani")) set.UnionWith(["Hanb", "Hntl", "Jpan", "Kore"]);
if (set.Contains("Hira") || set.Contains("Kana")) set.Add("Jpan");
if (set.Contains("Hang")) set.Add("Kore");
if (set.Contains("Bopo")) set.Add("Hanb");
if (set.Contains("Latn")) set.Add("Hntl");
return set;
}
private static HashSet<string> Intersect(IReadOnlyList<HashSet<string>> sets)
{
var result = new HashSet<string>(sets[0], StringComparer.Ordinal);
foreach (var set in sets.Skip(1)) result.IntersectWith(set);
return result;
}
}
With the Unicode 18.0.0 data, per label:
| Label | Resolved script set | Mixed | Restriction level |
|---|---|---|---|
tubanco | {Hntl, Latn} | False | AsciiOnly |
tubаnco | {} | True | MinimallyRestrictive |
аррӏе | {Cyrl} | False | SingleScript |
münchen | {Hntl, Latn} | False | SingleScript |
東京 | {Hanb, Hani, Hntl, Jpan, Kore} | False | SingleScript |
tokyo東京 | {Hntl} | False | SingleScript |
тубанко | {Cyrl} | False | SingleScript |
tubanc0 | {Hntl, Latn} | False | AsciiOnly |
The restriction level is an approximation: the code doesn't apply the UTS #39 identifier profile or recommended scripts list. Treat it as a signal, not as an exact level.
tubаnco mixes Latin and Cyrillic and gets caught. аррӏе, which imitates apple, doesn't: it's all Cyrillic, so nothing is mixed. UTS #39 calls this a whole-script confusable, and its own example is "scope" in Latin next to "ѕсоре" in Cyrillic. That case needs the skeleton.
Confusable characters: the UTS #39 skeleton
Section 4 of UTS #39 defines a string's skeleton in four steps: "Convert X to NFD format", "Remove any characters in X that have the property Default_Ignorable_Code_Point", replace each character with its prototype from confusables.txt, and "Reapply NFD". Two strings are confusable when their skeletons match. UnicodeSecurityData.cs loads the five data files and computes the skeleton:
using System.Globalization;
using System.Text;
namespace HomographGuard;
// Loads the Unicode data files that UTS #39 needs. .NET has no API for the
// Script_Extensions property or for confusables, so we read the official files:
// ucd/Scripts.txt, ucd/ScriptExtensions.txt, ucd/PropertyValueAliases.txt,
// ucd/DerivedCoreProperties.txt and security/confusables.txt
public sealed class UnicodeSecurityData
{
private const int MaxCodePoint = 0x10FFFF;
private readonly string[]?[] _scriptExtensions = new string[]?[MaxCodePoint + 1];
private readonly bool[] _defaultIgnorable = new bool[MaxCodePoint + 1];
private readonly Dictionary<int, string> _prototypes = new();
public string UnicodeVersion { get; }
private UnicodeSecurityData(string version) => UnicodeVersion = version;
public static UnicodeSecurityData Load(string dataDirectory)
{
string Read(string name) => File.ReadAllText(Path.Combine(dataDirectory, name));
var data = new UnicodeSecurityData(ReadVersion(Read("confusables.txt")));
// Scripts.txt uses long names (Latin); ScriptExtensions.txt uses short codes (Latn).
var shortCode = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var fields in DataLines(Read("PropertyValueAliases.txt")))
if (fields[0] == "sc") shortCode[fields[2]] = fields[1];
foreach (var fields in DataLines(Read("Scripts.txt")))
data.SetRange(fields[0], [shortCode[fields[1]]]);
// Script_Extensions overrides Script where it is listed.
foreach (var fields in DataLines(Read("ScriptExtensions.txt")))
data.SetRange(fields[0], fields[1].Split(' ', StringSplitOptions.RemoveEmptyEntries));
foreach (var fields in DataLines(Read("DerivedCoreProperties.txt")))
if (fields[1] == "Default_Ignorable_Code_Point")
foreach (var cp in Range(fields[0])) data._defaultIgnorable[cp] = true;
foreach (var fields in DataLines(Read("confusables.txt")))
{
var source = int.Parse(fields[0], NumberStyles.HexNumber);
var target = string.Concat(fields[1].Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(hex => char.ConvertFromUtf32(int.Parse(hex, NumberStyles.HexNumber))));
data._prototypes[source] = target;
}
return data;
}
// Script_Extensions of a code point; unassigned code points are "Zzzz" (Unknown).
public IReadOnlyList<string> ScriptExtensions(int codePoint) => _scriptExtensions[codePoint] ?? ["Zzzz"];
// UTS #39 section 4: internalSkeleton(X). We stop there: domain labels that pass
// IDNA checks are treated as left-to-right (see "fast path" in UTS #39).
public string Skeleton(string text)
{
var builder = new StringBuilder();
foreach (var rune in text.Normalize(NormalizationForm.FormD).EnumerateRunes())
{
if (_defaultIgnorable[rune.Value]) continue;
builder.Append(_prototypes.TryGetValue(rune.Value, out var prototype) ? prototype : rune.ToString());
}
return builder.ToString().Normalize(NormalizationForm.FormD);
}
private void SetRange(string range, string[] scripts)
{
foreach (var cp in Range(range)) _scriptExtensions[cp] = scripts;
}
private static IEnumerable<int> Range(string range)
{
var parts = range.Split("..");
var first = int.Parse(parts[0], NumberStyles.HexNumber);
var last = parts.Length == 2 ? int.Parse(parts[1], NumberStyles.HexNumber) : first;
for (var cp = first; cp <= last; cp++) yield return cp;
}
// Each data line is "field ; field ; ... # comment".
private static IEnumerable<string[]> DataLines(string content)
{
foreach (var line in content.Split('\n'))
{
var data = line.Split('#')[0];
if (string.IsNullOrWhiteSpace(data)) continue;
yield return data.Split(';').Select(f => f.Trim()).ToArray();
}
}
private static string ReadVersion(string content) =>
content.Split('\n').First(l => l.StartsWith("# Version:", StringComparison.Ordinal))["# Version:".Length..].Trim();
}
| Text A | Text B | Skeletons | Confusable |
|---|---|---|---|
tubanco | tubаnco | tubanco / tubanco | True |
tubanco | tubanc0 | tubanco / tubancO | False |
tubanco | tubancо | tubanco / tubanco | True |
apple | аррӏе | apple / apple | True |
tubanco | tuba\u00ADnco | tubanco / tubanco | True |
tubanco | tubanko | tubanco / tubanko | False |
In the third row, the last letter of tubancо is a Cyrillic "о". And here аррӏе does show up. The limit is tubanc0, with the digit zero: it isn't confusable with tubanco, because confusables.txt maps zero to a capital O ("0030 ; 004F ; MA # ( 0 → O ) DIGIT ZERO → LATIN CAPITAL LETTER O"), so the skeleton is tubancO. An ASCII domain that resembles another one (typosquatting) needs different tools.
Don't store skeletons: UTS #39 says they aren't stable across Unicode versions, "so that they can only be interchanged between systems that use the same version of Unicode". And the version matters: this machine's icu.dll uses Unicode 15.1, while the data files are 18.0.0. In production, pin and track both: the ICU in the OS or image and the Unicode files you deploy.
A link checker with an allow list
LinkChecker brings it all together. The rules, in order:
Uri.TryCreatewithUriKind.Absolute, anhttporhttpsscheme and a DNS host. Otherwise,Invalid.- Take
uri.IdnHost, remove one trailing dot at most (the one a fully qualified name, FQDN, may have) and check withAscii.IsValidthat it's ASCII; step 3 validates the labels. IfIdnHostthrowsUriFormatExceptionor another trailing dot remains,Invalid. GetUnicodewith an STD3IdnMapping. If it throws,Invalid.Allowedif the ASCII host equals a listed domain or, withallowSubdomains: true, ends with.plus that domain.- Otherwise,
Lookalikeif its skeleton matches an allowed domain's skeleton, andNotAllowedif not. Either way, the reason says whether a label mixes scripts.
using System.Globalization;
using System.Net;
using System.Text;
namespace HomographGuard;
public enum Verdict
{
Allowed,
NotAllowed,
Lookalike,
Invalid,
}
public sealed record LinkCheckResult(Verdict Verdict, string? AsciiHost, string? UnicodeHost, string Reason);
// Checks a link pasted by a user against a list of allowed hosts.
// Rule 1: compare the ASCII form (what DNS receives), never the text the user sees.
// Rule 2: if the host is not allowed, look for mixed scripts and for a skeleton that
// matches an allowed host, so we can tell "unknown" apart from "lookalike".
public sealed class LinkChecker
{
private static readonly IdnMapping Idn = new() { UseStd3AsciiRules = true };
private readonly UnicodeSecurityData _data;
private readonly bool _allowSubdomains;
private readonly HashSet<string> _allowedAscii;
private readonly Dictionary<string, string> _allowedBySkeleton;
// allowSubdomains: true accepts every subdomain of an allowed host (not only www);
// false accepts exact matches only.
public LinkChecker(UnicodeSecurityData data, IEnumerable<string> allowedHosts, bool allowSubdomains)
{
// In globalization-invariant mode Normalize() returns its input unchanged and
// IdnMapping skips the UTS #46 mapping, so every check below would be wrong.
if ("e\u0301".Normalize() != "\u00E9")
throw new PlatformNotSupportedException("LinkChecker needs Unicode normalization: globalization-invariant mode is on.");
_data = data;
_allowSubdomains = allowSubdomains;
// GetAscii returns an all-ASCII input unchanged, upper case included: lower it ourselves.
_allowedAscii = allowedHosts.Select(h => Idn.GetAscii(h).ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
// Allowed hosts can share a skeleton (a defensive registration of your own lookalike): keep the first one.
_allowedBySkeleton = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var host in _allowedAscii)
_allowedBySkeleton.TryAdd(data.Skeleton(Idn.GetUnicode(host)), host);
}
public LinkCheckResult Check(string input)
{
if (!Uri.TryCreate(input, UriKind.Absolute, out var uri))
return new(Verdict.Invalid, null, null, "not a valid absolute URI");
if (uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp)
return new(Verdict.Invalid, null, null, $"scheme '{uri.Scheme}' is not http(s)");
if (uri.HostNameType != UriHostNameType.Dns)
return new(Verdict.Invalid, null, null, $"host type is {uri.HostNameType}");
string ascii;
try
{
ascii = uri.IdnHost;
}
catch (UriFormatException)
{
// Uri.TryCreate accepts some hosts and rejects them only when IdnHost maps them (U+2100, U+200D...).
return new(Verdict.Invalid, null, null, "Uri rejects the host (IDN)");
}
// A fully qualified name may end with one dot: remove that one only.
if (ascii.EndsWith('.')) ascii = ascii[..^1];
if (ascii.EndsWith('.'))
return new(Verdict.Invalid, ascii, null, "more than one trailing dot");
// Ascii.IsValid only checks that every char is ASCII; GetUnicode below validates the labels.
if (!Ascii.IsValid(ascii))
return new(Verdict.Invalid, ascii, null, "host is not a valid IDN");
// Uri classifies some IP addresses as DNS names (127.0.0.1. with a trailing dot, fullwidth digits).
if (IPAddress.TryParse(ascii, out _))
return new(Verdict.Invalid, ascii, null, "host is an IP address");
string unicode;
try
{
unicode = Idn.GetUnicode(ascii);
}
catch (ArgumentException)
{
return new(Verdict.Invalid, ascii, null, "IdnMapping rejects the host (STD3 rules)");
}
foreach (var allowed in _allowedAscii)
if (Matches(ascii, allowed))
return new(Verdict.Allowed, ascii, unicode, $"matches {allowed}");
var mixed = unicode.Split('.').Where(label => ScriptAnalysis.IsMixedScript(_data, label)).ToList();
var skeleton = _data.Skeleton(unicode);
foreach (var (allowedSkeleton, allowed) in _allowedBySkeleton)
if (Matches(skeleton, allowedSkeleton))
return new(Verdict.Lookalike, ascii, unicode,
$"same skeleton as {allowed}" + (mixed.Count > 0 ? $"; mixed-script label '{mixed[0]}'" : ""));
return new(Verdict.NotAllowed, ascii, unicode,
mixed.Count > 0 ? $"not in the list; mixed-script label '{mixed[0]}'" : "not in the list");
}
private bool Matches(string host, string allowed) =>
host == allowed || (_allowSubdomains && host.EndsWith("." + allowed, StringComparison.Ordinal));
}
The constructor's first check is the invariant-mode guard: if "e\u0301".Normalize() doesn't give é, there's no normalization and the checker refuses to start. And if two allowed hosts share a skeleton, such as when you also register your own lookalike so nobody else can use it, it keeps the first one instead of failing. Program.cs runs it against the list [tubanco.mx, Nippysoft.com], first with allowSubdomains: true:
using System.Globalization;
using System.Text;
using HomographGuard;
// Usage: dotnet run -- <folder with the five Unicode 18.0.0 data files>
Console.OutputEncoding = Encoding.UTF8;
const string Lookalike = "tub\u0430nco.mx"; // U+0430 CYRILLIC SMALL LETTER A
// Host keeps the Cyrillic letter; only IdnHost gives the ASCII form that DNS receives.
var uri = new Uri($"https://{Lookalike}/login");
Console.WriteLine($"Host: {uri.Host}");
Console.WriteLine($"IdnHost: {uri.IdnHost}");
Console.WriteLine($"AbsoluteUri: {uri.AbsoluteUri}");
Console.WriteLine($"Host equals tubanco.mx (OrdinalIgnoreCase): {string.Equals(uri.Host, "tubanco.mx", StringComparison.OrdinalIgnoreCase)}");
var data = UnicodeSecurityData.Load(args.Length > 0 ? args[0] : "data");
var label = Lookalike.Split('.')[0];
Console.WriteLine($"Unicode data: {data.UnicodeVersion}");
Console.WriteLine($"Mixed script: {ScriptAnalysis.IsMixedScript(data, label)}");
Console.WriteLine($"Skeletons: {data.Skeleton("tubanco")} / {data.Skeleton(label)}");
LinkChecker checker;
try
{
checker = new LinkChecker(data, ["tubanco.mx", "Nippysoft.com"], allowSubdomains: true);
}
catch (PlatformNotSupportedException e)
{
Console.WriteLine($"{e.GetType().Name}: {e.Message}");
return;
}
string[] links =
[
"https://tubanco.mx/login",
"https://www.tubanco.mx/",
"HTTPS://TUBANCO.MX/",
"https://tubanco.mx./",
"https://tubanco.mx../",
"https://tubanco.mx:8443/login",
"https://127.0.0.1./",
$"https://{Lookalike}/login",
"https://xn--tubnco-5nf.mx/login",
"https://tubanc0.mx/",
"https://\uFF54\uFF55\uFF42\uFF41\uFF4E\uFF43\uFF4F\uFF0E\uFF4D\uFF58/", // fullwidth letters and full stop
"https://tuba\u00ADnco.mx/", // U+00AD SOFT HYPHEN
"https://tuba\u200Dnco.mx/", // U+200D ZERO WIDTH JOINER
"https://a\u2100b.mx/", // U+2100 ACCOUNT OF
"https://tubanco.mx.example.net/",
"https://tubanco.mx@example.net/",
"https://m\u00FCnchen.de/",
"https://tu_banco.mx/",
"https://nippysoft.com/es/blog",
"ftp://tubanco.mx/",
"tubanco.mx/login",
];
foreach (var link in links)
Print(checker, link);
// allowSubdomains: false accepts exact matches only.
Console.WriteLine("Exact matches only:");
var exact = new LinkChecker(data, ["tubanco.mx", "Nippysoft.com"], allowSubdomains: false);
foreach (var link in new[] { "https://tubanco.mx/login", "https://www.tubanco.mx/" })
Print(exact, link);
static void Print(LinkChecker checker, string link)
{
var result = checker.Check(link);
Console.WriteLine($"{Show(link),-36} {result.Verdict,-10} {result.AsciiHost ?? "-",-23} {result.Reason}");
}
// Shows invisible characters as \uXXXX so the output can be read.
static string Show(string text)
{
var builder = new StringBuilder();
foreach (var rune in text.EnumerateRunes())
{
var category = Rune.GetUnicodeCategory(rune);
var invisible = category is UnicodeCategory.Format or UnicodeCategory.Control or UnicodeCategory.NonSpacingMark;
builder.Append(invisible ? $"\\u{rune.Value:X4}" : rune.ToString());
}
return builder.ToString();
}
The ICU output, after the Uri lines:
Unicode data: 18.0.0
Mixed script: True
Skeletons: tubanco / tubanco
https://tubanco.mx/login Allowed tubanco.mx matches tubanco.mx
https://www.tubanco.mx/ Allowed www.tubanco.mx matches tubanco.mx
HTTPS://TUBANCO.MX/ Allowed tubanco.mx matches tubanco.mx
https://tubanco.mx./ Allowed tubanco.mx matches tubanco.mx
https://tubanco.mx../ Invalid - not a valid absolute URI
https://tubanco.mx:8443/login Allowed tubanco.mx matches tubanco.mx
https://127.0.0.1./ Invalid 127.0.0.1 host is an IP address
https://tubаnco.mx/login Lookalike xn--tubnco-5nf.mx same skeleton as tubanco.mx; mixed-script label 'tubаnco'
https://xn--tubnco-5nf.mx/login Lookalike xn--tubnco-5nf.mx same skeleton as tubanco.mx; mixed-script label 'tubаnco'
https://tubanc0.mx/ NotAllowed tubanc0.mx not in the list
https://tubanco.mx/ Allowed tubanco.mx matches tubanco.mx
https://tuba\u00ADnco.mx/ Allowed tubanco.mx matches tubanco.mx
https://tuba\u200Dnco.mx/ Invalid - Uri rejects the host (IDN)
https://a℀b.mx/ Invalid - Uri rejects the host (IDN)
https://tubanco.mx.example.net/ NotAllowed tubanco.mx.example.net not in the list
https://tubanco.mx@example.net/ NotAllowed example.net not in the list
https://münchen.de/ NotAllowed xn--mnchen-3ya.de not in the list
https://tu_banco.mx/ Invalid tu_banco.mx IdnMapping rejects the host (STD3 rules)
https://nippysoft.com/es/blog Allowed nippysoft.com matches nippysoft.com
ftp://tubanco.mx/ Invalid - scheme 'ftp' is not http(s)
tubanco.mx/login Invalid - not a valid absolute URI
The link with the Cyrillic "а" and its xn-- form get the same verdict, because the ASCII form is what's compared. tubanco.mx.example.net isn't a subdomain of tubanco.mx, because the rule checks the suffix with a dot in front. In tubanco.mx@example.net, tubanco.mx is the userinfo and the host is example.net. And tubanc0.mx isn't reported as a lookalike, but it doesn't get through either: it isn't in the list. tubanco.mx. (FQDN) passes; tubanco.mx.. is already rejected by Uri.TryCreate, and the code removes one trailing dot only, never all of them. The port doesn't count: tubanco.mx:8443 comes out Allowed; if it matters, check uri.Port. a℀b.mx and the link with the ZERO WIDTH JOINER return Invalid: Uri.TryCreate accepts them, but reading IdnHost throws and Check catches the exception. Under NLS a single line changes, because NLS accepts the ZERO WIDTH JOINER and turns that link into tubanco.mx, as in the modes table:
https://tuba\u200Dnco.mx/ Allowed tubanco.mx matches tubanco.mx
In invariant mode, the program stops in the constructor:
PlatformNotSupportedException: LinkChecker needs Unicode normalization: globalization-invariant mode is on.
With allowSubdomains: true, the rule accepts any subdomain of the allowed host, not just www. If you don't control every subdomain, use allowSubdomains: false, which accepts exact matches only; the end of Program.cs shows it:
Exact matches only:
https://tubanco.mx/login Allowed tubanco.mx matches tubanco.mx
https://www.tubanco.mx/ NotAllowed www.tubanco.mx not in the list
LinkChecker decides on the host name and nothing else, so it isn't full protection against SSRF (your server making requests to places it shouldn't). It rejects hosts that are an IP literal, but it doesn't resolve DNS, doesn't check whether the target IP is private, loopback or link-local, doesn't cover DNS rebinding and, since it makes no HTTP requests, never sees redirects to unauthorized targets. If your server is going to fetch that URL, those checks are a separate job.
It's the same family of problems as the post on Unicode digits in .NET: by default, .NET accepts characters from other scripts that the developer doesn't expect, and the defense is to state explicitly what you accept.
Running it
A single console project, no NuGet packages, with the SDK pinned (global.json):
{
"sdk": { "version": "10.0.403", "rollForward": "disable" }
}
And HomographGuard/HomographGuard.csproj, which treats warnings as errors (it builds with 0 warnings):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
</Project>
The program needs the five Unicode 18.0.0 data files in a folder:
mkdir data
curl -sfL https://www.unicode.org/Public/18.0.0/ucd/Scripts.txt -o data/Scripts.txt
curl -sfL https://www.unicode.org/Public/18.0.0/ucd/ScriptExtensions.txt -o data/ScriptExtensions.txt
curl -sfL https://www.unicode.org/Public/18.0.0/ucd/PropertyValueAliases.txt -o data/PropertyValueAliases.txt
curl -sfL https://www.unicode.org/Public/18.0.0/ucd/DerivedCoreProperties.txt -o data/DerivedCoreProperties.txt
curl -sfL https://www.unicode.org/Public/18.0.0/security/confusables.txt -o data/confusables.txt
dotnet run --project HomographGuard -- data
The browser helps, but it doesn't decide for your app
Miguel is right about his example: Chrome shows Punycode when a label mixes scripts, because "Latin, Cyrillic or Greek characters cannot be mixed with each other", and Firefox applies a similar profile. But Firefox acknowledges that its system "permits whole-script confusables". When your application receives a link, there's no address bar to look at: the server makes the call.
What isn't tested
- Linux and real containers. On Linux, results depend on the distribution's ICU version.
- Which form of the host
HttpClientuses for DNS resolution or for theHostheader. - A character assigned after Unicode 15.1, the version of Windows' ICU.
- The skeleton is
internalSkeleton, notbidiSkeleton, so it isn't suitable as is for right-to-left labels (Arabic, Hebrew). The code doesn't replicate Chrome's other rules either. - The NLS results are from Windows 11 26200. I didn't compare against third-party libraries.
Frequently asked questions
Is it enough to block domains that start with xn--?
With an allow list you don't need to: anything not on the list is rejected, xn-- or not. The skeleton gives you a better reason, Lookalike instead of NotAllowed.
Does it work in a chiseled or Alpine container image?
The ones without the -extra suffix start in invariant mode, where LinkChecker throws PlatformNotSupportedException on purpose. The -extra variants and noble include ICU. I didn't test it in a real container.
Can I store skeletons in the database?
Better not: they aren't stable across Unicode versions. Store the ASCII form of the host and recompute the skeleton with the data your process loads.
Conclusion
In Uri, the real form of the host is in exactly one property: IdnHost. Compare that ASCII form, compute it in the same globalization mode you used for the allow list, turn on UseStd3AsciiRules if you use IdnMapping directly, and don't run in invariant mode. Going from "unknown" to "lookalike" takes more than .NET: you need five Unicode data files and the two UTS #39 algorithms; with the checker, that's three short classes.
If your application accepts links or redirects to domains on a list, find where it compares Host or AbsoluteUri, switch it to IdnHost, and run the links from this guide through LinkChecker.
References
- Uri.IdnHost — Microsoft Learn: learn.microsoft.com/en-us/dotnet/api/system.uri.idnhost
- .NET globalization and ICU — Microsoft Learn: learn.microsoft.com/en-us/dotnet/core/extensions/globalization-icu
- Globalization invariant mode, design doc — GitHub: github.com/dotnet/runtime/…/globalization-invariant-mode.md
- DomainNameHelper.cs, .NET 10 source — GitHub: github.com/dotnet/runtime/…/DomainNameHelper.cs
- UTS #46, Unicode IDNA Compatibility Processing — Unicode: unicode.org/reports/tr46
- UTS #39, Unicode Security Mechanisms — Unicode: unicode.org/reports/tr39
- confusables.txt 18.0.0 — Unicode: unicode.org/Public/18.0.0/security/confusables.txt
- Internationalized Domain Names (IDN) in Google Chrome — Chromium: chromium.googlesource.com/chromium/src/+/main/docs/idn.md
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment