Generating TLS Keys for DKIM & OpenSMTPD

by jon 2024-4-5

Once you know how email works, you might come across the situation where you need to setup some email verification.  Generating keys is very easy to do, but it's tricky to remember the syntax.

DKIM

# Filenames
PRIV_KEY=private.key
PUB_KEY=public.key

# DKIM Private signing key
openssl genrsa -out $PRIV_KEY 1024

# DKIM Public key, for DNS record
openssl rsa -in $PRIV_KEY -pubout -out $PUB_KEY

Then the public key must be put into a DNS record. The DNS record name is the 'selector' name. So if you want the 'selector' of 'mali', then create a DNS record called: mail._domainkey.DOMAIN-NAME.COM. Set the value of the record as:

v=DKIM1; k=rsa; p=PUBLIC_KEY_HERE

Do not include the -----BEGIN PUBLIC KEY.... stuff. Just the key, as a single string.

TLS Certificate (Self-Signed)

# Variables
DAYS=3650 # so it doesn't expire unexpectly soon
KEY_FILE=tls_key.pem
CERT_FILE=tls_cert.pem

# Generate key
openssl genrsa -out $KEY_FILE 4096

# Generate cert
openssl req -x509 -new -nodes -key $KEY_FILE -out $CERT_FILE -days $DAYS -sha256

Configure DKIM Proxy

You might use this dkimproxy_out.conf configuration:

# For incoming messages
listen 127.0.0.1:10027

# Relay back out
relay 127.0.0.1:10028

# Domains
domain your-domain.com,your-second-domain.com

# What to add
signature dkim(c=relaxed)
signature domainkeys(c=nofws)

# Signing key
keyfile /path/to/dkim/private.key

# Selector
selector mail

Configure OpenSMTPD as Outbound Relay

This configuration doesn't accept mail, but it relays mail with an authenticated user:

# Setup TLS certificates
pki "mail" cert "/path/to/tls_cert.pem"
pki "mail" key "/path/to/tls_key.pem"

# Tables
table credentials passwd:/etc/mail/credentials

# Listen
## main listener for outbound messages
listen on vtnet0 port 587 tls-require pki mail auth 

## accept mail from dkimproxy after it signs messages
listen on localhost port 10028 tag DKIM

# Available actions
## sends mail externally
action "outbound" relay

## send mail to dkimproxy for signing
action "relay_dkim" relay host smtp://127.0.0.1:10027

# Rule routing
## if message has been signed, relay it outbound
match tag DKIM for any action "outbound"

## if connection is authenticated, send it to dkimproxy for signing
match auth from any for any action "relay_dkim"