RingDotNetfor Ring

International domain names

Domain names can contain letters of any alphabet — and that makes it possible to build a name that looks exactly like another one. This lesson converts names to and from Punycode with IdnMapping, shows what makes a name invalid, builds a look-alike of apple.com, and detects it by checking the alphabets of each part.

What you will learn#

The tutorial URLs and encodings took URLs apart and the tutorial Unicode and encodings looked at Unicode text. This lesson is where the two meet — and where it becomes a security question.

The program#

samples/UsingDotNet/tutorials/ch02_domain_names.ring
# international domain names - Punycode with IdnMapping, Uri.IdnHost, invalid names, and look-alike letters (homograph attacks)
load "dotnet.ring"

using {
	"System"
	"System.Globalization"
	"System.Text"
}

func main

	oIdn = new IdnMapping()

	# The system of domain names (DNS) knows only the letters a-z, the digits and the hyphen. A name with other letters is sent as
	# PUNYCODE: the text "xn--" followed by an encoding of the letters in ASCII. IdnMapping converts both ways.
	cGerman = "b" + char(195) + char(188) + "cher.example"                                 # bücher.example
	cArabic = char(217) + char(133) + char(217) + char(136) + char(217) + char(130) + char(216) + char(185) + ".example"          # موقع.example
	? "1. German:  " + cGerman + "  ->  " + oIdn.GetAscii(cGerman)
	? "   Arabic:  the name with the word for 'site' ->  " + oIdn.GetAscii(cArabic)
	? "   back:    " + oIdn.GetUnicode(oIdn.GetAscii(cGerman)) + "  and the round trip is exact: " + (oIdn.GetUnicode(oIdn.GetAscii(cGerman)) = cGerman)
	? "   a name that is plain ASCII does not change: " + oIdn.GetAscii("www.example.com")

	# 2. The Uri class keeps both forms: Host is the name as it was written and IdnHost the ASCII form that goes to the network
	oUri = new Uri("https://" + cGerman + "/path")
	? nl + "2. Host: " + oUri.Host + "   IdnHost (for DNS and certificates): " + oUri.IdnHost
	? "   an HTTP client sends the IdnHost; a certificate for this site names it in the Punycode form"

	# 3. Names that are not valid: a part (label) is at most 63 characters, it must not be empty, and it must not start or end with a
	#    hyphen. GetAscii raises an error for them.
	oStrict = new IdnMapping()
	oStrict.UseStd3AsciiRules = True                       # only letters, digits and hyphens are allowed in a name (a space is refused)
	? nl + "3. checking names (the second answer is with UseStd3AsciiRules):"
	aNames = ["good-name.example","-bad.example","empty..label.example",copy("a",64) + ".example","has space.example"]
	for cName in aNames
		? "   " + padRight(shortText(cName),24) + padRight(checkName(oIdn,cName),32) + checkName(oStrict,cName)
	next

	# 4. Look-alike letters. The Cyrillic letter U+0430 looks the same as the Latin letter a, so "apple.com" can be written with it:
	#    a different name that a person cannot tell apart. This is called a HOMOGRAPH attack. Punycode shows the difference at once.
	cLatin = "apple.com"
	cLookAlike = char(208) + char(176) + "pple.com"                                       # the first letter is Cyrillic
	? nl + "4. apple.com in two spellings:"
	? "   Latin:      " + cLatin + "   " + oIdn.GetAscii(cLatin)
	? "   look-alike: " + cLookAlike + "   " + oIdn.GetAscii(cLookAlike)
	? "   they look the same on the screen but they are different names: " + (cLatin != cLookAlike)

	# 5. A defense: look at the SCRIPTS (alphabets) of the letters in each part. A normal name uses one script; a name that mixes
	#    Latin and Cyrillic letters is suspicious. Browsers show such names in Punycode instead of the letters.
	? nl + "5. the alphabets in each part of the name (the parts are separated by dots):"
	aNames = [cLatin,cLookAlike,cGerman,cArabic,"dom" + char(208) + char(176) + "in.com"]
	for cName in aNames
		? "   " + padRight(oIdn.GetAscii(cName),26) + padRight(scriptsOf(cName),18) + decision(cName)
	next

	# 6. Safe display: show the Unicode form only when it is safe, otherwise the Punycode form
	? nl + "6. what to show to a person: " + displayName(oIdn,cArabic) + ", " + displayName(oIdn,cLookAlike)

