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

Free lesson

DMARC: aligning SPF and DKIM with From

After this lesson: I can decide whether a message passes DMARC from its SPF and DKIM results.

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

Stopping mail that pretends to be from you

Domain-based Message Authentication, Reporting and Conformance (DMARC) is a DNS record that tells receivers what to do with mail that fakes your domain. It also asks them to report back.

It matters because SPF and DKIM alone never look at the From line, which is the address people actually read.

By the end of this lesson

Note

I can decide whether a message passes DMARC from its SPF and DKIM results.

Key words

WordWhat it meansExample
Alignmentthe checked domain matching the From line's domain
Organisational domainthe registered name a domain sits underexample.test
Policywhat the domain asks receivers to do with a failurep=reject
Quarantinedeliver to the junk folder instead of the inbox
Aggregate reporta daily summary a receiver sends back to the domainrua=

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

A pass only counts if it is aligned

DMARC passes when SPF or DKIM passes and its domain is aligned with the From line. For SPF that is the envelope sender's domain; for DKIM it is d=.

Relaxed alignment, the default, needs the same organisational domain: bounce.example.test aligns with example.test. Strict alignment needs the very same name.

Worked example: mail with From example.test

SPF passes forDKIM passes forAligned?DMARC
bounce.example.testnothingSPF, relaxedpass
mailer.example.comexample.comNeitherfail
nothing (forwarded)example.testDKIMpass

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 DMARC records

Command
mkdir -p mail && printf '%s\n' 'txt-record=_dmarc.example.test,"v=DMARC1; p=reject; rua=mailto:[email protected]; adkim=r; aspf=r"' 'txt-record=_dmarc.news.example.com,"v=DMARC1; p=none; rua=mailto:[email protected]"' > mail/dmarc.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/dmarc.conf --no-hosts --no-resolv --port=5303 --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 DMARC record

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

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

The policy says what happens to a failure

The policy is p=. With p=none, receivers deliver as normal and only report. With p=quarantine, failures go to junk. With p=reject, they are refused.

A receiver looks for _dmarc on the From domain first, then on its organisational domain. The checker below does the same.

Write the DMARC checker, part 1

Command
mkdir -p mail && printf '%s\n' 'import subprocess' 'import sys' '' '' 'def txt(name):' '    out = subprocess.run(["dig", "+short", "@127.0.0.1", "-p", "5303", name, "TXT"],' '                         capture_output=True, text=True).stdout' '    for line in out.splitlines():' '        text = "".join(line.split(chr(34))[1::2])' '        if text.startswith("v=DMARC1"):' '            return text' '    return ""' '' '' 'def org(domain):' '    return ".".join(domain.split(".")[-2:])' '' '' 'def aligned(a, b, mode):' '    if mode == "s":' '        return a == b' '    return org(a) == org(b)' '' '' 'def policy(domain):' '    record = txt("_dmarc." + domain)' '    if not record and not org(domain) == domain:' '        record = txt("_dmarc." + org(domain))' '    found = {}' '    for part in record.split(";"):' '        name, eq, value = part.strip().partition("=")' '        if eq:' '            found[name] = value' '    return record, found' '' '' > mail/dmarc.py

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

Write the DMARC checker, part 2

Command
printf '%s\n' 'sender, spf, spf_domain, dkim, dkim_domain = sys.argv[1:6]' 'record, tags = policy(sender)' 'if not record:' '    print(sender + ": dmarc=none")' '    sys.exit()' 'print("  _dmarc: " + record)' 'spf_ok = spf == "pass" and aligned(sender, spf_domain, tags.get("aspf", "r"))' 'dkim_ok = dkim == "pass" and aligned(sender, dkim_domain, tags.get("adkim", "r"))' 'result = "pass" if spf_ok or dkim_ok else "fail"' 'print("  SPF " + spf + " " + spf_domain + ": aligned=" + str(spf_ok))' 'print("  DKIM " + dkim + " " + dkim_domain + ": aligned=" + str(dkim_ok))' 'print(sender + ": dmarc=" + result + ", p=" + tags.get("p", "none"))' >> mail/dmarc.py

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

