Tree


README.mdcommits | blame

README.md

# OpenBSD Mail Server Setup & Migration Guide

This guide walks through setting up a complete, production-ready OpenBSD mail environment: a primary server running OpenSMTPD, Dovecot, Sieve, Rspamd, Redis, and DKIM, paired with a minimal, base-only OpenBSD backup MX server.

Replace `example.com` / `example.net`, `<PRIMARY_IP>`, and `<BACKUP_IP>` with your own domains and IP addresses throughout.

---

## 1. DNS Prerequisites

Before configuring the servers, create the required DNS records for your primary mail host (`mx1.example.com`), backup MX (`mx2.example.com`), and every hosted domain.

### A Records
```dns
mx1	A	<PRIMARY_IP>
mail	A	<PRIMARY_IP>
smtp	A	<PRIMARY_IP>
mx2	A	<BACKUP_IP>
```

### PTR (Reverse DNS)
Configure `<PRIMARY_IP>` with your ISP or hosting provider so it resolves back to `mx1.example.com`.

### MX Records (for every hosted domain)
```dns
	MX	0 mx1.example.com.
	MX	10 mx2.example.com.
```

### SPF & DMARC (for every hosted domain)
```dns
	TXT	"v=spf1 ip4:<PRIMARY_IP> -all"
_dmarc	TXT	"v=DMARC1; p=none; rua=mailto:dmarc@example.com"
```

*(You will add the DKIM TXT record for each domain in Step 4 after generating the key.)*

---

## 2. Primary Server Preparation

### Install Required Packages
```sh
pkg_add dovecot dovecot-pigeonhole rspamd \
	opensmtpd-filter-rspamd opensmtpd-filter-dkimsign opensmtpd-table-passwd
```

### Set the Mail Hostname (`mailname`)
Set `/etc/mail/mailname` so OpenSMTPD announces `mx1.example.com` in `EHLO`, matching your PTR record:
```sh
echo "mx1.example.com" > /etc/mail/mailname
```

### Create the Virtual Mail User & Directories
```sh
useradd -m -s /sbin/nologin -d /home/vmail vmail
mkdir -p /etc/mail/dkim /etc/dovecot/sieve
chown _dkimsign:_dkimsign /etc/mail/dkim
chmod 700 /etc/mail/dkim
```

---

## 3. TLS Certificates (`httpd` & `acme-client`)

Issuing a single SAN certificate covering `mail.example.com`, `smtp.example.com`, and `mx1.example.com` avoids TLS/SNI mismatches across IMAP, SMTP submission, and inbound MX delivery.

### Minimal `/etc/httpd.conf` for HTTP-01 Challenges
```conf
server "mail.example.com" {
	listen on * port 80
	alias "smtp.example.com"
	alias "mx1.example.com"
	location "/.well-known/acme-challenge/*" {
		root "/acme"
		request strip 2
	}
	location * {
		block return 302 "https://$HTTP_HOST$REQUEST_URI"
	}
}
```

Enable and start `httpd`:
```sh
httpd -n && rcctl enable httpd && rcctl start httpd
```

### Configure `/etc/acme-client.conf`
```conf
authority letsencrypt {
	api url "https://acme-v02.api.letsencrypt.org/directory"
	account key "/etc/acme/letsencrypt-privkey.pem"
}

domain mail.example.com {
	alternative names { smtp.example.com mx1.example.com }
	domain key "/etc/ssl/private/mail.example.com.key"
	domain full chain certificate "/etc/ssl/mail.example.com.fullchain.pem"
	sign with letsencrypt
}
```

### Pull the Initial Certificate
```sh
acme-client -v mail.example.com
```

### Schedule Automated Renewals
Add a daily check to `root`'s crontab (`crontab -e`) so renewals automatically restart `smtpd` and reload `dovecot`:
```cron
~ 2 * * * acme-client mail.example.com && rcctl restart smtpd && rcctl reload dovecot
```

---

## 4. Generate DKIM Key & Publish DNS

Generate a 2048-bit RSA keypair for DKIM signing:
```sh
openssl genrsa -out /etc/mail/dkim/2026.key 2048
openssl rsa -in /etc/mail/dkim/2026.key -pubout -out /etc/mail/dkim/2026.pub
chown _dkimsign:_dkimsign /etc/mail/dkim/2026.key
chmod 600 /etc/mail/dkim/2026.key
```

Extract the single-line public key string:
```sh
awk '!/^---/' /etc/mail/dkim/2026.pub | tr -d '\n'; echo
```

Publish this TXT record in DNS for **every** hosted domain you send mail from:
```dns
2026._domainkey	TXT	"v=DKIM1; k=rsa; p=<PUBLIC_KEY_STRING>"
```