# the checks of GetAscii: an error means that the name is not valid
func checkName oIdn,cName

	try
		return "valid: " + oIdn.GetAscii(cName)
	catch
		return "not valid"
	done

# the code of every letter of a text (Unicode code points): UTF-32 has four bytes for each letter
func codePoints cText

	aCodes = []
	cBytes = new UTF32Encoding().GetBytes(cText)
	for nPos = 1 to len(cBytes) step 4
		aCodes + (ascii(cBytes[nPos]) + ascii(cBytes[nPos + 1]) * 256 + ascii(cBytes[nPos + 2]) * 65536)
	next
	return aCodes

# the alphabet of a letter, from the range of its code (only a few alphabets, to show the idea)
func scriptOf nCode

	cScript = "other"
	if nCode >= 65 and nCode <= 122 and not (nCode > 90 and nCode < 97)
		cScript = "Latin"
	but nCode >= 192 and nCode <= 591
		cScript = "Latin"
	but nCode >= 880 and nCode <= 1023
		cScript = "Greek"
	but nCode >= 1024 and nCode <= 1327
		cScript = "Cyrillic"
	but nCode >= 1536 and nCode <= 1791
		cScript = "Arabic"
	ok
	return cScript

# the alphabets used in the letters of ONE part of a name (digits and hyphens are not letters of an alphabet)
func scriptList cLabel

	aScripts = []
	aCodePoints = codePoints(cLabel)
	for nCode in aCodePoints
		cScript = scriptOf(nCode)
		if cScript != "other" and find(aScripts,cScript) = 0
			aScripts + cScript
		ok
	next
	return aScripts

# the labels of a name are separated by dots; each label is checked alone (an Arabic name under the Latin ".example" is normal)
func labels cName

	return str2list(substr(cName,".",nl))

func scriptsOf cName

	cText = ""
	aLabels = labels(cName)
	for cLabel in aLabels
		cText += joinWith(scriptList(cLabel),"+") + " "
	next
	return cText

func isMixed cName

	aLabels = labels(cName)
	for cLabel in aLabels
		if len(scriptList(cLabel)) > 1
			return True
		ok
	next
	return False

func decision cName

	if isMixed(cName)
		return "MIXED in one part: suspicious"
	ok
	return "one alphabet in each part"

func displayName oIdn,cName

	if isMixed(cName)
		return oIdn.GetAscii(cName) + " (Punycode: mixed alphabets)"
	ok
	return cName + " (shown as written)"

func shortText cText

	if len(cText) > 22
		return left(cText,20) + "..."
	ok
	return cText

func padRight cText,nWidth

	return cText + copy(" ",nWidth - len(cText))

func joinWith aList,cSeparator

	cText = ""
	for item in aList
		if cText != ""
			cText += cSeparator
		ok
		cText += "" + item
	next
	return cText
Output
1. German:  bücher.example  ->  xn--bcher-kva.example
   Arabic:  the name with the word for 'site' ->  xn--4gbrim.example
   back:    bücher.example  and the round trip is exact: 1
   a name that is plain ASCII does not change: www.example.com

2. Host: bücher.example   IdnHost (for DNS and certificates): xn--bcher-kva.example
   an HTTP client sends the IdnHost; a certificate for this site names it in the Punycode form

3. checking names (the second answer is with UseStd3AsciiRules):
   good-name.example       valid: good-name.example        valid: good-name.example
   -bad.example            not valid                       not valid
   empty..label.example    not valid                       not valid
   aaaaaaaaaaaaaaaaaaaa... not valid                       not valid
   has space.example       valid: has space.example        not valid