SPF passed for a bounce subdomain

Command
python3 mail/dmarc.py example.test pass bounce.example.test none -

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

Both passed for another domain

Command
python3 mail/dmarc.py example.test pass mailer.example.com pass example.com

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

A forwarded message kept its signature

Command
python3 mail/dmarc.py example.test fail list.example.com pass example.test

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

What dmarc.py printed

CaseSPF alignedDKIM alignedLast line
Bounce subdomainTrueFalseexample.test: dmarc=pass, p=reject
Another domainFalseFalseexample.test: dmarc=fail, p=reject
ForwardedFalseTrueexample.test: dmarc=pass, p=reject

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

Reports show who sends as you

Receivers send an aggregate report to the rua= address: each sending address, how many messages, and how SPF and DKIM fared.

So a domain starts at p=none and reads reports for a few weeks. It fixes its own senders, then moves to quarantine, then reject.

Write a report the college received, part 1

Command
mkdir -p mail && printf '%s\n' '<?xml version="1.0"?>' '<feedback>' '<report_metadata><org_name>mx.example.net</org_name><report_id>r-2026-11-16</report_id></report_metadata>' '<policy_published><domain>example.test</domain><p>none</p><adkim>r</adkim><aspf>r</aspf></policy_published>' '<record><row><source_ip>10.0.10.25</source_ip><count>412</count><policy_evaluated><disposition>none</disposition><dkim>pass</dkim><spf>pass</spf></policy_evaluated></row><identifiers><header_from>example.test</header_from></identifiers></record>' '<record><row><source_ip>198.51.100.7</source_ip><count>96</count><policy_evaluated><disposition>none</disposition><dkim>fail</dkim><spf>pass</spf></policy_evaluated></row><identifiers><header_from>example.test</header_from></identifiers></record>' > mail/report.xml

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

Write a report the college received, part 2

Command
printf '%s\n' '<record><row><source_ip>203.0.113.66</source_ip><count>7</count><policy_evaluated><disposition>none</disposition><dkim>fail</dkim><spf>fail</spf></policy_evaluated></row><identifiers><header_from>example.test</header_from></identifiers></record>' '</feedback>' >> mail/report.xml

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

Write the report reader

Command
mkdir -p mail && printf '%s\n' 'import sys' 'import xml.etree.ElementTree as ET' '' 'root = ET.parse(sys.argv[1]).getroot()' 'print("report from " + root.findtext("report_metadata/org_name")' '      + ", p=" + root.findtext("policy_published/p"))' 'for record in root.findall("record"):' '    row = record.find("row")' '    seen = row.find("policy_evaluated")' '    print(row.findtext("source_ip").ljust(14) + row.findtext("count").rjust(5)' '          + "  dkim=" + seen.findtext("dkim") + " spf=" + seen.findtext("spf")' '          + "  " + seen.findtext("disposition"))' > mail/rua.py

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

Read the report

Command
python3 mail/rua.py mail/report.xml

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

A common mistake

Warning

Many people think p=reject should be set on the first day. If one of your own senders is not yet aligned, its mail is refused too. Start at p=none, read the reports, fix every sender, then tighten.

Stop the practice server

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

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

Assignment: a DMARC verdict

Write the DMARC decision a receiver makes.

org_domain(name) returns the last two labels in lower case, or the last three when the last two are in SUFFIXES. aligned(a, b, mode) compares two domains: mode "s" needs the same name in any case, mode "r" the same organisational domain.

verdict(record, from_domain, spf, spf_domain, dkim, dkim_domain) reads p, aspf and adkim from the record (defaults none, r, r). DMARC passes when SPF is "pass" and aligned, or DKIM is "pass" and aligned. Return ["pass", "deliver"], or on a failure ["fail", "deliver"] for p=none and ["fail", p] otherwise.

Code: python
SUFFIXES = ["co.uk", "ac.uk", "org.uk"]


def org_domain(name):
    return name


def aligned(a, b, mode):
    return False


def verdict(record, from_domain, spf, spf_domain, dkim, dkim_domain):
    return ["fail", "deliver"]

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.