---

## 5. Configure OpenSMTPD (`/etc/mail/`)

### Create Lookup Tables

1. **`/etc/mail/domains`** — one hosted domain per line:
   ```text
   example.com
   example.net
   ```

2. **`/etc/mail/passwd`** — virtual user credentials. Generate password hashes with `smtpctl encrypt`:
   ```text
   user@example.com:$2b$10$...
   ```
   Set ownership and permissions so both `_smtpd` and `_dovecot` have read-only access (while `root` can still edit it):
   ```sh
   chown _smtpd:_dovecot /etc/mail/passwd
   chmod 440 /etc/mail/passwd
   ```

3. **`/etc/mail/virtuals`** — map incoming addresses and aliases to virtual mailboxes:
   ```text
   user@example.com	user@example.com
   alias@example.com	user@example.com
   user@example.net	user@example.com
   ```

### Configure `/etc/mail/smtpd.conf`
Repeat `-d <domain>` in `filter dkimsign` for every domain you send mail from:
```conf
pki mail.example.com cert	"/etc/ssl/mail.example.com.fullchain.pem"
pki mail.example.com key	"/etc/ssl/private/mail.example.com.key"

table aliases	db:/etc/mail/aliases.db
table domains	file:/etc/mail/domains
table passwd	passwd:/etc/mail/passwd
table virtuals	file:/etc/mail/virtuals

filter check_rdns phase connect match !rdns junk
filter check_fcrdns phase connect match !fcrdns junk
filter rspamd proc-exec "filter-rspamd"
filter dkimsign proc-exec "filter-dkimsign -d example.com -d example.net -s 2026 -k /etc/mail/dkim/2026.key" user _dkimsign group _dkimsign

smtp max-message-size 50M

listen on lo0
listen on egress port 25 tls pki mail.example.com \
	filter { check_rdns, check_fcrdns, rspamd }
listen on egress port 465 smtps pki mail.example.com auth <passwd> \
	filter dkimsign
listen on egress port 587 tls-require pki mail.example.com auth <passwd> \
	filter dkimsign

action "local_mail" mbox alias <aliases>
action "lmtp_deliver" lmtp "/var/dovecot/lmtp" rcpt-to virtual <virtuals>
action "outbound" relay

match from any for domain <domains> action "lmtp_deliver"
match from local for local action "local_mail"
match from auth for any action "outbound"
match from local for any action "outbound"
```

Validate the configuration:
```sh
smtpd -n
```

---

## 6. Configure Dovecot & Sieve (`/etc/dovecot/`)

### Increase File Descriptor Limits
Create `/etc/login.conf.d/dovecot` so Dovecot does not hit OpenBSD's default `daemon` open-file limits:
```conf
dovecot:\
	:openfiles-cur=1024:\
	:openfiles-max=2048:\
	:tc=daemon:
```

### Self-Contained `/etc/dovecot/dovecot.conf`
Back up the stock configuration to avoid conflicts with `conf.d/*` defaults:
```sh
mv /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf.orig
```

Create a clean `/etc/dovecot/dovecot.conf`:
```conf
protocols = imap lmtp

ssl = required
ssl_cert = </etc/ssl/mail.example.com.fullchain.pem
ssl_key = </etc/ssl/private/mail.example.com.key
ssl_min_protocol = TLSv1.2
ssl_prefer_server_ciphers = yes

auth_mechanisms = plain login

mail_location = maildir:/home/vmail/%d/%n/Maildir
mail_uid = vmail
mail_gid = vmail
first_valid_uid = 1000

passdb {
	driver = passwd-file
	args = scheme=BLF-CRYPT username_format=%u /etc/mail/passwd
}

userdb {
	driver = static
	args = uid=vmail gid=vmail home=/home/vmail/%d/%n
}

namespace inbox {
	inbox = yes

	mailbox Drafts {
		auto = subscribe
		special_use = \Drafts
	}
	mailbox Junk {
		auto = subscribe
		special_use = \Junk
	}
	mailbox Sent {
		auto = subscribe
		special_use = \Sent
	}
	mailbox Trash {
		auto = subscribe
		special_use = \Trash
	}
}

service lmtp {
	unix_listener lmtp {
		mode = 0660
		user = _smtpd
		group = _dovecot
	}
}

protocol lmtp {
	mail_plugins = $mail_plugins sieve
}

plugin {
	sieve = file:~/sieve;active=~/.dovecot.sieve
	sieve_before = /etc/dovecot/sieve/spam-to-junk.sieve
}
```

