Lesson 07 · 35 minutes
Turn a name into an address and question the answer
- Follow a name through the hosts file, the resolver settings and the DNS record types
- Query records with Python, getent and dig, and read the TTL
- Explain how DNS spoofing and typosquatting abuse trust in names
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your company moves its shop to a new server. After the change, some users still reach the old page and some get "site not found". Your lead gives you a small test DNS server that holds the records of the new setup. You must read what it answers: where each name points in the end, how long a resolver may keep the answer, and which name does not exist.
Some steps of the worked example need an internet connection. Each one says so. The steps without that note work offline.
Recall
A connection to a port ends at once with "connection refused". What does that tell you?
The host is reachable and its kernel answered with a reset, but no program listens on that port. A timeout would mean something drops the packets.
Which entry of the routing table does the kernel use when no other entry matches?
The default route. It points to a gateway, which forwards the packet onward.
The idea
DNS (the Domain Name System) is a distributed database that maps names to data. Most programs do not talk to DNS directly. They call the resolver of the system, which looks in the places listed in /etc/nsswitch.conf (usually files, then dns). files means /etc/hosts: a plain list of address and name pairs. dns means a question to the servers named in /etc/resolv.conf. Those servers are usually a recursive resolver run by your network or by a provider, which asks other servers on your behalf and keeps the answers.
- Your program → System resolver: getaddrinfo("example.com")
- System resolver: look in /etc/hosts first
- System resolver → Recursive resolver: A record for example.com?
- Recursive resolver → DNS server: asks, if not in its cache
- DNS server → Recursive resolver: 192.0.2.10, TTL 300
- Recursive resolver → System resolver: 192.0.2.10
- System resolver → Your program: 192.0.2.10
An answer is a record. The types you meet most:
| Type | Holds |
|---|---|
A | An IPv4 address |
AAAA | An IPv6 address |
CNAME | An alias: "this name is another name" |
MX | The mail servers of the domain |
TXT | Free text: mail policy (SPF), domain ownership proofs |
NS | The servers that hold the records of the domain |
Each record has a TTL (time to live): the number of seconds that a resolver may keep the answer. A resolver that answers from its cache returns a smaller TTL each time. A short TTL lets an owner change a record fast; a long TTL saves queries.
A classic DNS query and answer are plain UDP with no signature. The resolver trusts what comes back. That is the weak point.
- Laptop → Resolver: where is example.com?
- Attacker → Laptop: false answer, arrives first
- Resolver → Laptop: the real answer, too late
- Laptop → Attacker: the browser connects to the attacker
Worked example
1. Resolve a name with the system resolver
getent hosts asks the resolver of the system, the same one that every normal program uses. This step is offline: localhost comes from /etc/hosts.
getent hosts localhost::1 localhostIt shows the first answer. Your machine may show 127.0.0.1 instead. Python reaches the same resolver with getaddrinfo, which returns every address of a name. -c runs the text as a small program.
python3 -c "
import socket
for r in socket.getaddrinfo('localhost', 80, type=socket.SOCK_STREAM):
print(r[0].name, r[4])
"AF_INET ('127.0.0.1', 80)Your machine may also list AF_INET6 with ::1.
2. Read the two settings files
grep prints the lines that match a pattern. With -v it prints the lines that do not match, so grep -v '^#' hides the comments (lines that start with #). head -3 keeps the first three lines.
grep -v '^#' /etc/hosts | head -3
grep '^hosts' /etc/nsswitch.conf
grep nameserver /etc/resolv.conf127.0.0.1 localhost
127.0.1.1 krbox
hosts: files dns
nameserver 127.0.0.53The address 127.0.0.53 is a resolver that runs on your own machine (a local stub that forwards the questions). Your file may name your router, for example 192.168.1.1.
3. Ask for an address (needs the internet)
dig (domain information groper) sends a DNS question and shows the raw answer. It is part of the package dnsutils or bind9-dnsutils. The option +noall +answer hides everything except the answer lines.
dig +noall +answer example.com Aexample.com. 124 IN A 104.20.23.154
example.com. 124 IN A 172.66.147.243Your addresses may differ: large sites return different answers by place and time.
4. Try each record type (needs the internet)
A for loop in the shell repeats a command once for each word in a list. Here $t is the record type of the round.
for t in AAAA MX TXT NS; do dig +noall +answer example.com $t; done
dig +noall +answer www.github.comexample.com. 215 IN AAAA 2606:4700:10::6814:179a
example.com. 215 IN MX 0 .
example.com. 300 IN TXT "v=spf1 -all"
example.com. 11246 IN NS elliott.ns.cloudflare.com.
www.github.com. 3516 IN CNAME github.com.
github.com. 27 IN A 20.233.83.145The MX record 0 . says "this domain receives no mail". The TXT record v=spf1 -all says "no server may send mail for this domain". The last query shows a CNAME: the answer lists the alias and then the address of the real name.
5. Watch the cache count down (needs the internet)
sleep 3 waits three seconds. Ask twice, and keep the first line each time.
dig +noall +answer example.com A | head -1; sleep 3; dig +noall +answer example.com A | head -1example.com. 124 IN A 104.20.23.154
example.com. 121 IN A 104.20.23.154The TTL fell by three, so the second answer came from the cache of your resolver and not from the owner's server.
6. See an answer that says "no such name" (needs the internet)
The top-level name .invalid is reserved and never exists. grep status keeps the header line that holds the status.
dig example.invalid A | grep status;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 33586NXDOMAIN means that the name does not exist. A host that asks for many names and gets NXDOMAIN for most of them is a clue: malware that generates random names behaves this way.
7. List the look-alikes of a name
Write typos.py. name.rpartition(".") splits a name at its last dot into the part before it, the dot and the part after it, so example.com gives example, . and com. The program builds names with a missing, swapped or doubled letter, and asks the resolver about each one. The resolution part needs the internet; without it every line says "no answer".
typos.py
import socket
def variants(name):
host, _, tld = name.rpartition(".")
out = set()
for i in range(len(host)):
out.add(host[:i] + host[i + 1:] + "." + tld)
if i + 1 < len(host):
out.add(host[:i] + host[i + 1] + host[i] + host[i + 2:] + "." + tld)
out.add(host[:i] + host[i] * 2 + host[i + 1:] + "." + tld)
out.discard(name)
return sorted(out)
for v in variants("example.com"):
try:
socket.getaddrinfo(v, 80)
print("resolves ", v)
except socket.gaierror:
print("no answer", v)python3 typos.py | head -4resolves eample.com
resolves eaxmple.com
resolves eexample.com
no answer exaample.comYour lines depend on the live DNS, so they can differ from these. A name that resolves is registered by someone. That does not prove it is bad, but it is the list to check.
Your turn
Read the records of the new shop setup. There are no steps here: use dig as in the worked example, but ask a different server.
Save the program below as minidns.py. It is a tiny DNS server with fixed records. It listens on 127.0.0.1, UDP port 8053, and you start it in one terminal with python3 minidns.py. It knows the names app.lab.test, shop.lab.test, www.lab.test and the name lab.test. It answers NXDOMAIN for a name that does not exist, and an empty answer with the status NOERROR for a name that exists but has no record of the type that you asked. Leave it running.
minidns.py
import socket
import struct
# name: (record type, TTL, data). Type 1 is A, 5 is CNAME, 16 is TXT.
RECORDS = {
"app.lab.test": (1, 300, "10.9.0.5"),
"shop.lab.test": (1, 120, "10.9.0.77"),
"www.lab.test": (5, 60, "shop.lab.test"),
"lab.test": (16, 900, "v=spf1 -all"),
}
def encode(name):
return b"".join(bytes([len(p)]) + p.encode() for p in name.split(".")) + b"\0"
def reply(query):
ident = query[:2]
labels, i = [], 12
while query[i]:
labels.append(query[i + 1:i + 1 + query[i]].decode())
i += 1 + query[i]
name = ".".join(labels).lower()
qtype = struct.unpack("!H", query[i + 1:i + 3])[0]
answers = []
while name in RECORDS and RECORDS[name][0] in (qtype, 5):
kind, ttl, data = RECORDS[name]
if kind == 1:
body = socket.inet_aton(data)
elif kind == 5:
body = encode(data)
else:
body = bytes([len(data)]) + data.encode()
answers.append(encode(name) + struct.pack("!HHIH", kind, 1, ttl, len(body)) + body)
if kind != 5:
break
name = data
rcode = 0 if answers or name in RECORDS else 3 # 3 is NXDOMAIN, "no such name"
header = ident + struct.pack("!HHHHH", 0x8180 | rcode, 1, len(answers), 0, 0)
return header + query[12:i + 5] + b"".join(answers)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("127.0.0.1", 8053))
print("mini DNS server on 127.0.0.1 port 8053. Press Ctrl+C to stop.", flush=True)
while True:
query, client = sock.recvfrom(512)
sock.sendto(reply(query), client)In a second terminal, ask this server and not your resolver: dig takes @127.0.0.1 for the server and -p 8053 for the port. Find the following:
- The address at the end of the alias
www.lab.test(ask for typeA, and read the whole answer). - The TTL of the alias record itself.
- The status of the question for the name
ghost.lab.test. - The text of the
TXTrecord oflab.test. Type it without the quotes.
Stop the server with Ctrl+C. Then ask yourself: if the owner changes shop.lab.test to a new address, how long can a resolver that has just cached it keep the old one?
Check yourself
Why does a program on your machine find "localhost" without any network?
The resolver reads /etc/hosts first (files comes before dns in nsswitch.conf). The entry is there, so no question leaves the machine.
An attacker on your Wi-Fi sends your machine a false DNS answer before the real one arrives. Why can that work, and what does it give the attacker?
A plain DNS answer is not signed, and the resolver accepts a reply that matches the question. The false address makes your browser connect to the attacker's machine while the name in the address bar looks correct. This is why encryption with a certificate check (lesson 9) must stand behind the name.
You change an A record, but some users still reach the old address for an hour. Why?
Resolvers keep the old answer until its TTL ends. Before a planned change, lower the TTL a day ahead, so that caches expire fast when you switch.
What is typosquatting and why is it a DNS problem?
It is the registration of names that look like a real one (exmaple.com), to catch users who mistype or to fool them in a link. Anyone can register any free name, so DNS cannot tell a real name from a look-alike. People and tools must check.
Field notes
- DNSSEC signs records so that a resolver can detect a forged answer. It protects the data, not the privacy of the question, and many domains do not use it. DNS over HTTPS and DNS over TLS encrypt the question between you and the resolver; they do not prove that the answer is true.
- A
TXTrecord is a source of facts: SPF, DKIM and DMARC records show who may send mail for a domain, and missing ones leave spoofed mail unchecked. Read them in every assessment of a domain. - A dangling CNAME is a real finding: an alias that points to a cloud name that nobody owns now. An attacker who claims that name controls a page on your domain (a subdomain takeover). Check your aliases against live targets.
- DNS logs are strong evidence. Short TTLs, long random-looking names, many
NXDOMAINanswers, and largeTXTanswers can mean command traffic or data leaving through DNS. - Public certificate logs list every name that gets a public certificate, so a "secret" subdomain is not secret. Do not rely on an obscure name as a defence.