# Have your Email server support the latest internet technology

To be up to date with latest internet (security) technology your email server needs to handle IPv6, measures against forgery (SPF, DKIM and DMARC), encrypt the transport of mail, i.e. use TLS in connection with DANE and run under a domain that is protected by DNSSEC on a hosting service that implements route authorization. That's quite a bunch of requirements and not even all of the big email providers are handling all of them well. So let's give it a try. This post deals with setting up all required features on a mail system using Exim4 as MTA on a Debian or Ubuntu installation.

[SIDN](https://www.sidn.nl), the organization that manages the .nl-top-level-domain, has built a nice site where you can test your mail server on how it performs in all the categories that are mentioned above. ([https://internet.nl/test-mail/](https://internet.nl/test-mail/)). In the following we will go through all topics the site will test on your email server.

## IPv6

The first topic on the list of the mail test is whether your mail server can be reached via IPv6.

The first hurdle is that at least two of the name servers that are handling your domain need to be reachable over IPv6. Depending on who owns these name servers this might be not so much in your control but otherwise it is unlikely that nowadays any decent domain name registrar is providing you with name servers that can't handle IPv6.

Next you need to set up a quad-A record that resolves the name of your mail server to an IPv6 address.

If both of the two requirements from above are fulfilled we need to check if Exim4 is listening also on IPv6 addresses. A look in `/etc/exim4/update-exim4.conf.conf` will show which addresses are configured.

If `dc_local_interfaces` has only IPv4 addresses you need to add your IPv6 addresses. This could either be the localhost address ::1, your actual IPv6 address, or a ::0 to listen on all interfaces.

`update-exim4.conf` will update your Exim4 configuration and a `systemctl reload exim4` will read the new configuration.

With 'show sockets', i.e. the `ss` command, we can check which process is listening on which address on port 25

~~~
~~~

The listing should now also include your IPv6 addresses.

## DNSSEC

[DNSSEC](https://de.wikipedia.org/wiki/Domain_Name_System_Security_Extensions) is a cryptographic security extension to DNS. With DNSSEC a name server attaches a digital signature to the delivery of records to a client that is posting a request. With this signature the authenticity of the DNS reply can be checked. Again, unless you operate your own name servers,  DNSSEC is probably offered by your domain name registrar and you can activate it in the settings for your domain.

## SPF

The idea of Sender Policy Framework (SPF) is to publish a list of valid IP addresses that are authorized to send mail in behalf of your mail domain. The list is published via a DNS TXT record. Receiving MTAs can then poll the DNS for the domain they are apparently receiving mail from and check if the IP address that is currently connected to them is actually allowed to deliver mail for this domain.

In order to implement SPF  on both ends you need to publish SPF information for your domain as well as check the domains of all incoming mails for their SPF information.

By advertising the policy for your domain through a TXT record in the DNS  all receiving serves that get mail from your server can check that they received that mail from an authorized server. In the TXT record the valid IP addresses that are authorized to send mail for your domain are either directly listed or pointed to by A, quad-A, MX records and some more mechanisms. How this text can be assembled is documented for example in the [SPF Wikipedia article](https://en.wikipedia.org/wiki/Sender_Policy_Framework#Implementation).

For an entry that would be sufficient for a server that is sending mail from a single IP address the entry could looks like this:

~~~
v=spf1 ip4:198.51.100.123 -all
~~~

The policy basically says that mail for this domain can only originate form the IP address 198.51.100.123, for anything else, the mail should be rejected.

In order to check incoming mail for SPF, both Debian and Ubuntu's Exim4 already has a prepared section in it's Check_rcpt access control list config file (30_exim4-config_check_rcpt). In order to activate it you need to set CHECK_RCPT_SPF to true. This is best done in /etc/exim4/conf.d/main/000_localmacros by adding

~~~
CHECK_RCPT_SPF = yes
~~~

This is all you have to do, in theory. Unfortunately, the Exim versions in Debian and Ubuntu are differing in how they implement SPF checking.

### Two distributions, a library, and a bug 

SPF support for Exim started within the [Exiscan patch](https://duncanthrax.net/exiscan-acl/). In version 4.34-22 from May 2004 support for SPF via the libspf_alt library (renamed to libspf2 later on), was introduced. With the release of Exim 4.50 the Exiscan patch became an integral part of Exim.

However, the Debian Maintainers did not adopt SPF testing via libspf and chose not to compile Exim against libspf2. Instead they introduced an alternative way for SPF verification by using `spfquery` from [Mail::SPF](https://metacpan.org/release/MBRADSHAW/Mail-SPF-3.20260331/source/README), a Perl implementation of SPF and provided in Debian via the `spf-tools-perl` package.

In 2021, when with Exim 4.91 SPF was no longer an experimental feature and was included in Exim's documentation ([Link to Exim's current SPF chapter](https://www.exim.org/exim-html-current/doc/html/spec_html/ch-dkim_spf_srs_and_dmarc.html)), the Debian maintainers changed their perception and with Exim 4.95 they switched to the upstream way of handling SPF.

The Ubuntu maintainers had their [reservations](https://bugs.launchpad.net/ubuntu/+source/exim4/+bug/1952738) regarding the usage of libspf2. They still didn't like the idea to link to an additional library. To make it even more complicated, it would mean that Exim, a package from the main part of the distribution, i.e. actively maintained by Ubuntu, depends on a library from the universe part which is not maintained by Ubuntu directly. On top of that, the upstream source of libspf2 seems to be quite unmaintained since a long while. So the Ubuntu maintainers did not compile Exim against `libspf2` and stayed with using `spfquery` from Mail::SPF as a helper tool. So, if you are using Ubuntu, don't forget to check that `spf-tools-perl` is installed, it is not a dependency of any of the Exim packages.

At this point it is probably a good idea to explain briefly how the SPF checking works in Exim both with libspf2 and the Perl implementation `spfquery` as a helper.

SPF verification kicks in during SMTP at the point where the sending MTA is giving the RCPT TO command. At this point Exim knows the IP where the sending MTA is contacting from and it knows the domain from which the email is supposedly coming from through the domain part of the sender email that was given in the MAIL FROM command in the previous step.

Exim now goes through the the Access Control List that is activated at this state of SMTP. It is defined by `acl_smtp_rcpt` and in Debian and Ubuntu this is `30_exim4-config_check_rcpt` located in `/etc/exim4/conf.d/acl/`. As already mentioned above, when the CHECK_RCPT_SPF macro is set to true the SPF part in this ACL is active. In both Debian and Ubuntu there are the following tasks to be done:

- deny the mail when SPF check fails
- defer the mail when there is a temporary DNS error and SPF check can't be done at the moment
- accept the mail in all other cases and add a header line with the actual SPF condition encountered.

With the native libspf2 solution used in Debian this is very easy:

~~~
deny
    spf = fail
~~~

for denying failed SPF,

~~~
defer
    spf = temperror
~~~

defer, when there is a temporary error and

~~~
warn
    spf = pass:softfail:neutral:permerror
    add_header = $spf_received
~~~

add a header line with the SPF checking outcome (available in Exim in the variable `$spf_received`) whenever SPF passes, there is a soft failure, a neutral policy or a permanent error.

The solution using `spfquery` is basically doing the same. But here the actual check result as to be filtered out of a medium complex string expansion that has `spfquery` as an external program in a `${run ...}` operator.

The `deny` section has the call to `spfquery`

~~~
deny
    condition = ${run{/usr/bin/spfquery.mail-spf-perl \
                   --ip ${quote:$sender_host_address} \
                   --scope mfrom \
                   --identity ${quote:$sender_address}} \
                   {no}{${if eq {$runrc}{1}{yes}{no}}}}
~~~

In the expansion the sending MTA's IP address (`$sender_host_address`) and the sender address (`$sender_address`) are handed over to `spfquery`. When the SPF check result is ok, `spfquery` issues an exit status of 0, which triggers a 'false' (`{no}`), the condition fails and the message is not denied. All other exit status values are evaluated in the subsequent if statement. In `$runrc` the exit status of the last executed `${run ...}` operator is available and when it equals `1`, `spfquery`'s exit state for a failed SPF check, the condition is 'true' (`{yes}`) and the message gets denied. All other exit codes render the condition 'true' so the message is only denied for exit status `1`.

Subsequently, the exit status of `spfquery` is examined.

~~~
defer
    condition = ${if eq {$runrc}{5}{yes}{no}}
~~~

When it is `5`, the message is deferred for a temporary DNS failure.

~~~
warn
    condition = ${if <={$runrc}{6}{yes}{no}}
~~~

When it is smaller or equal to `6`, the code continues to add a  header line to include the outcome of the SPF check. The correct content of the header line is determined through a long string expansion term. An additional `warn` instruction creates an 'Unexpected SPF error' log entry, when `spfquery`'s exit status is above 6. 

Due to the various string expansions the Ubuntu solution is a bit harder to comprehend but working fine as well. This was at least until [Exim changed the way that the `${run ...}` expression is expanded](https://utcc.utoronto.ca/~cks/space/blog/sysadmin/EximRunQuotingChange). This happened with Exim 4.96 in summer of 2022 and it affects quoting. As you can see in the `${run ...}` call in the deny section, the variables are quoted using the `${quote:<string>}` operator.

With the string expansion change in Exim 4.96 the `$sender_address` gets double quoted and as a result that the string expansion is not working as intended anymore. It mostly produces an exit state of `6`. i.e. "none" as a result. It took a while until this was covered in a [launchpad bug report](https://bugs.launchpad.net/ubuntu/+source/exim4/+bug/2056372) but it is still not fixed. So the SPF section in Ubuntu's take of the RCPT TO ACL is non-functional since four years as the time of writing this.

### How to fix it

The fix - you might have guessed - is quite simple. Just remove the `${quote:<string>}` operators from the two variables involved. this results in

~~~
deny
    condition = ${run{/usr/bin/spfquery.mail-spf-perl \
                   --ip $sender_host_address \
                   --scope mfrom \
                   --identity $sender_address} \
                   {no}{${if eq {$runrc}{1}{yes}{no}}}}
~~~

Due to the new expansion mechanism, the variables still get quoted so I don't see a big security risk here.

So, after this long and maybe a bit too detailed explanation your mail server system should now utilize SPF both to protect your email domain and to improve the quality of your incoming mail.

## DKIM

DKIM stands for DomainKeys Identified Mail. When configured, the digital signature of the sending MTA is added to every outgoing mail. Receiving MTAs can verify these signatures by checking them with the public key of the signing mail server that is published via DNS.

### Signing outgoing messages

Let's start with signing the outgoing messages of our mail server and publishing the public key in a DNS TXT record.



### Checking signatures on incoming messages

Now let's continue with verifying incoming messages. Exim verifies DKIM signatures whenever they are found in a message that is received. You can set the variable `dkim_disable_verify` to exclude messages from being checked.

In Debian and Ubuntu's configuration this DKIM checking is disabled for all mail that is sent via local SMTP, i.e. not via TCP/IP, via an authenticated connection, i.e. via the submission port, or if the mail is deliverd by a relay server in case you have configured this. The DKIM check is also skipped if the mail server is set to minimal DNS (this is highly uncommon, it makes sense for mail servers that would need to avoid going online for every DNS request) or if DKIM checking is deliberately disabled by setting the macro DISABLE_DKIM_VERIFY to true.