### Global Spam-to-Junk Sieve Rule
Create `/etc/dovecot/sieve/spam-to-junk.sieve`:
```sieve
require ["fileinto"];

if header :contains "X-Spam" "Yes" {
	fileinto "Junk";
	stop;
}
```

Compile the Sieve script and validate Dovecot:
```sh
sievec /etc/dovecot/sieve/spam-to-junk.sieve
doveconf -n > /dev/null
```

---

## 7. Configure Rspamd & Redis (`/etc/rspamd/local.d/`)

### Connect Rspamd to Redis
Create `/etc/rspamd/local.d/redis.conf` to enable Bayes learning, greylisting, and ratelimiting:
```conf
servers = "127.0.0.1";
```

### Whitelist Backup MX from SPF Failures
Create `/etc/rspamd/local.d/settings.conf` so queued mail forwarded from `mx2` is not penalized for SPF mismatches:
```conf
backup_mx {
	ip = ["<BACKUP_IP>"];
	apply {
		symbols_disabled = ["R_SPF_FAIL", "R_SPF_SOFTFAIL"];
	}
}
```

Validate the Rspamd configuration:
```sh
rspamadm configtest
```

---

## 8. Firewall & Services (Primary Server)

1. Allow inbound TCP ports `25`, `80` (ACME), `465`, `587`, and `993` in `/etc/pf.conf`:
   ```conf
   pass in on egress proto tcp to port { 25, 80, 465, 587, 993 }
   ```
   Validate and reload PF:
   ```sh
   pfctl -nf /etc/pf.conf && pfctl -f /etc/pf.conf
   ```

2. Enable and start the mail stack (start `redis` before `rspamd`):
   ```sh
   rcctl enable redis rspamd dovecot smtpd
   rcctl start redis rspamd dovecot
   rcctl restart smtpd
   ```

---

## 9. Backup MX Server Setup (`mx2`)

The backup MX requires **no third-party packages, Dovecot, Rspamd, or TLS certificates**—only OpenBSD's base `smtpd`.

1. Set `/etc/mail/mailname` to your backup MX hostname:
   ```sh
   echo "mx2.example.com" > /etc/mail/mailname
   ```

2. Generate a random queue encryption key:
   ```sh
   openssl rand -hex 16
   ```

3. Replace `/etc/mail/smtpd.conf` with the minimal backup configuration:
   ```conf
   queue compression
   queue encryption <HEX_KEY>
   queue ttl 7d

   table aliases		db:/etc/mail/aliases.db
   table hosted_domains	{ example.com, example.net }

   smtp max-message-size	50M

   listen on lo0
   listen on egress

   action "local" mbox alias <aliases>
   action "outbound" relay
   action "backup_mx" relay backup mx mx2.example.com

   match from any for domain <hosted_domains> action "backup_mx"
   match from local for local action "local"
   match from local for any action "outbound"
   ```

4. Allow inbound TCP port `25` in `/etc/pf.conf`, then validate, enable, and restart `smtpd`:
   ```sh
   pfctl -nf /etc/pf.conf && pfctl -f /etc/pf.conf
   smtpd -n && rcctl enable smtpd && rcctl restart smtpd
   ```

---

## 10. Mail Client Configuration

Use the following settings in your mail client:

| Setting | Value |
| --- | --- |
| **Username** | Full email address (`user@example.com`) |
| **IMAP Server** | `mail.example.com`, Port `993` (SSL/TLS) |
| **SMTP Server** | `smtp.example.com`, Port `465` (SMTPS) or `587` (STARTTLS) |

### NeoMutt Snippet (`neomuttrc`)
Define `folder` **before** `spoolfile`, `trash`, `record`, and `postponed` so the `+` shortcut expands correctly:
```muttrc
set folder = "imaps://mail.example.com"
set spoolfile = "+INBOX"
set trash = "+Trash"
set record = "+Sent"
set postponed = "+Drafts"
```

---

## 11. Post-Migration Verification Checklist

- [ ] Send a test email from an external provider (e.g., Gmail) to verify inbound delivery, `X-Spam` headers, and Sieve routing.
- [ ] Send a test email outbound to verify SPF, DKIM, and DMARC alignment (check raw headers on the receiving side).
- [ ] Temporarily stop `smtpd` on the primary server (`rcctl stop smtpd`), send an external test email to confirm `mx2` queues it (`smtpctl show queue`), then restart `smtpd` on the primary to verify delivery and confirm Rspamd didn't flag SPF.
- [ ] Test certificate renewal dry-run and verify `/etc/ssl/mail.example.com.fullchain.pem` includes all three SANs (`openssl x509 -in /etc/ssl/mail.example.com.fullchain.pem -noout -text | grep DNS:`).