Skip to content

About

Checks a domain's SPF, DKIM and DMARC setup (RFC 7208, 6376, 9989): a CLI, a bulk scanner and an HTTP API in Go.

Topics

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

mailauth-check

CI

Checks a domain's email authentication setup: SPF, DKIM and DMARC. It finds the problems that make receivers ignore a policy, such as an SPF record over the DNS lookup limit, a DMARC record that receivers discard, or a DKIM key that is too short.

The checks follow the current RFCs, including RFC 9989, which replaced RFC 7489 (DMARC) in May 2026.

mailcheck has three commands: check for one domain, scan for a list of domains, and serve for an HTTP API.

Usage

Requires Go 1.26 or later, on Linux.

go build -o bin/mailcheck ./cmd/mailcheck     # or: make build

mailcheck check example.com
mailcheck check example.com --selector s1 --selector s2   # DKIM selectors to check
mailcheck check example.com --json                       # machine-readable report
mailcheck check example.com --dns 1.1.1.1 --timeout 10s  # own DNS server, longer limit

Example (real output; example.com publishes a revoked "null" DKIM key):

$ mailcheck check example.com --selector default
example.com  WARN   (33 ms)

SPF
  PASS   SPF record found: "v=spf1 -all"
  PASS   policy ends with "-all": unlisted senders fail
  PASS   the record needs 0 of 10 allowed DNS lookups

DKIM
  INFO   the key at default._domainkey.example.com is revoked (empty p tag): signatures made with it fail

DMARC
  PASS   DMARC record found at _dmarc.example.com: "v=DMARC1;p=reject;sp=reject;adkim=s;aspf=s"
  PASS   policy is p=reject
  WARN   no rua address: the domain receives no aggregate reports
         → Add rua=mailto:... to see who sends mail as this domain.
  INFO   DKIM alignment is strict (adkim=s), SPF alignment is strict (aspf=s)

Colours are used only when the output is a terminal (and NO_COLOR is not set).

Exit code Meaning
0 no failures
1 at least one fail finding
2 usage error, or a check could not be completed (DNS error or timeout) and nothing failed

Bulk scan

mailcheck scan --input domains.txt --workers 50 --qps 200 > results.ndjson
  • Reads one domain per line from a file or stdin (--input -). Blank lines and # comments are skipped; invalid, duplicate and over-long lines are counted and skipped.
  • Writes one JSON report per line (NDJSON) to stdout, in the order the checks finish. Progress and a summary go to stderr.
  • --workers checks run at the same time; --qps caps DNS queries per second for the whole scan, so the scanner does not overload the resolver.
  • A domain whose lookups fail gets a report with error findings; the scan carries on.
  • Ctrl-C stops the scan cleanly: every line already written is a complete report.
  • Exit code 0 when the scan finished, 2 for a usage error, an I/O error or an interruption. The findings themselves don't change the exit code; filter the NDJSON instead, for example jq -c 'select(.status == "fail")' results.ndjson.

Real run on a list of 29 well-known domains plus one invalid line and one duplicate:

$ mailcheck scan --input domains.txt --workers 10 --qps 50 > results.ndjson
19 checked (3.8/s)
checked 29 domains in 6.244s (4.6/s)
  pass 0, info 4, warn 25, fail 0, error 0
  duration p50 1.96s, p95 2.97s
  skipped: 1 invalid, 1 duplicate, 0 too long, 0 cancelled

At --qps 50 the query limit, not the number of workers, sets the speed: these domains need about 12 queries each.

HTTP API

mailcheck serve --addr :8080          # logs JSON lines to stderr; Ctrl-C shuts down gracefully
Endpoint Returns
GET /v1/check?domain=example.com&selector=s1&selector=s2 the report as JSON (200, also when the domain has problems)
GET /healthz {"status":"ok"}
GET /metrics Prometheus metrics (text format)

Errors are JSON ({"error": "..."}): 400 for a missing or invalid parameter, 429 when the client is over its rate limit and 503 when all check slots are busy (both with Retry-After). Every response has an X-Request-ID that also appears in the log. The full description is in docs/openapi.yaml.

$ mailcheck serve --addr :8099 &
$ curl -i 'localhost:8099/v1/check?domain=https://x'
HTTP/1.1 400 Bad Request
Content-Type: application/json
X-Request-Id: 57261fa1a6b488b0

{"error":"domain \"https://x\": character ':' is not allowed"}

(Date and Content-Length headers left out.)

Limits, because every request makes DNS queries for whoever sends it:

Limit Value
Requests per client 1 per second, bursts of 10 (an IPv4 address, or an IPv6 /64 network)
Checks running at once 50
DNS queries per check 64
Time per check 5 s; a client that disconnects stops its check
Selectors per request 10

The client address is taken from the TCP connection; X-Forwarded-For is ignored, because any client can set it. Callers cannot choose the DNS server.

