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

Free lesson

SPF records: who may send your email

After this lesson: I can read an SPF record and say whether a server may send mail for a domain.

70 min lesson10 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

Anyone can type any sender into an email

Sender Policy Framework (SPF) is a DNS record that lists the servers allowed to send email for a domain. A receiving server checks it before it trusts a message.

It matters because email itself checks nothing. A server anywhere can claim to send for your college, and SPF is the first way to say it may not.

By the end of this lesson

Note

I can read an SPF record and say whether a server may send mail for a domain.

Key words

WordWhat it meansExample
Envelope senderthe address a sending server gives in MAIL FROM, where bounces go[email protected]
SPF recorda TXT record listing who may send for a domainv=spf1 mx -all
Mechanismone test in an SPF recordip4:198.51.100.0/24
Qualifierthe sign that says what a match means-all
Includea mechanism that asks another domain's SPF recordinclude:_spf.news.example.com

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

An email has two senders

When one mail server hands a message to another, it first says MAIL FROM with the envelope sender. That address is where bounces go, and it is saved as Return-Path.

The From line is part of the message itself, and it is what people see. SPF checks the envelope sender's domain against the address of the server that connected.

Worked example: the college's SPF record

TermWhat it testsIf it matches
v=spf1Marks the record as SPFNothing: it is not a test
mxIs the server one of the domain's MX servers?pass (no sign means +)
include:_spf.news.example.comDoes the newsletter firm's record give pass?pass
-allEverything elsefail

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

Write the zone for the practice server

Command
mkdir -p mail && printf '%s\n' 'txt-record=example.test,"v=spf1 mx include:_spf.news.example.com -all"' 'mx-host=example.test,mail.example.test,10' 'host-record=mail.example.test,10.0.10.25' 'txt-record=_spf.news.example.com,"v=spf1 ip4:198.51.100.0/24 ~all"' 'txt-record=shop.example.test,"v=spf1 ip4:10.0.10.30 ~all"' > mail/spf.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/spf.conf --no-hosts --no-resolv --port=5301 --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.

Read the college's SPF record

Command
dig +short @127.0.0.1 -p 5301 example.test TXT

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

Five results and a limit of ten

A check ends in a result. pass means the server is listed. fail comes from -all and means it is not. softfail comes from ~all and means "probably not". neutral comes from ?all. none means the domain has no SPF record.

An include, mx or a term costs a DNS lookup. A record that needs more than ten gives permerror, and receivers treat it as broken.

Write the SPF checker, part 1

Command
mkdir -p mail && printf '%s\n' 'import ipaddress' 'import subprocess' 'import sys' '' '' 'def ask(name, rtype):' '    out = subprocess.run(["dig", "+short", "@127.0.0.1", "-p", "5301", name, rtype],' '                         capture_output=True, text=True).stdout' '    return out.splitlines()' '' '' 'def txt(name):' '    found = []' '    for line in ask(name, "TXT"):' '        found.append("".join(line.split(chr(34))[1::2]))' '    return found' '' '' 'RESULT = {"+": "pass", "-": "fail", "~": "softfail", "?": "neutral"}' 'lookups = [0]' '' '' 'def check(domain, ip):' '    record = ""' '    for text in txt(domain):' '        if text.startswith("v=spf1 "):' '            record = text' '    if not record:' '        return "none", "no SPF record for " + domain' '    print("  " + domain + ": " + record)' '    for term in record.split()[1:]:' '        qualifier = "+"' '        if term[0] in RESULT:' '            qualifier = term[0]' '            term = term[1:]' > mail/spf.py

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

Write the SPF checker, part 2

Command
printf '%s\n' '        hit = False' '        if term == "all":' '            hit = True' '        elif term.startswith("ip4:"):' '            hit = ipaddress.ip_address(ip) in ipaddress.ip_network(term[4:])' '        elif term == "mx":' '            lookups[0] += 1' '            for line in ask(domain, "MX"):' '                if ip in ask(line.split()[1], "A"):' '                    hit = True' '        elif term.startswith("include:"):' '            lookups[0] += 1' '            result, why = check(term[8:], ip)' '            hit = result == "pass"' '        if hit:' '            return RESULT[qualifier], qualifier + term' '    return "neutral", "nothing matched"' '' '' 'result, why = check(sys.argv[1], sys.argv[2])' 'print(sys.argv[2] + " -> " + result + " (" + why + "), lookups: " + str(lookups[0]))' >> mail/spf.py

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

Check the college's own mail server

Command
python3 mail/spf.py example.test 10.0.10.25

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

Check the newsletter firm's server

Command
python3 mail/spf.py example.test 198.51.100.7

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

Check a server nobody listed

Command
python3 mail/spf.py example.test 203.0.113.66

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

Check the same server for the shop

Command
python3 mail/spf.py shop.example.test 203.0.113.66

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

What spf.py printed

Domain and addressResultWhyLookups
example.test, 10.0.10.25pass+mx: it is the MX server, mail.example.test1
example.test, 198.51.100.7passThe include gave pass for 198.51.100.0/242
example.test, 203.0.113.66fail-all: nothing else matched2
shop.example.test, 203.0.113.66softfail~all: the shop only says "probably not"0

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

Check the Run

Have a go

Check the Run

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

A common mistake

Warning

Many people think SPF pass proves who wrote the From line. SPF checks only the envelope sender's domain, which can differ from the From line. Lesson 3 ties the two together with DMARC.

Try it: an SPF check by hand

Code: python
# A tiny SPF check with no DNS: each term is tried in order.
RECORD = "v=spf1 ip4:10.0.10.25 ip4:10.0.10.26 -all"
RESULTS = {"+": "pass", "-": "fail", "~": "softfail", "?": "neutral"}

def check(ip):
    for term in RECORD.split()[1:]:
        sign = "+"
        if term[0] in RESULTS:
            sign = term[0]
            term = term[1:]
        if term == "all" or term == "ip4:" + ip:
            return RESULTS[sign]
    return "neutral"

print(check("10.0.10.26"), check("203.0.113.66"))
# Change -all to ~all, then press Run. What does 203.0.113.66 get now?

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

Match each term to what it means

Have a go

Loading…

Your answers are marked here and are not kept. An account keeps your marks.

Stop the practice server

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

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

Assignment: check an SPF record

Write an SPF check with no DNS: the records are a dictionary from a domain to its SPF text.

spf_result(records, domain, ip) tries the terms after v=spf1 in order and returns the result of the first match: + (or no sign) gives "pass", - "fail", ~ "softfail" and ? "neutral". It knows ip4: (an address or a network), include: (a match when that domain's result is "pass") and all. No match gives "neutral", and a domain with no record gives "none".

lookups(records, domain) counts the terms that cost a DNS lookup (include:, a, mx, exists: and redirect=), including those in every record an include reaches.

Code: python
import ipaddress


def spf_result(records, domain, ip):
    return "none"


def lookups(records, domain):
    return 0

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.