Skip to content

Repository files navigation

spf-grabber

Collect the IPv4 and IPv6 networks that the SPF records of mail domains authorize, as a validated list for firewall aliases and allowlists.



⭐ Found this useful? Support open-source and star this project:

GitHub repository


Table of contents

Overview

spf-grabber resolves the SPF policies (RFC 7208) of one or more mail domains and prints the IPv4 and IPv6 networks that those policies authorize to send mail. The list is validated, normalized, deduplicated and sorted, one network per line, so that other software can load it without parsing SPF itself. Typical consumers are a firewall alias that limits who may connect to port 25, for example a URL table alias in pfSense or OPNsense, and the allowlists of mail software.

The tool is a single Bash script. It follows include and redirect, resolves a and mx to addresses, joins TXT records that DNS splits into several strings, checks every address and prefix length, and clears host bits. Only a complete list is written: a permanent failure of a policy, a guard violation or a temporary DNS failure leaves the existing output file as it is and ends with a non-zero exit status. With --keep-going, a domain whose policy fails permanently is skipped instead, and the list of the other domains is written (see Exit status).

How spf-grabber reads SPF policies

For each domain, spf-grabber queries the TXT records, joins the character-strings of each record and selects the record that starts with v=spf1. A domain without such a record, or with more than one, fails. The same applies to every domain reached through include or redirect. It then collects every network for which an SPF check could answer pass.

Terms

Mechanisms with the qualifier + or without a qualifier add networks. A mechanism with -, ~ or ? is looked up as well, because the first mechanism that matches decides (RFC 7208 section 4.6.2): its networks are taken out of those that later mechanisms of the same record add. A network that holds an excluded one is split into the largest networks outside it, so the list can hold more and smaller networks than the policy names. The target of an include that does not pass is read the same way, but what it passes only excludes: neither the prefix length guard nor the non-global filter applies there, and +all or a matching exists there excludes every address. An exclusion whose senders cannot be listed (see What cannot be listed) cannot be taken out; when it comes before a mechanism that adds networks, spf-grabber warns once per domain that the list may be broader than the policy. An exclusion that may take out more than the policy does, such as an include that does not pass and whose target holds such an exclusion itself, warns that the list may lack senders.