4. apple.com in two spellings:
   Latin:      apple.com   apple.com
   look-alike: аpple.com   xn--pple-43d.com
   they look the same on the screen but they are different names: 1

5. the alphabets in each part of the name (the parts are separated by dots):
   apple.com                 Latin Latin       one alphabet in each part
   xn--pple-43d.com          Cyrillic+Latin Latin MIXED in one part: suspicious
   xn--bcher-kva.example     Latin Latin       one alphabet in each part
   xn--4gbrim.example        Arabic Latin      one alphabet in each part
   xn--domin-6ve.com         Latin+Cyrillic Latin MIXED in one part: suspicious

6. what to show to a person: موقع.example (shown as written), xn--pple-43d.com (Punycode: mixed alphabets)

How it works#

Punycode#

The system of domain names (DNS) was made for the letters a to z, the digits and the hyphen. A name with other letters is sent as Punycode: the text xn-- and then the letters of the part encoded with ASCII characters only. bücher.example becomes xn--bcher-kva.example and the Arabic name becomes xn--4gbrim.example. Each part (label) of the name is converted alone, so .example stays as it is. IdnMapping.GetAscii(name) converts to Punycode, GetUnicode(name) converts back, and the round trip is exact. A name that is already plain ASCII does not change. A person sees the Unicode form; the network, the HTTP client and the certificate use the Punycode form.

Uri#

new Uri("https://bücher.example/path") keeps both: Host is the name as written and IdnHost is the ASCII form that goes to DNS. When you compare host names or look up a certificate for one, use IdnHost.

Invalid names#

A label is at most 63 characters, it must not be empty (empty..label), and it must not start or end with a hyphen. GetAscii raises an error for these, so the program uses try / catch (the tutorial When things go wrong) to answer valid or not valid. The default mapper allows a space; with UseStd3AsciiRules = True the mapper follows the strict rules (letters, digits and hyphens only) and refuses it. For names that come from a user, use the strict mapper.

Look-alike letters#

The Cyrillic letter а (U+0430) and the Latin letter a (U+0061) are different letters that look the same in almost every font. So аpple.com — written with the Cyrillic first letter — is a different name from apple.com, and a person cannot see the difference. An attacker who registers the look-alike can send mail and links that seem to come from the real company. This is a homograph attack. The Punycode form shows the truth at once: xn--pple-43d.com is obviously not apple.com. Other pairs exist: Latin o and Greek ο, Latin l and capital I in many fonts, the digit 0 and the letter O.

Checking the alphabets#

A defense that browsers use: a name is shown in Unicode only when each part uses one alphabet. The program gets the code of every letter (a text is converted to UTF-32, four bytes for a letter), decides from the range of the code which alphabet it belongs to (Latin 0041–024F, Greek 0370–03FF, Cyrillic 0400–04FF, Arabic 0600–06FF; a real program uses the Unicode script data), and reports a part that mixes alphabets. аpple.com mixes Cyrillic and Latin in one part, so it is suspicious; bücher is one alphabet; the Arabic name under .example is fine because each part is checked alone. The name to show to a person is the Unicode form when it is safe, otherwise the Punycode form.

Warning

This check is only a first step. A whole-script look-alike (every letter Cyrillic, such as an all-Cyrillic word that looks Latin) passes it. Real systems also use lists of confusable letters, the rules of the registry of the top-level domain, and a warning when a name is new or rare. When your program shows or compares a name that a stranger chose — a link in a message, a sender address, a download URL — show the Punycode form or warn the user.

What you learned#

Exercises#

  1. Write sameSite(a, b) that compares two URLs by their IdnHost, ignoring case.
  2. Add the Hebrew range (0590–05FF) and the Greek look-alike ο (U+03BF) to the check and test gοogle.com.
  3. Write safeLink(text, address) that warns when the visible text and the real address have different hosts.
  4. Read the e-mail address of a message (the tutorial E-mail messages) and check the part after @.

Next#

MIME types

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.