SPF (Sender Policy Framework) is a system that identifies to mail servers what hosts are allowed to send email for a given domain. Setting up SPF helps to prevent your email from being classified as spam.
DKIM (DomainKeys Identified Mail) is a system that lets your official mail servers add a signature to headers of outgoing email and identifies your domain’s public key so other mail servers can verify the signature. As with SPF, DKIM helps keep your mail from being considered spam. It also lets mail servers detect when your mail hass been tampered with in transit.
The instructions for setting up DNS for SPF and DKIM are generic. The instructions for configuring the SPF policy agent and OpenDKIM into Postfix should work on any distribution after making respective code adjustments for the package tool and to identify the exact path to OpenDKIM’s socket file in Postfix.
The steps required in this guide require root privileges. Be sure to run the steps below as root or with the
You must already have Postfix installed, configured and working. Refer to the Linode Postfix Guides for assistance.sudo apt-get install libsasl2-modules sudo apt-get install postfix
Publishing an SPF DNS record without having the SPF policy agent configured within Postfix is safe; however, publishing DKIM DNS records without having OpenDKIM working correctly within Postfix can result in your email being discarded by the recipient’s email server.
Install DKIM, SPF and Postfix
- Install the three required packages:
1 sudo apt-get install opendkim opendkim-tools postfix-policyd-spf-python
- Add user
opendkimgroup so that Postfix can access OpenDKIM’s socket when it needs to:
1 sudo adduser postfix opendkim
Set up SPF
Add SPF records to DNS
The value in an SPF DNS record will look something like the following examples. The full syntax is at the SPF record syntax page.
Example 1 Allow mail from all hosts listed in the MX records for the domain:
1 v=spf1 mx -all
Example 2 Allow mail from a specific host:
1 v=spf1 a:mail.example.com -all
v=spf1tag is required and has to be the first tag.
- The last tag,
-all, indicates that mail from your domain should only come from servers identified in the SPF string. Anything coming from any other source is forging your domain. An alternative is
~all, indicating the same thing but also indicating that mail servers should accept the message and flag it as forged instead of rejecting it outright.
-allmakes it harder for spammers to forge your domain successfully; it is the recommended setting.
~allreduces the chances of email getting lost because an incorrect mail server was used to send mail.
~allcan be used if you don’t want to take chances.
The tags between identify eligible servers from which email to your domain can originate.
mxis a shorthand for all the hosts listed in MX records for your domain. If you’ve got a solitary mail server,
mxis probably the best option. If you’ve got a backup mail server (a second MX record), using
mxwon’t cause any problems. Your backup mail server will be identified as an authorized source for email althought it will probably never send any.
atag lets you identify a specific host by name or IP address, letting you specify which hosts are authorized. You’d use
aif you wanted to prevent the backup mail server from sending outgoing mail or if you wanted to identify hosts other than your own mail server that could send mail from your domain (e.g., putting your ISP’s outgoing mail servers in the list so they’d be recognized when you had to send mail through them).
For now, we’re going to stick with the
mxversion. It’s simpler and correct for most basic configurations, including those that handle multiple domains. To add the record, go to your DNS management interface and add a record of type TXT for your domain itself (i.e., a blank hostname) containing this string:
1 v=spf1 mx -all
Go to the domain zone page for the selected domain and add a new TXT record. The screen will look something like this once you’ve got it filled out:
If your DNS provider allows it (DNS Manager doesn’t), you should also add a record of type SPF, filling it in the same way as you did the TXT record.
For example freedns.afraid.org requires the values to be written in the style found in BIND zonefiles. Thus, the above SPF record’s value would need to be wrapped in double-quotes like this:
"v=spf1 mx -all". You’ll need to consult your DNS provider’s documentation for the exact style required.
Add the SPF policy agent to Postfix
The Python SPF policy agent adds SPF policy-checking to Postfix. The SPF record for the sender’s domain for incoming mail will be checked and, if it exists, mail will be handled accordingly. Perl has its own version, but it lacks the full capabilities of Python policy agent.
- If you are using SpamAssassin to filter spam, you may want to edit
/etc/postfix-policyd-spf-python/policyd-spf.confto change the
False. This edit will cause the SPF policy agent to run its tests and add a message header with the results in it while not rejecting any messages. You may also want to make this change if you want to see the results of the checks but not actually apply them to mail processing. Otherwise, just go with the standard settings.
/etc/postfix/master.cfand add the following entry at the end:
1 2 policyd-spf unix - n n - 0 spawn user=policyd-spf argv=/usr/bin/policyd-spf
/etc/postfix/main.cfand add this entry to increase the Postfix policy agent timeout, which will prevent Postfix from aborting the agent if transactions run a bit slowly:
1 policyd-spf_time_limit = 3600
- Edit the
smtpd_recipient_restrictionsentry to add a
1 2 3 4 5 smtpd_recipient_restrictions = ... reject_unauth_destination, check_policy_service unix:private/policyd-spf, ...
Make sure to add the
check_policy_serviceentry after the
reject_unauth_destinationentry to avoid having your system become an open relay. If
reject_unauth_destinationis the last item in your restrictions list, add the comma after it and omit the comma at the end of the
- Restart Postfix:
1 sudo service postfix restart
You can check the operation of the policy agent by looking at raw headers on incoming email messages for the SPF results header. The header the policy agent adds to messages should look something like this:
This header indicates a successful check against the SPF policy of the sending domain. If you changed the policy agent settings in Step 1 to not reject mail that fails the SPF check, you may see Fail results in this header. You won’t see this header on outgoing or local mail.
The SPF policy agent also logs to
/var/log/mail.log. In the
mail.logfile you’ll see messages like this from the policy agent:
Jan 7 06:24:44 arachnae policyd-spf: None; identity=helo; client-ip=127.0.0.1; helo=mail.example.com; email@example.com; firstname.lastname@example.org
Jan 7 06:24:44 arachnae policyd-spf: Pass; identity=mailfrom; client-ip=127.0.0.1; helo=mail.example.com; email@example.com; firstname.lastname@example.org
The first message is a check of the HELO command, in this case indicating that there wasn’t any SPF information matching the HELO (which is perfectly OK). The second message is the check against the envelope From address, and indicates the address passed the check and is coming from one of the outgoing mail servers the sender’s domain has said should be sending mail for that domain. There may be other statuses in the first field after the colon indicating failure, temporary or permanent errors and so on.
Set up DKIM
DKIM involves setting up the OpenDKIM package, hooking it into Postfix, and adding DNS records.
- The main OpenDKIM configuration file
/etc/opendkim.confneeds to look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 # This is a basic configuration that can easily be adapted to suit a standard # installation. For more advanced options, see opendkim.conf(5) and/or # /usr/share/doc/opendkim/examples/opendkim.conf.sample. # Log to syslog Syslog yes # Required to use local socket with MTAs that access the socket as a non- # privileged user (e.g. Postfix) UMask 002 # OpenDKIM user # Remember to add user postfix to group opendkim UserID opendkim # Map domains in From addresses to keys used to sign messages KeyTable /etc/opendkim/key.table SigningTable refile:/etc/opendkim/signing.table # Hosts to ignore when verifying signatures ExternalIgnoreList /etc/opendkim/trusted.hosts InternalHosts /etc/opendkim/trusted.hosts # Commonly-used options; the commented-out versions show the defaults. Canonicalization relaxed/simple Mode sv SubDomains no #ADSPAction continue AutoRestart yes AutoRestartRate 10/1M Background yes DNSTimeout 5 SignatureAlgorithm rsa-sha256 # Always oversign From (sign using actual From and a null From to prevent # malicious signatures header fields (From and/or others) between the signer # and the verifier. From is oversigned by default in the Debian pacakge # because it is often the identity key used by reputation systems and thus # somewhat security sensitive. OversignHeaders From
/etc/opendkim.confand replace it’s contents with the above, or download a copy of opendkim.conf, upload it to your server and copy it over
- Ensure that file permissions are set correctly:
1 chmod u=rw,go=r /etc/opendkim.conf
- Create the directories to hold OpenDKIM’s data files, assign ownership to the
opendkimuser, and restrict the file permissions:
1 2 3 4 mkdir /etc/opendkim mkdir /etc/opendkim/keys chown -R opendkim:opendkim /etc/opendkim chmod go-rw /etc/opendkim/keys
- Create the signing table
/etc/opendkim/signing.table. It needs to have one line per domain that you handle email for. Each line should look like this:
1 *@example.com key
example.comwith your domain and
keywith a short name for the domain. The first field is a pattern that matches e-mail addresses. The second field is a name for the key table entry that should be used to sign mail from that address. For simplicity’s sake, we’re going to set up one key for all addresses in a domain.
- Create the key table
/etc/opendkim/key.table. It needs to have one line per short domain name in the signing table. Each line should look like this:
1 key example.com:YYYYMM:/etc/opendkim/keys/key.private
keyvalue you used for the domain in the signing table (make sure to catch the second occurrence at the end, where it’s followed by
example.comwith your domain name and replace the
YYYYMMwith the current 4-digit year and 2-digit month (this is referred to as the selector). The first field connects the signing and key tables.
The second field is broken down into 3 sections separated by colons.
- The first section is the domain name for which the key is used.
- The second section is a selector used when looking up key records in DNS.
- The third section names the file containing the signing key for the domain.
The flow for DKIM lookup starts with the sender’s address. The signing table is scanned until an entry whose pattern (first item) matches the address is found. Then, the second item’s value is used to locate the entry in the key table whose key information will be used. For incoming mail the domain and selector are then used to find the public key TXT record in DNS and that public key is used to validate the signature. For outgoing mail the private key is read from the named file and used to generate the signature on the message.
- Create the trusted hosts file
/etc/opendkim/trusted.hosts. Its contents need to be:
1 2 3 4 5 6 127.0.0.1 ::1 localhost myhostname myhostname.example.com example.com
When creating the file, change
myhostnameto the name of your server and replace
example.comwith your own domain name. We’re identifying the hosts that users will be submitting mail through and should have outgoing mail signed, which for basic configurations will be your own mail server.
- Make sure the ownership and permissions on
/etc/opendkimand it’s contents are correct (
opendkimshould own everything, the
keysdirectory should only be accessible by the owner) by running the following commands:
1 2 chown -R opendkim:opendkim /etc/opendkim chmod -R go-rwx /etc/opendkim/keys
- Generate keys for each domain:
1 opendkim-genkey -b 2048 -r -s YYYYMM
YYYYMMwith the current year and month as in the key table. This will give you two files,
YYYYMM.privatecontaining the key and
YYYYMM.txtcontaining the TXT record you’ll need to set up DNS. Rename the files so they have names matching the third section of the second field of the key table for the domain:
1 2 mv YYYYMM.private key.private mv YYYYMM.txt example.txt
Repeat the commands in this step for every entry in the key table. The
-b 2048indicates the number of bits in the RSA key pair used for signing and verification. 1024 bits is the minimum, but with modern hardware 2048 bits is safer. (It’s possible 4096 bits will be required at some point.)
- Make sure the ownership, permissions and contents on
/etc/opendkimare correct by running the following commands:
1 2 3 cd /etc chown -R opendkim:opendkim /etc/opendkim chmod -R go-rw /etc/opendkim/keys
- Check that OpenDKIM starts correctly:
1 sudo service opendkim restart
You should not get error messages, but if you do, use:
1 service opendkim status
to get the status and untruncated error messages.
Set up DNS
As with SPF, DKIM uses TXT records to hold information about the signing key for each domain. Using YYYYMM as above, you need to make a TXT record for the host
YYYYMM._domainkeyfor each domain you handle mail for. Its value can be found in the
example.txtfile for the domain. Those files look like this:
201510._domainkey IN TXT ( "**v=DKIM1; k=rsa; s=email; " "p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu5oIUrFDWZK7F4thFxpZa2or6jBEX3cSL6b2TJdPkO5iNn9vHNXhNX31nOefN8FksX94YbLJ8NHcFPbaZTW8R2HthYxRaCyqodxlLHibg8aHdfa+bxKeiI/xABRuAM0WG0JEDSyakMFqIO40ghj/h7DUc/4OXNdeQhrKDTlgf2bd+FjpJ3bNAFcMYa3Oeju33b2Tp+PdtqIwXR" "ZksfuXh7m30kuyavp3Uaso145DRBaJZA55lNxmHWMgMjO+YjNeuR6j4oQqyGwzPaVcSdOG8Js2mXt+J3Hr+nNmJGxZUUW4Uw5ws08wT9opRgSpn+ThX2d1AgQePpGrWOamC3PdcwIDAQAB**" ) ; ----- DKIM key 201510 for example.com
The value inside the parentheses is what you want. Select and copy the entire region from (but not including) the double-quote before
v=DKIM1on up to (but not including) the final double-quote before the closing parentheses. Then edit out the double-quotes within the copied text and the whitespace between them. From the above file the result would be:
v=DKIM1; k=rsa; s=email; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu5oIUrFDWZK7F4thFxpZa2or6jBEX3cSL6b2TJdPkO5iNn9vHNXhNX31nOefN8FksX94YbLJ8NHcFPbaZTW8R2HthYxRaCyqodxlLHibg8aHdfa+bxKeiI/xABRuAM0WG0JEDSyakMFqIO40ghj/h7DUc/4OXNdeQhrKDTlgf2bd+FjpJ3bNAFcMYa3Oeju33b2Tp+PdtqIwXRZksfuXh7m30kuyavp3Uaso145DRBaJZA55lNxmHWMgMjO+YjNeuR6j4oQqyGwzPaVcSdOG8Js2mXt+J3Hr+nNmJGxZUUW4Uw5ws08wT9opRgSpn+ThX2d1AgQePpGrWOamC3PdcwIDAQAB
Paste that into the value for the TXT record.
This is what the add TXT record screen will look like when you have it filled out:
Repeat this for every domain you handle mail for, using the
.txtfile for that domain.
Test your configuration
Test the keys for correct signing and verification using the
1 opendkim-testkey -d example.com -s YYYYMM
If everything is OK you shouldn’t get any output. If you want to see more information, add
-vvvto the end of the command. That produces verbose debugging output. The last message should be “key OK”. Just before that you may see a “key not secure” message. That’s normal and doesn’t signal an error, it just means your domain isn’t set up for DNSSEC yet.
Hook OpenDKIM into Postfix
- Create the OpenDKIM socket directory in Postfix’s work area and make sure it has the correct ownership:
1 2 mkdir /var/spool/postfix/opendkim chown opendkim:postfix /var/spool/postfix/opendkim
- Set the correct socket for Postfix in the OpenDKIM defaults file
1 2 3 4 5 6 7 8 9 10 # Command-line options specified here will override the contents of # /etc/opendkim.conf. See opendkim(8) for a complete list of options. #DAEMON_OPTS="" # # Uncomment to specify an alternate socket # Note that setting this will override any Socket value in opendkim.conf SOCKET="local:/var/spool/postfix/opendkim/opendkim.sock" #SOCKET="inet:54321" # listen on all interfaces on port 54321 #SOCKET="inet:12345@localhost" # listen on loopback on port 12345 #SOCKET="inet:email@example.com" # listen on 192.0.2.1 on port 12345
Uncomment the first SOCKET line and edit it so it matches the uncommented line in the above file. The path to the socket is different from the default because on Debian 8 the Postfix process that handles mail runs in a chroot jail and can’t access the normal location.
/etc/postfix/main.cfand add a section to activate processing of e-mail through the OpenDKIM daemon:
1 2 3 4 5 6 # Milter configuration # OpenDKIM milter_default_action = accept milter_protocol = 2 smtpd_milters = local:/opendkim/opendkim.sock non_smtpd_milters = local:/opendkim/opendkim.sock
You can put this anywhere in the file. The usual practice is to put it after the
smtpd_recipient_restrictionsentry. You’ll notice the path to the socket isn’t the same here as it was in the
/etc/defaults/opendkimfile. That’s because of Postfix’s chroot jail, the path here is the path within that restricted view of the filesystem instead of within the actual filesystem.
- Restart the OpenDKIM daemon so it sets up the correct socket for Postfix:
1 sudo service opendkim restart
- Restart Postfix so it starts using OpenDKIM when processing mail:
1 sudo service postfix restart
Verify that everything’s fully operational
The easiest way to verify that everything’s working is to send a test e-mail to
firstname.lastname@example.org an email client configured to submit mail to the submission port on your mail server. It will analyze your message and mail you a report indicating whether your email was signed correctly or not. It also reports on a number of other things such as SPF configuration and SpamAssassin flagging of your domain. If there’s a problem, it’ll report what the problem was.
Set up Author Domain Signing Practices (ADSP) (optional)
As a final item, you can add an ADSP policy to your domain saying that all emails from your domain should be DKIM-signed. As usual, it’s done with a TXT record for host
_adsp._domainkeyin your domain with a value of
dkim=all.The screen for the new text record will look like this:
You don’t need to set this up, but doing so makes it harder for anyone to forge email from your domains because recipient mail servers will see the lack of a DKIM signature and reject the message.
The reason the YYYYMM format is used for the selector is that best practice calls for changing the DKIM signing keys every so often (monthly is recommended, and no longer than every 6 months). To do that without disrupting messages in transit, you generate the new keys using a new selector. The process is:
- Generate new keys as in step 8 of “Configuring OpenDKIM”. Do this in a scratch directory, not directly in
/etc/opendkim/keys. Use the current year and month for the YYYYMM selector value, so it’s different from the selector currently in use.
- Use the newly-generated
.txtfiles to add the new keys to DNS as in the DKIM “Setting Up DNS” section, using the new YYYYMM selector in the host names. Don’t remove or alter the existing DKIM TXT records.
- Stop Postfix and OpenDKIM by doing a
sudo service postfix opendkim stopso that they won’t be processing mail while you’re changing out keys.
- Copy the newly-generated
.privatefiles into place and make sure their ownership and permissions are correct by running these commands from the directory in which you generated the key files:
1 2 3 cp *.private /etc/opendkim/keys/ chown opendkim:opendkim /etc/opendkim/keys/* chmod go-rw /etc/opendkim/keys/*
opendkim-testkeycommand as described above to ensure that your new record is propogated before you continue.
/etc/opendkim/key.tableand change the old YYYYMM values to the new selector, reflecting the current year and month. Save the file.
- Restart OpenDKIM and Postfix by:
1 2 sudo service opendkim restart sudo service postfix restart
Make sure they both start without any errors.
- After a couple of weeks, all email in transit should either have been delivered or bounced and the old DKIM key information in DNS won’t be needed anymore. Delete the old
YYYYMM._domainkeyTXT records in each of your domains, leaving just the newest ones (most recent year and month). Don’t worry if you forget and leave the old keys around longer than planned. There’s no security issue. Removing the obsolete records is more a matter of keeping things neat and tidy than anything else.
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
- Sender Policy Framework
- DomainKeys Identified Mail
- The Sender Policy Framework and DomainKeys Identified Mail Wikipedia pages should not be considered authoritative but do provide helpful discusson and additional references.
参考资料1 /etc/postfix/main.cf: 2 myhostname = hostname.example.com 3 myorigin = $mydomain 4 #relayhost = $mydomain 5 inet_interfaces = loopback-only 6 mydestination =