Term What spf-grabber does
ip4:ADDR[/LEN], ip6:ADDR[/LEN] Checks the network and adds it.
a[:NAME][/LEN4][//LEN6] Looks up the A and AAAA records of NAME, by default of the domain whose record is read, and adds each address with the given prefix lengths.
mx[:NAME][/LEN4][//LEN6] Looks up the MX records of NAME, then the A and AAAA records of every mail exchanger, and adds them as for a. A null MX (0 .) adds nothing.
include:NAME Reads the policy of NAME and adds the networks for which it passes.
redirect=NAME Reads the policy of NAME in place of the current one, after all mechanisms, when the record has no all.
-all, ~all, ?all Ends the record. Later terms and redirect are not read.
all, +all Fails the domain: the policy authorizes every address. In the target of an include that does not pass, it matches every address instead, so that include excludes them all.
exists:NAME Looks up the A record of NAME, also for IPv6 senders. Without one, it matches no sender and adds nothing. With one, it matches every sender: without a qualifier or with +, it fails the domain as +all does; with -, ~ or ?, it ends the record as -all does.
ptr[:NAME] A passing one warns and adds nothing, or with --strict fails the domain. One that does not pass is an exclusion that cannot be taken out.
exp=... and other name=value modifiers Ignored.
Anything else Fails the domain with a syntax error that quotes the term.

The macros %{d} (the domain whose record is read) and %{o} (the sender's domain) with their transformers and delimiters, such as %{d2} or %{or}, their upper-case forms, and %%, %_ and %- are expanded. spf-grabber takes the domain given on the command line as the sender's domain, so a policy that uses %{o} is read correctly when that is the domain senders use, not one of its include targets. %{v} is in-addr for IPv4 senders and ip6 for IPv6 senders: a term with it is evaluated once for each family, and what it yields applies to that family only. A name that holds a macro that depends on a concrete sender, such as %{i}, %{s} or %{l}, makes spf-grabber warn and add nothing for that term, or with --strict fail the domain; a mechanism with such a name that does not pass is skipped. Invalid macro syntax, the macros %{c}, %{r} and %{t}, which only explanations may use, a name that does not expand to a valid host name, an invalid address or prefix length, and an empty name after a colon are syntax errors. Every term of a record is checked before the first one is evaluated, so a syntax error after -all also fails the domain.

Limits

RFC 7208 section 4.6.4 limits a policy to 10 terms that cause DNS lookups (include, a, mx, ptr, exists and redirect), to 2 void lookups (an answer with NXDOMAIN or without a record of the requested type), and to 10 MX names per mx. spf-grabber counts them per domain given on the command line, across all includes and redirects. A term counts even when it is skipped for a macro. A domain that is included twice is evaluated once and counted twice; when %{v} led to it for one family only, it is evaluated again for the other. Void lookups of a, and all lookups behind a term with %{v}, count separately for IPv4 and IPv6, because an SPF check queries only for the family of the connecting address. A warning names the family when only one of them exceeds a limit.

A violation is a warning by default, because SPF checkers differ and mail from such senders often still arrives. With --strict it fails the domain. Independent of --strict, more than 100 lookups or more than 100 MX names for one domain, counted for both families together, more than 10000 networks in the list of one domain, a recursion deeper than 20 levels and an include or redirect loop always fail the domain.

What cannot be listed

An SPF check answers for one connection. ptr and the macros %{i} (the connecting address), %{p} (its validated host name), %{h} (the HELO name), %{s} and %{l} (the sender address and its local part) make a term ask DNS about that one connection. exists:%{i}._spf.example.net, for example, asks whether the name 45.67.89.4._spf.example.net exists when 45.67.89.4 connects, and ptr asks for the host name of the connecting address. DNS answers such a question for a given address, but it cannot list every address for which the answer is yes, because it offers no general way to list the names of a zone. Some mail providers publish their policies in this form on purpose, so that their addresses cannot be collected.

No tool can turn these terms into a list. spf-grabber warns and adds nothing for them, so their senders are missing from the list. With --strict, such a term fails the domain instead.

An exclusion through such a term cannot be taken out of the list either, so the list may then hold addresses that the policy rejects.

Requirements

  • Bash 4.4 or newer. The script checks the version when it starts.
  • dig from BIND 9, tested with 9.18. The environment variable SPF_GRABBER_DIG names another executable.
  • GNU coreutils: sort, mktemp, mv, cp, chmod, rm, cat, head and tail, as well as grep. --output uses mv -T, a GNU option that BusyBox has as well.
  • A DNS resolver, preferably one that validates DNSSEC (see Security notes).

Installation

spf-grabber is one file, spf-grabber.sh in the repository, and is installed as spf-grabber. Install it from the latest release:

# Install the dependencies: dig, plus curl and jq for the download below
sudo apt-get install bind9-dnsutils curl jq # Debian, Ubuntu
sudo dnf install bind-utils curl jq         # Fedora, RHEL and derivatives

# Get the version number of the latest release
version="$(curl -fsSL 'https://api.github.com/repos/foundata/spf-grabber/releases/latest' | jq -r '.tag_name' | sed -e 's/^v//')"
printf '%s\n' "${version}"

# Download into a private temporary directory
tmp_dir="$(mktemp -d)"
curl -fsSL -o "${tmp_dir}/spf-grabber" "https://raw.githubusercontent.com/foundata/spf-grabber/v${version}/spf-grabber.sh"

# Check the content (you have just downloaded a file from the internet)
cat "${tmp_dir}/spf-grabber"

# Install it with owner and permissions, then remove the download
sudo install -o root -g root -m 0755 "${tmp_dir}/spf-grabber" /usr/local/bin/spf-grabber
rm -r -- "${tmp_dir}"

/usr/local/bin/spf-grabber --version

To update, run the same steps again. From a clone of the repository, install the checked-out revision with sudo install -o root -g root -m 0755 spf-grabber.sh /usr/local/bin/spf-grabber.

Usage

spf-grabber [OPTION]... [DOMAIN]...

Give the domains as arguments, in files, or both. At least one domain is required. Domains are lower-cased, one trailing dot is removed and duplicates are evaluated once. A domain must be an ASCII host name: labels of letters, digits, hyphen and underscore, 1 to 63 characters each and 253 in total. Pass internationalized names in A-label form (xn--).

Options

Short options can be bundled, as in -qk, and take their value as the next argument or attached (-o FILE, -oFILE). Long options accept --name VALUE and --name=VALUE, and -- ends the options.

  -f, --domains-file FILE   Read more domains from FILE, one per line; blank
                            lines and text after '#' are ignored; '-' reads
                            standard input. May be given more than once.
  -o, --output FILE         Write the list to FILE instead of standard output,
                            atomically; an unchanged list leaves the content
                            and modification time of FILE as they are.
      --mode MODE           Octal permission bits for the output file, also an
                            existing one (default: 0644 for a new file, the
                            current mode for an existing one). Needs --output.
  -4, --ipv4-only           Evaluate the policies for IPv4 senders only and
                            print IPv4 networks.
  -6, --ipv6-only           Evaluate the policies for IPv6 senders only and
                            print IPv6 networks.
      --cidr                Always print a prefix length, also for single
                            addresses (/32, /128). Default: single addresses
                            are printed bare.
      --collapse            Drop networks that another listed network of the
                            same family covers completely.
      --allow-non-global    Keep networks outside global unicast space.
      --min-prefix4 BITS    Refuse IPv4 networks shorter than /BITS (default 8).
      --min-prefix6 BITS    Refuse IPv6 networks shorter than /BITS (default 16).
      --max-total4 BITS     Fail when the IPv4 networks together cover more
                            addresses than one /BITS network (default 6, or
                            two less than --min-prefix4 if that is smaller).
      --max-total6 BITS     Fail when the IPv6 networks together cover more
                            addresses than one /BITS network (default 14, or
                            two less than --min-prefix6 if that is smaller).
      --min-entries N       Fail when the final list has fewer than N entries
                            (default 1; 0 allows an empty list).
  -k, --keep-going          Skip domains whose policy fails permanently
                            instead of failing the whole run.
      --strict              Treat RFC 7208 processing-limit violations, and
                            passing terms whose senders cannot be listed, such
                            as ptr, as permanent failures instead of warnings.
  -r, --resolver ADDRESS    Query this DNS server instead of the system
                            resolver.
      --timeout SECONDS     Timeout of each attempt of a query (default 5).
      --tries N             Attempts per query (default 3).
  -q, --quiet               Suppress warnings.
  -v, --verbose             Trace lookups and the origin of every network on
                            standard error.
  -h, --help                Show help and exit.
  -V, --version             Show the version and exit.

-4 and -6 evaluate the policies for that family only, as an SPF check for a sender of that family does: the address lookups, the networks and the limits of the other family are left out. A network shorter than --min-prefix4 or --min-prefix6 fails the domain given on the command line whose policy reached it. --max-total4 and --max-total6 limit the address space of the whole list, by default to a /6 and a /14, or to four networks of the minimum prefix length when --min-prefix4 or --min-prefix6 is lowered; networks that another listed network covers count once. --resolver takes an IP address or a host name. SPF_GRABBER_DIG sets the dig executable, by default dig from PATH.

Output

Standard output carries the list and nothing else: one network per line, IPv4 before IPv6, each family sorted numerically by address and then by prefix length, with a final newline. IPv6 networks are printed per RFC 5952, except that IPv4-mapped addresses stay hexadecimal, such as ::ffff:c000:280, where the RFC recommends ::ffff:192.0.2.128. Every network is reduced to its network address; --verbose reports where host bits were cleared. Networks outside global unicast space are dropped with a warning, unless --allow-non-global is given: for IPv4 0.0.0.0/8, 10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.0.0.0/24, 192.0.2.0/24, 192.168.0.0/16, 198.18.0.0/15, 198.51.100.0/24, 203.0.113.0/24 and 224.0.0.0/3, for IPv6 everything outside 2000::/3 as well as the documentation ranges 2001:db8::/32 and 3fff::/20 and the benchmarking range 2001:2::/48. A network counts as non-global when it lies inside such a range or contains one.

Diagnostics go to standard error as lines that start with the name the command was run under, spf-grabber once installed, followed by error:, warning: and, with --verbose, info:. On a terminal they are colored, unless NO_COLOR is set to a non-empty value or TERM is unset or dumb. Error messages name the domain given on the command line and the chain of includes and redirects that led to the failing record, for example example.com > include:_spf.example.net.

With --output, spf-grabber evaluates every domain and checks the guards, then writes the list to a temporary file in the directory of FILE, named .FILE. followed by ten random characters, sets its mode and renames it over FILE. Before the first DNS query, it creates such a file once and removes it again, to check that it can. A reader sees the old or the new list, never a partial one. When the list equals the content of FILE, the file stays untouched and keeps its modification time; only --mode is applied to it. A new list keeps the mode of the existing FILE unless --mode is given, and its owner and group where the user may set them, also with --mode. The temporary file is removed on every exit path, including SIGHUP, SIGINT and SIGTERM, but not SIGKILL. A missing or unwritable directory, a FILE that exists and is not a regular file, such as a symbolic link, an existing FILE that cannot be read while --mode is not given, and a temporary file that cannot be created, for example because the name of FILE is too long, are errors before any DNS query.

Exit status

Status Meaning
0 Success. The list was printed or written, or FILE already held it.
1 A domain's policy failed permanently, or the result violates a guard such as --min-entries. Nothing was written. Problems with the output directory or the output file, a missing dig, or a missing mktemp with --output also end with 1.
2 Usage error. Nothing was queried or written.
3 --keep-going skipped at least one domain. The list of the other domains was written.
4 A DNS query failed temporarily: timeout, no reply, SERVFAIL, REFUSED, another response code, or an answer from a server that does not offer recursion. Nothing was written, also with --keep-going, so that an outage never shrinks a published list.

SIGHUP, SIGINT and SIGTERM end a run at once, also during a DNS query, with 129, 130 and 143; nothing is written.

Examples

The examples use reserved example domains. Replace them with the domains that send mail to you.

A list on standard output

spf-grabber example.com example.net

The output has this form:

45.67.89.0/24
81.2.69.144
2a0f:1234:5678::/48

A file for a firewall URL-table alias

A firewall such as pfSense or OPNsense can load a list of networks from a URL into an alias. Write the list into a directory that a web server publishes, and let the firewall fetch it from there:

spf-grabber --quiet --resolver 127.0.0.1 \
  --output /var/www/spf/allowlist.txt \
  example.com example.net

The file changes only when the list changes, and it is replaced in one step. A failed run keeps the previous list and ends with a non-zero exit status. Add --cidr if the consumer expects a prefix length on every line, and --collapse to shorten the list.

Daily refresh with systemd

This service and timer pair refreshes the file once a day as an unprivileged user. Create the user spf-grabber and give it write access to /var/www/spf first.

/etc/systemd/system/spf-grabber.service:

[Unit]
Description=Refresh the SPF allowlist
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
User=spf-grabber
ExecStart=/usr/local/bin/spf-grabber --resolver 127.0.0.1 --domains-file /etc/spf-grabber/domains.txt --output /var/www/spf/allowlist.txt
TimeoutStartSec=30min
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
ReadWritePaths=/var/www/spf

/etc/systemd/system/spf-grabber.timer:

[Unit]
Description=Refresh the SPF allowlist daily

[Timer]
OnCalendar=daily
RandomizedDelaySec=1h
Persistent=true

[Install]
WantedBy=timers.target

Enable the timer and run the service once to check it:

sudo systemctl daemon-reload
sudo systemctl enable --now spf-grabber.timer
sudo systemctl start spf-grabber.service

Every exit status other than 0 marks the service as failed, so monitoring of failed units also reports a policy that broke or a DNS outage. Warnings go to the journal; the service omits --quiet so that they stay visible there. TimeoutStartSec= matters because a Type=oneshot service has no start timeout by default, and a run that does not end would block every later one. If you add --keep-going and want skipped domains not to mark the unit as failed, add SuccessExitStatus=3 to the service.

Domains from a file

A domains file holds one domain per line. Blank lines and text after # are ignored:

# Partners that send mail to us
example.com
example.net   # through their own mail servers
example.org

Read it with --domains-file, or read domains from standard input with -:

spf-grabber --domains-file /etc/spf-grabber/domains.txt
printf '%s\n' example.com example.org | spf-grabber --domains-file -

Security notes

  • The list is only as trustworthy as the DNS answers it is built from. spf-grabber does not validate DNSSEC itself. Point --resolver to a resolver that validates DNSSEC, for example one on the same host, so that forged answers fail instead of adding networks.
  • SPF records are controlled by the listed domains and by every domain they include. Each of them can add networks to your list at any time. List only domains whose operators you trust with access to the service the list protects, and check the warnings and the size of the list from time to time.
  • Networks outside global unicast space are dropped because a partner's record that lists 10.0.0.0/8, 127.0.0.0/8 or fe80::/10, by mistake or on purpose, would otherwise open your own internal networks.
  • all and +all are refused because they authorize every address. As a list, such a policy would allow everyone. --min-prefix4 and --min-prefix6 refuse very large networks for the same reason, and --max-total4 and --max-total6 refuse a list whose many smaller networks add up to a very large part of the address space.
  • A replacement output file takes the mode, the ACLs and, as far as the user who runs spf-grabber may set them, the owner and group of the existing file. Set-user-ID and set-group-ID bits stay only when root runs spf-grabber or --mode sets them; extended attributes and SELinux labels are not kept. A new file, and with --mode an existing one that this user cannot read, belongs to this user.

Limitations

  • An exclusion through ptr or through a macro that depends on the connection cannot be taken out of the list, so the list may then hold addresses that the policy rejects. Inside the target of an include that does not pass, such an exclusion can also make the list lack senders. spf-grabber warns when this can happen.
  • Senders that a policy authorizes through ptr or through a macro that depends on the connection, such as %{i}, are missing from the list, because DNS cannot enumerate them (see What cannot be listed). With --strict, such a policy fails the domain instead.
  • The list reflects the DNS at the time of the run. Run it regularly, because the addresses behind a, mx and include change.
  • The list reflects the DNS view of the resolver. A resolver that serves an internal version of a listed domain (split-horizon DNS) may hold no SPF record for it, and the domain then fails. Use --resolver to query a resolver with the public view, or leave that domain out.
  • A real SPF check evaluates one connection and stops at the first mechanism that matches. spf-grabber counts the lookups of the whole record, as for a sender that no mechanism matches, so a limit warning can concern senders that a real check accepts before it reaches the limit.
  • --output needs mv -T (GNU coreutils or BusyBox) and refuses a symbolic link as FILE. On file systems with names of up to 255 bytes, such as ext4, XFS and Btrfs, the name of FILE can have at most 243 bytes, because the name of its temporary file is 12 bytes longer.
  • The parser of the dig output is tested with captured output of BIND 9.18.
  • Only ASCII domain names are accepted. Pass internationalized names in A-label form, which idn2 prints: idn2 bücher.example gives xn--bcher-kva.example.

Contributing

See CONTRIBUTING.md for the contribution workflow and DEVELOPMENT.md for the checks, the tests and the release workflow.

Licensing, copyright

Copyright (c) 2021-2026, foundata GmbH https://foundata.com

This project is licensed under the GNU General Public License v3.0 or later (SPDX-License-Identifier: GPL-3.0-or-later), see LICENSES/GPL-3.0-or-later.txt for the full text.

The REUSE.toml file provides detailed licensing and copyright information in a human- and machine-readable format. This includes parts that may be subject to different licensing or usage terms, such as third-party components. The repository conforms to the REUSE specification. You can use reuse spdx to create an SPDX software bill of materials (SBOM).

REUSE status

Trademarks

Own and licensed trademarks used in this repository:

  • foundata® is a trademark of IPAM GmbH, registered in Germany, the European Union, licensed to foundata GmbH.

Author information

This project was created and is maintained by foundata.

Releases

Contributors

Languages