/metrics after two checks and one bad request (# HELP lines left out):

# TYPE mailcheck_http_requests_total counter
mailcheck_http_requests_total{code="200"} 2
mailcheck_http_requests_total{code="400"} 1
# TYPE mailcheck_http_request_duration_seconds histogram
mailcheck_http_request_duration_seconds_bucket{le="0.01"} 1
mailcheck_http_request_duration_seconds_bucket{le="0.05"} 1
mailcheck_http_request_duration_seconds_bucket{le="0.1"} 1
mailcheck_http_request_duration_seconds_bucket{le="0.25"} 3
mailcheck_http_request_duration_seconds_bucket{le="0.5"} 3
mailcheck_http_request_duration_seconds_bucket{le="1"} 3
mailcheck_http_request_duration_seconds_bucket{le="2.5"} 3
mailcheck_http_request_duration_seconds_bucket{le="5"} 3
mailcheck_http_request_duration_seconds_bucket{le="10"} 3
mailcheck_http_request_duration_seconds_bucket{le="+Inf"} 3
mailcheck_http_request_duration_seconds_sum 0.44710559099999997
mailcheck_http_request_duration_seconds_count 3
# TYPE mailcheck_http_requests_in_flight gauge
mailcheck_http_requests_in_flight 1
# TYPE mailcheck_dns_queries_total counter
mailcheck_dns_queries_total 20
# TYPE mailcheck_dns_cache_hits_total counter
mailcheck_dns_cache_hits_total 0
# TYPE mailcheck_dns_cache_misses_total counter
mailcheck_dns_cache_misses_total 20

/metrics is not rate limited, so a monitoring system can always reach it; in production, serve it on an internal port only.

Docker

The image contains only the static binary (about 9 MB, on distroless/static) and runs as a non-root user. By default it starts the API on port 8080; any other command works too.

docker build -t mailcheck .
docker run --rm -p 8080:8080 mailcheck                          # mailcheck serve --addr :8080
docker run --rm mailcheck check example.com --selector default  # one check
docker run --rm -i mailcheck scan < domains.txt > results.ndjson

docker stop sends SIGTERM, and the server shuts down gracefully: running requests finish first. Use GET /healthz for liveness checks.

Python client

clients/python holds a small typed client for the API (httpx, with dataclasses for the report). Its tests start the Docker image on a free port and call /healthz and /v1/check.

from mailcheck_client import APIError, Client

with Client("http://localhost:8080") as c:
    report = c.check("example.com", selectors=["default"])
    print(report.status, [f.check for f in report.spf])
docker build -t mailcheck:latest .
cd clients/python && uv run pytest     # MAILCHECK_IMAGE overrides the image name

A non-200 answer raises APIError with the status, the error message and, for 429 and 503, retry_after in seconds.

What it checks

Area Checks
SPF (RFC 7208) exactly one record; full syntax including macros and dual CIDR lengths; the 10-lookup limit counted through include and redirect; void lookups; include and redirect loops; how the policy ends (-all, ~all, ?all, +all); ptr; terms after all; include= typos
DMARC (RFC 9989) policy discovery with the DNS Tree Walk (at most 8 queries); organizational domain from psd; p, sp, np, t; the removed pct, rf, ri; rua/ruf addresses and authorisation of external report destinations (RFC 9990, RFC 9991)
DKIM (RFC 6376, 8301, 8463) key records for given selectors, or a probe of common ones; RSA key size; Ed25519 keys; revoked keys; testing mode; SHA-1-only keys

Every result is a finding with a stable check ID (for example spf.lookup_limit), a severity and a hint on how to fix it:

Severity Meaning
pass correct
info worth knowing, no action needed
warn works, but weak or close to a limit
fail broken: receivers ignore or reject this
error could not be determined, for example a DNS timeout

A DNS timeout is never reported as a missing record.

Run the tests

Unit tests never touch the network: all DNS goes through an interface, and tests use an in-memory fake resolver.

go test ./...
make test     # go test -race ./...
make fuzz     # fuzz each parser for 30 seconds (FUZZTIME=10s to change)
go test -tags integration ./internal/checker   # one test against real DNS

The text output has a golden-file test; after an intended change, regenerate it with go test ./internal/report -update.

Benchmarks

Measured on an Intel Core i5-6300U (2 cores, 4 threads; 3 given to WSL2).

Parsers (go test -run '^$' -bench Parse -benchmem ./internal/spf ./internal/dmarc ./internal/dkim):

Parser Time per record Allocated
SPF (7 terms) 2.3 µs 1.7 KB, 6 allocations
DMARC (full record, 2 report addresses) 3.9 µs 1.4 KB, 15 allocations
DKIM (2048-bit RSA key) 4.5 µs 1.2 KB, 11 allocations

Scan of 1,000 domains against a fake DNS server that answers every query after 20 ms (go test -run '^$' -bench Scan -benchtime 1x ./internal/scan, about 2 minutes):

Workers Without cache With cache DNS queries per domain (without → with cache)
1 16 domains/s 48 domains/s 12 → 9
10 161 domains/s 463 domains/s 12 → 9
50 726 domains/s 1,965 domains/s 12 → 9
200 2,257 domains/s 2,109 domains/s 12 → 9
  • Throughput scales almost linearly with workers up to 50, because each domain spends its time waiting for DNS, not using CPU.
  • The cache makes each domain about 3× faster and cuts queries by 25%. A domain takes as long as its slowest check. Without the cache that is SPF: three lookups one after another (the domain's record, then the provider's two nested includes). With the cache, the provider's records and the parent DMARC record are fetched once for all domains, and SPF needs one lookup.
  • At 200 workers DNS latency is no longer the limit: 200 workers × 20 ms per lookup would allow 10,000 domains/s, but both variants stop at about 2,200 on 3 CPU threads, most likely CPU (not profiled). The cache's shared lock may explain why it is slightly slower there.
  • With a real resolver, the --qps limit is reached long before that: 2,000 domains/s × 12 queries would be 24,000 queries/s. Fewer queries per domain then means more domains per second.
  • Before the DKIM selectors were looked up concurrently, the 7 probes took 140 ms per domain and capped the scan at 6.9 domains/s per worker, with or without the cache.

Layout

cmd/mailcheck      the CLI (check, scan, serve)
internal/api       HTTP handlers, rate limiting, request logging, /metrics, graceful shutdown
internal/checker   runs the three checks for one domain; validates domains and selectors
internal/dnsx      Resolver interface, real resolver, per-domain query budget, cache, retry, rate limit, test fake
internal/ratelimit token bucket, and one bucket per client with bounded memory
internal/report    Finding and Report types, the list of check IDs, text and JSON output
internal/scan      bulk scan: reader, worker pool, NDJSON writer, summary
internal/taglist   The "tag=value;" syntax shared by DKIM and DMARC records
internal/spf       SPF parser and checks
internal/dmarc     DMARC parser, Tree Walk and checks
internal/dkim      DKIM key parser and checks
clients/python     typed Python client for the HTTP API, tested against the Docker image

Architecture

flowchart TB
    subgraph entry["cmd/mailcheck"]
        check["check"]
        scan["scan<br/>(internal/scan: reader → worker pool → NDJSON writer)"]
        serve["serve<br/>(internal/api: rate limit, slots, /metrics)"]
    end
    check --> checker
    scan --> checker
    serve --> checker
    checker["internal/checker<br/>runs SPF, DKIM, DMARC concurrently<br/>one timeout, one query budget"]
    checker --> spf["internal/spf"]
    checker --> dkim["internal/dkim"]
    checker --> dmarc["internal/dmarc"]
    dkim --> taglist["internal/taglist"]
    dmarc --> taglist
    spf & dkim & dmarc --> stack
    subgraph stack["internal/dnsx: one Resolver interface"]
        direction LR
        budget["Budget<br/>(per domain)"] --> cache["Cache<br/>(singleflight)"] --> retry["Retry"] --> limit["RateLimited<br/>(scan only)"] --> net["NetResolver"]
    end
    net --> dns[("DNS")]
Loading

Each check package has a pure parser (parse.go, fuzzed) and a checker (check.go) that does the lookups. All DNS goes through the dnsx.Resolver interface, so unit tests use an in-memory fake and never touch the network.

Design notes

  • DNS data is untrusted input. Records are written by whoever controls a domain. Every parser has size, term and depth limits, every check has a query limit, and fuzz tests assert that no input causes a panic. Record text in messages is escaped and truncated.
  • Parsing is separate from checking. Each parser is a pure function of one record, so it can be fuzzed and tested without DNS.
  • A timeout is not a missing record. DNS failures become error findings, never fail, and get their own exit code.
  • One budget per domain. The three checks run concurrently and share a limit of 64 DNS queries and one timeout.
  • A fixed worker pool with bounded channels. A slow DNS server makes the scan slower, not bigger: the reader waits for a free worker instead of starting more goroutines or buffering the input.
  • Cache with merged lookups. Many domains include the same SPF records. Concurrent identical lookups share one query, "no record" is cached, timeouts never are. The TTL is fixed because the standard library does not expose record TTLs.
  • The SPF lookup count is a worst case. Without a sender IP, every reachable DNS-querying term is counted. A receiver stops at the first match and may need fewer.

Limitations

  • DKIM keys can only be found for known selectors. "No key at the common selectors" does not mean DKIM is not set up.
  • Go's resolver cannot tell a non-existent domain (NXDOMAIN) from a name without records, so the DMARC np policy is reported, never applied.
  • SPF is not evaluated for a specific sender IP.
  • exists targets are looked up for A and AAAA records, although RFC 7208 §5.7 asks for A only. A name with only AAAA records is therefore not counted as a void lookup.
  • The cache and the API rate limiter live in one process. Running several instances needs shared ones (see docs/DESIGN.md).
  • Report hosts for external DMARC destinations are not resolved with a second Tree Walk; a host is internal when it is under the policy's organizational domain.

Security

See SECURITY.md for how to report a vulnerability.

License

MIT

References

About

Checks a domain's SPF, DKIM and DMARC setup (RFC 7208, 6376, 9989): a CLI, a bulk scanner and an HTTP API in Go.

Topics

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Used by

Contributors

Languages