From 3fb2b9563d9b58a9683808c6620832dc71f76b20 Mon Sep 17 00:00:00 2001 From: Sam Chudnick Date: Thu, 8 Dec 2022 20:44:37 -0500 Subject: Initial commit --- articles/mail-server.html | 723 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 723 insertions(+) create mode 100644 articles/mail-server.html (limited to 'articles/mail-server.html') diff --git a/articles/mail-server.html b/articles/mail-server.html new file mode 100644 index 0000000..12a3264 --- /dev/null +++ b/articles/mail-server.html @@ -0,0 +1,723 @@ + + + + + + + + + + +

Postfix and Dovecot Mail Server

+
+ +

Postfix and dovecot will be the two primary pieces of our mail sever. +Postfix is the mail transport agent that handles the sending and +receiving of mail and dovecot is the IMAP server that will allow us to +access our mail from a mail client such as mutt. The server will also +have several other supporting components, a complete list of which is:

+ + + +

You can use +this script I have written to automate this process, but I would +recommend that you run through the tutorial first to understand +what is being done.

+ +

Please note that this tutorial is loosely intended for small personal mail +servers. Using PAM for authentication, as is done here, is not a scalable solution +for working with a large number of users. I do plan on covering Dovecot LDAP +authentication at some point which would be a better solution in an enterprise +setting.

+ +

Install Packages

+

Let's start by installing the required packages. Note that if you already +have Apache installed on the server, replace python3-certbot-nginx +with python3-certbot-apache.

+
apt install postfix dovecot-imapd dovecot-sieve opendkim opendkim-tools spamassassin gnupg postgrey postfix-policyd-spf-python opendmarc dbconfig-no-thanks certbot python3-certbot-nginx
+

During the installation of Postfix you will get a Debconf prompt in which +you need to select "Internet Site" and then provide your domain name, +example.com.

+ +

Get a certificate

+

Now we'll use Certbot to get a certificate for our server. If you are +using Apache replace nginx with apache2.

+ +
systemctl stop nginx
+certbot certonly --standalone -d mail.example.com 
+systemctl start nginx
+ +

Postfix Main Configuration

+

In this section we will be doing the bulk of the postfix configuration. +The postconf command used throughout appends (or changes) +the specified configuration item in /etc/postfix/main.cf

+ +

Network Configuration

+ +

Let's start by configuring some network and domain information.

+ +
postconf -e "myorigin = example.com"
+postconf -e "mydestination = \$myhostname, \$mydomain, localhost"
+postconf -e "mynetworks = 127.0.0.0/8 [::1]/128"
+postconf -e "myhostname = mail.example.com"
+
+ +

Next, point postfix to the cerbot key and certificate, as well as the distro's +CA certificates.

+ +
postconf -e "smtpd_tls_key_file=/etc/letsencrypt/live/mail.example.com/privkey.pem"
+postconf -e "smtpd_tls_cert_file=/etc/letsencrypt/live/mail.example.com/fullchain.pem"
+postconf -e "smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt"
+
+ +

Harden the TLS configuration by forcing strong +protocols and ciphers, and requiring that authentication occur only over an +encrypted session.

+
# Require authentication over TLS and optionally use it for sending and receiving mail
+postconf -e "smtpd_tls_auth_only = yes"
+postconf -e "smtpd_tls_security_level = may"
+postconf -e "smtp_tls_security_level = may"
+
+# Force the use of TLSv1.2 or TLSv1.3
+postconf -e 'smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
+postconf -e 'smtpd_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
+postconf -e 'smtp_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
+postconf -e 'smtp_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
+
+# Prefer server ciphers
+postconf -e "tls_preempt_cipherlist = yes"
+
+# Force strong ciphers
+postconf -e "smtpd_tls_ciphers = high"
+postconf -e "smtpd_tls_mandatory_ciphers = high"
+postconf -e "smtp_tls_ciphers = high"
+postconf -e "smtp_tls_mandatory_ciphers = high"
+postconf -e "smtpd_tls_exclude_ciphers = aNULL, eNULL, EXP, LOW, MEDIUM, PSK, SRP, SHA1, kRSA, CAMELLIA, ARIA, DSS, RSA+AES, ADH, AECDH"
+postconf -e "smtp_tls_exclude_ciphers = aNULL, eNULL, EXP, LOW, MEDIUM, PSK, SRP, SHA1, kRSA, CAMELLIA, ARIA, DSS, RSA+AES, ADH, AECDH"
+
+ +

Local Recipients and Aliases

+ +

Here we configure the bulk of the postfix built-in security settings which are +structured as a series of access restrictions. Do not edit these settings without +first reading the Postfix documentation as an incorrect change could inadvertently +make your server an open relay.

+ +
postconf -e "smtpd_helo_required = yes"
+postconf -e "smtpd_sender_login_maps = proxy:hash:/etc/postfix/login_maps"
+postconf -e "smtpd_helo_restrictions = reject_unknown_helo_hostname, reject_non_fqdn_helo_hostname" 
+postconf -e "smtpd_sender_restrictions = reject_sender_login_mismatch, reject_non_fqdn_sender, reject_unknown_sender_domain"
+postconf -e "smtpd_recipient_restrictions = reject_non_fqdn_recipient, reject_unknown_recipient_domain, permit_sasl_authenticated, reject_unauth_destination, check_policy_service unix:private/postgrey, check_policy_service unix:private/policyd-spf, reject_rbl_client zen.spamhaus.org"
+postconf -e "smtpd_relay_restrictions = permit_sasl_authenticated, reject_unauth_destination"
+postconf -e "smtpd_data_restrictions = reject_unauth_pipelining"
+
+# Disable VRFY command to prevent harvesting of user accounts on system
+postconf -e "disable_vrfy_command = yes"
+
+# Change smptd banner (hide distribution)
+postconf -e "smtpd_banner = \$myhostname ESMTP \$mail_name"
+ +

Now, configure the local mail recipients and some aliases. We'll create +an account called mailadmin to receive mail addressed to +several other accounts. This is to keep administrative mail separate, but +you can certainly alias these to your main account later if you would prefer to see +it there.

+ +
# Set a custom local_recipient_maps here in order to avoid accepting mail for all local accounts
+postconf -e "local_recipient_maps = proxy:hash:/etc/postfix/local_maps \$alias_maps"
+
+# You will need to manually set a password later to login as mailadmin
+adduser --disabled-login --shell /usr/sbin/nologin --gecos "" mailadmin
+echo "# postfix aliases
+postmaster:     mailadmin
+root:           mailadmin
+dmarc:          mailadmin
+" > /etc/aliases
+
+# Update address databases
+echo "mailadmin@mail.example.com    mailadmin" > /etc/postfix/login_maps
+echo "mailadmin mailadmin" > /etc/postfix/local_maps
+newaliases
+postmap /etc/postfix/login_maps
+postmap /etc/postfix/local_maps
+
+ +

Mail Delivery

+ + +

These commands configure our mail delivery preferences. Mail will be +delivered inside a user's home folder with a maildir-style mailbox using +dovecot.

+ +
# Maildir delivery to $HOME/Mail/Inbox/
+postconf -e "home_mailbox = Mail/Inbox/"
+# Deliver mail with Dovecot
+postconf -e "mailbox_command = /usr/lib/dovecot/deliver"
+ +

Header and Body Checks

+ +

Header and body checks allow for some simple content filtering within Postfix. +This is done by scanning a message line by line for a configured regex string, +nothing more. For example, the first header check listed will reject a message +with an attachment of ransomware.exe but will not block it if sent with +no extension. This is mostly a protection against uneducated users and poorly +written mail clients. Other checks block vulnerabilities and improve privacy.

+ +

Create a new file /etc/postfix/header_checks, then open it in a +text editor and add the following

+
# Block files with common executable extensions
+/name=[^>]*\.(exe|pif|com|dll|vbs|bat|sh|bash|so|zip|tar|gz|cpio)/ REJECT
+
+# Block message/partial vulnerability
+/message\/partial/ REJECT
+
+# Remove Received string that is created when spamassassin reinjects message into postfix
+# This is to prevent leaking the userid of the spamassassin user
+/^Received:.*userid.*/  IGNORE
+
+# Remove User-Agent strings from headers
+/^User-Agent: .*/       IGNORE
+ +

Create another new file /etc/postfix/body_checks, and add this

+
# Block messages with iframes
+/<iframe/ REJECT" > /etc/postfix/body_checks
+ +

And then run these commands to point postfix to the check files.

+
postconf -e "header_checks = regexp:/etc/postfix/header_checks"
+postconf -e "body_checks = regexp:/etc/postfix/body_checks"
+ +

Postfix Master Configuration

+

SMTP client

+

This simple command configures the SMTP client process that is responsible +for sending your mail to other mail servers.

+ +
postconf -M "smtp/unix=smtp unix - - y - - smtp"
+ +

Postscreen and SMTP Recipient

+

Postscreen is a kind of firewall that sits in front of the Postfix SMTPD +process and receives all incoming traffic. Postscreen will drop connections +from IPs on a DNS blacklst, or from clients that violate the SMTP protocol by +speaking out of turn or sending non-SMTP commands. This adds up to less spam +connections and therefore a much lighter workload for your server.

+ +
postconf -M "smtp/inet=smtp inet n - y - 1 postscreen"
+postconf -M "smtpd/pass=smtpd pass - - y - - smtpd"
+postconf -P "smtpd/pass/content_filter=spamassassin"
+postconf -M "tlsproxy/unix=tlsproxy unix - - y - 0 tlsproxy"
+postconf -M "dnsblog/unix=dnsblog unix - - y - 0 dnsblog"
+postconf -e "postscreen_dnsbl_sites = zen.spamhaus.org"
+postconf -e "postscreen_dnsbl_action = enforce"
+postconf -e "postscreen_greet_action = enforce"
+
+ +

Submission over TLS (submissions)

+

Submission over TLS (aka submissions) is the process you will use to submit +mail to your server from a mail client. These commands configure submissions to +use a fully-encrypted session, as opposed to STARTTLS, and to only allow access +to authenticated clients.

+ +
postconf -M "submissions/inet=submissions inet n - y - - smtpd"
+postconf -P "submissions/inet/smtpd_tls_wrappermode=yes"
+postconf -P "submissions/inet/smtpd_tls_security_level=encrypt"
+postconf -P "submissions/inet/smtpd_tls_auth_only=yes"
+postconf -P "submissions/inet/smtpd_sasl_auth_enable=yes"
+postconf -P "submissions/inet/smtpd_client_restrictions=permit_sasl_authenticated,reject"
+postconf -P "submissions/inet/smtpd_helo_restrictions="
+postconf -P "submissions/inet/smtpd_sender_restrictions=reject_sender_login_mismatch"
+postconf -P "submissions/inet/smtpd_recipient_restrictions=reject_non_fqdn_recipient,reject_unknown_recipient_domain,permit_sasl_authenticated,reject"
+postconf -P "submissions/inet/syslog_name=postfix/submissions"
+postconf -P 'submissions/inet/smtpd_tls_protocols=!SSLv2,!SSLv3,!TLSv1,!TLSv1.1'
+postconf -P 'submissions/inet/smtpd_tls_mandatory_protocols=!SSLv2,!SSLv3,!TLSv1,!TLSv1.1'
+ +

OPTIONAL - submission with mandatory STARTTLS

+

Having configured submission over TLS on port 465 this step is optional. +STARTTLS is considered by some to be less secure than full-session TLS and +may be vulnerable to exploitation.

+ +
postconf -M "submission/inet=submission inet n - y - - smtpd"
+postconf -P "submission/inet/smtpd_tls_security_level=encrypt"
+postconf -P 'submission/inet/smtpd_tls_protocols=!SSLv2,!SSLv3,!TLSv1,!TLSv1.1'
+postconf -P 'submission/inet/smtpd_tls_mandatory_protocols=!SSLv2,!SSLv3,!TLSv1,!TLSv1.1'
+postconf -P "submission/inet/smtpd_sasl_auth_enable=yes"
+postconf -P "submission/inet/smtpd_tls_auth_only=yes"
+postconf -P "submission/inet/syslog_name=postfix/submission"
+postconf -P "submission/inet/smtpd_helo_restrictions="
+postconf -P "submission/inet/smtpd_client_restrictions=permit_sasl_authenticated,reject"
+postconf -P "submission/inet/smtpd_helo_restrictions="
+postconf -P "submission/inet/smtpd_sender_restrictions=reject_sender_login_mismatch"
+postconf -P "submission/inet/smtpd_recipient_restrictions=reject_non_fqdn_recipient,reject_unknown_recipient_domain,permit_sasl_authenticated,reject"
+
+ +

SpamAssassin Configuration

+

Finally, this command tells Postfix how to interact with SpamAssassin.

+ +
postconf -M "spamassassin/unix=spamassassin unix - n n - - pipe user=debian-spamd argv=/usr/bin/spamc --socket=/var/run/spamd.sock -e /usr/sbin/sendmail -oi -f \${sender} \${recipient}" 
+ +

Dovecot Configuration

+

Dovecot configuration is usually split up into many different files under +/etc/dovecot/conf.d/ but here will be doing all of the +configuration in the primary config file +/etc/dovecot/dovecot.conf. Open that file with your editor +of choice, clear all of its contents, and then replace it with the following.

+ +
# /etc/dovecot/conf.d/10-auth.conf
+disable_plaintext_auth = yes
+auth_username_format = %n
+auth_mechanisms = plain
+userdb {
+	driver = passwd
+}
+passdb {
+	driver = pam
+}
+
+# /etc/dovecot/conf.d/10-mail.conf
+mail_location = maildir:~/Mail:INBOX=~/Mail/Inbox:LAYOUT=fs
+namespace inbox {
+	type = private
+	prefix = 
+	separator = /
+	inbox = yes
+	subscriptions = yes
+	list = yes
+}
+
+# /etc/dovecot/conf.d/10-master.conf
+service imap-login {
+# Run login processes in high-security mode (see: LoginProcess.txt in dovecot docs)
+service_count = 1
+# Disable unencrypted IMAP by setting port for plain IMAP to 0
+	inet_listener imap {
+		port = 0
+	}
+	inet_listener imaps {
+		port = 993
+		ssl = yes
+	}
+}
+
+# Allow postfix to use dovecot SASL
+service auth {
+	unix_listener /var/spool/postfix/private/auth {
+		mode = 0660
+		user = postfix
+		group = postfix
+	}
+}
+
+# /etc/dovecot/conf.d/10-ssl.conf
+ssl = required
+ssl_key = </etc/letsencrypt/live/mail.example.com/privkey.pem
+ssl_cert = </etc/letsencrypt/live/mail.example.com/fullchain.pem
+ssl_client_ca_dir = /etc/ssl/certs
+ssl_dh = </usr/share/dovecot/dh.pem
+
+# Mozilla intermediate compatibility
+ssl_min_protocol = TLSv1.2
+ssl_cipher_list = ECDHE+ECDSA+AESGCM:ECDHE+aRSA+AESGCM:ECDHE+ECDSA+CHACHA20:ECDHE+aRSA+CHACHA20:DHE+aRSA+AESGCM:!aNULL:!eNULL
+
+ssl_prefer_server_ciphers = yes
+ssl_client_require_valid_cert = yes
+
+
+# /etc/dovecot/conf.d/15-lda.conf
+protocol lda {
+	mail_plugins = \$mail_plugins sieve
+}
+
+# /etc/dovecot/conf.d/15-mailboxes.conf
+namespace inbox {
+	mailbox Sent {
+			special_use = \Sent
+			auto = subscribe
+	}
+	mailbox Trash {
+			special_use = \Trash
+			auto = create
+			autoexpunge = 30d
+	}
+	mailbox Drafts {
+			special_use = \Drafts
+			auto = subscribe
+	}
+	mailbox Spam {
+			special_use = \Junk
+			auto = create
+			autoexpunge = 30d
+	}
+	mailbox Archive {
+			special_use = \Archive
+			auto = create
+	}
+}
+
+# /etc/dovecot/conf.d/20-imap.conf
+imap_capability = +SPECIAL-USE
+
+# /etc/dovecot/conf.d/90-sieve.conf
+plugin {
+	sieve = ~/.dovecot.sieve
+	sieve_default = /var/lib/dovecot/sieve/default.sieve
+	sieve_global = /var/lib/dovecot/sieve/
+}
+ +

Then create the default sieve filtering script at +/var/lib/dovecot/sieve/default.sieve

+
require ["fileinto", "mailbox"];
+/*
+* Discard mail that has a spam score greater than or equal to 10
+*/
+if header :contains "X-Spam-Level" "**********" {
+	discard;
+	stop;
+}
+/*
+* Discard messages marked as infected by a virus scanner
+*/
+if header :contains "X-Virus-Scan" "infected" {
+	discard;
+	stop;
+}
+/*
+* If message is marked as spam (and falls below discard threshold) put into spam mailbox
+*/
+if header :contains "X-Spam-Flag" "YES" {
+	fileinto "Spam";
+}
+ +

And compile the script

+ +
sievec /var/lib/dovecot/sieve/default.sieve
+ + +

Finally, configure PAM authentication for dovecot at +/etc/pam.d/dovecot. Append these changes leaving any include +statements intact.

+
auth    required        pam_unix.so
+account required        pam_unix.so
+ +

OpenDKIM

+

DKIM is a mail-verification method that cryptographically signs mail +to allow receivers to verify the authenticity of the sender. Our mail server +will use DKIM to validate signatures on incoming mail and sign outgoing mail. DKIM +requires a public key to be published via DNS, which will be done near the end of +the guide.

+ +

Start by generating the DKIM key

+ +
opendkim-genkey -D /etc/dkimkeys -d example.com -s mail
+chown opendkim: /etc/dkimkeys/*
+chmod 600 /etc/dkimkeys/*
+mv /etc/dkimkeys/mail.private /etc/dkimkeys/mail.pem
+ +

Here we make a directory for the opendkim socket inside the postfix chroot and +make it accessible to the postfix user.

+ +
mkdir /var/spool/postfix/opendkim
+chmod 770 /var/spool/postfix/opendkim
+chown opendkim:opendkim /var/spool/postfix/opendkim
+usermod -aG opendkim postfix
+ +

Edit the configuration file at /etc/opendkim.conf +to be as follows:

+ +
On-BadSignature		reject
+On-Security		reject
+Syslog			yes
+SyslogSuccess		yes
+LogResults		yes
+Canonicalization		simple
+Mode			sv
+OversignHeaders		From
+Domain			example.com
+Selector			mail
+KeyFile			/etc/dkimkeys/mail.pem     
+UserID			opendkim
+UMask			007
+Socket			local:/var/spool/postfix/opendkim/opendkim.sock
+PidFile			/run/opendkim/opendkim.pid
+TemporaryDirectory		/run/opendkim
+InternalHosts		127.0.0.1
+TrustAnchorFile		/usr/share/dns/root.key
+RequireSafeKeys		True
+AlwaysAddARHeader		True
+
+ +

OpenDMARC

+

DMARC is another mail-verification technology that provides verification of the +address seen by end-users and either or both of SPF and DKIM. + +

Like with OpenDKIM, we need to make a directory inside the postfix chroot +for the socket and assign proper permissions.

+
mkdir /var/spool/postfix/opendmarc
+chmod 770 /var/spool/postfix/opendmarc
+chown opendmarc:opendmarc /var/spool/postfix/opendmarc
+usermod -aG opendmarc postfix
+
+ +

Now we write the configuration file at /etc/opendmarc.conf

+ +
PidFile 		/run/opendmarc/opendmarc.pid
+PublicSuffixList	/usr/share/publicsuffix/public_suffix_list.dat
+RejectFailures  	True
+Socket  		local:/var/spool/postfix/opendmarc/opendmarc.sock
+Syslog  		True
+SyslogFacility  	mail
+UMask   		002
+UserID  		opendmarc
+HistoryFile	/var/run/opendmarc/opendmarc.hist
+SPFIgnoreResults	True
+SPFSelfValidate	True
+
+ +

Then create the history file and set permissions.

+ +
touch /var/run/opendmarc/opendmarc.hist
+chown opendmarc:opendmarc /var/run/opendmarc/opendmarc.hist
+chmod 664 /var/run/opendmarc/opendmarc.hist
+
+ +

Now that both OpenDKIM and OpenDMARC are configured we can define them as milters +in postfix. This will tell postfix to route mail through one or both of these milters +depending on whether it is incoming or outgoing.

+ +
postconf -P "smtpd/pass/smtpd_milters=unix:opendkim/opendkim.sock,unix:opendmarc/opendmarc.sock"
+postconf -P "submissions/inet/smtpd_milters=unix:opendkim/opendkim.sock"
+# If you enabled submission on port 587 run this too
+postconf -P "submission/inet/smtpd_milters=unix:opendkim/opendkim.sock"
+
+ +

Postgrey

+

Postgrey implements a spam-filter technique known as greylisting, which +always rejects mail on the first try and for a period of time afterwards known +as the greylist period. The idea behind this being that legitimate senders will +send the mail again later, while spammers, in a rush to send as many messages as +possible before being blacklisted, will not.

+ +

Postgrey ships with an extensive whitelist domains that are known +to cause issues (mainly large providers that constantly send from different +addresses). This whitelist file is located at +/etc/postgrey/whitelist_clients and can be appended to include +any domain you do not wish to be subject to greylisting.

+ +

The configuration needed here is minimal, just open +/etc/default/postgrey and make these changes

+ +
POSTGREY_OPTS="--unix=/var/spool/postfix/private/postgrey --privacy"
+POSTGREY_TEXT="Greylisted - see https://www.greylisting.org"
+ +

And then enable the service

+ +
systemctl enable --now postgrey
+ +

Policyd-SPF

+

SPF is yet another mail-verification technology that uses DNS records to +delegate specific servers as being authorized to send mail for the domain +(and implicitly all other servers as unauthorized). Policyd-SPF will perform +SPF checking of received mail and reject mail that fails SPF verfication.

+ +

First, tell postfix how to access Policyd-SPF

+ +
postconf -e "policyd-spf_time_limit = 3600"
+postconf -M "policyd-spf/unix=policyd-spf unix - n n - 0 spawn user=policyd-spf argv=/usr/bin/policyd-spf"
+ +

And then edit the configuration file at +/etc/postfix-policyd-spf-python/policyd-spf.conf

+ +
debugLevel = 1
+TestOnly = 1
+HELO_reject = Fail
+Mail_From_reject = Fail
+Header_Type = AR
+# These settings increase false-positive risk
+# Comment them if you want to reduce that risk
+PermError_reject = True
+TempError_Defer = True
+ + +

SpamAssassin

+

SpamAssassin is a spam-filter that will scan all received mail and assign +a spam score based on configured rules. SpamAssassin is much heavier and more +resource-intensive than any of the previous spam-filtering/verification programs +we have configured. The postfix spam-filtering philosophy emphasizes the use +of lightweight checks before passing to an external content filter such as +SpamAssassin. Ideally, non-legitimate mail will have already been caught by one +of the previous methods, and SpamAssassin will only have to operate on a much +smaller subset of the mail that is sent to our server.

+ +

We have actually already told postfix to use SpamAssassin as a content filter +so in this section we just need to edit the configuration file +/etc/spamassassin/local.cf.

+ +
# Clearly indicate message is spam to user
+rewrite_header Subject *****SPAM*****
+rewrite_header From *****SPAM*****
+
+# Set required score to be marked as spam, 5.0 is default.
+# Lower to make policy more strict or raise to be more lenient.
+required_score 5.0
+
+# Attach original messages as text/plain instead of message/rfc822 to spam reports
+report_safe 2
+
+Do not implicitly trust mail based on IP address except localhost
+trusted_networks       127.0.0.1/32
+
+ +

And finally make a few changes to the defaults file at +/etc/default/spamassassin

+ +
OPTIONS="--listen /var/run/spamd.sock --max-children 5"
+PIDFILE=/var/run/spamd.pid
+CRON=1
+ +

Wrapping Up

+

At this point we have done all of the necessary configuration of the mail +server programs. We have just a few more minor tasks before your mail server +is operational.

+ +

Configure Firewall

+

We need to open the proper ports in the firewall. This example uses UFW.

+ +
ufw allow 25 comment "smtp"
+ufw allow 465 comment "submission over TLS"
+# Run this next command only if you enabled submission on port 587
+ufw allow 587 comment "mail submission"
+ufw allow 993 comment "IMAP over TLS"
+ufw reload
+ +

Restart services

+

Now let's restart the services to pick up any configuration changes.

+ +
systemctl restart postfix
+systemctl restart dovecot
+systemctl restart opendkim
+systemctl restart opendmarc
+systemctl enable --now spamassassin
+systemctl restart spamassassin
+systemctl restart postgrey
+ +

DNS Entries

+

Finally, we needs to set some required DNS records to enable mail flow and +verification. Begin by logging into your registrar or DNS host and editing +your DNS records.

+ +

A Record

+

If you did not set a wildcard A record earlier, you will need to set one now +for mail. +Alternatively, if you are running the mail server on the same server as your +website, you may want to instead make a CNAME record pointing mail to www.

+ +

MX Record

+

MX records tell servers attempting to send you mail where to send it. Open the +MX records section on your registrar and add a new record. An MX +record consists of a priority and a destination. Set the priority to 10 and the +destination to mail, or whatever your subdomain for this mail +server is. The host value can be left blank or may need to be set to "@" +depending on your registrar.

+ +

DKIM TXT Record

+

Now we will set the three TXT records we need. Open the TXT records tab on +your registrar.

+ +

We'll set the DKIM record first. The command we ran to +generate our DKIM keys also generates a DNS record for us which will be helpful +here. Print that to the screen with:

+ +
cat /etc/dkimkeys/mail.txt
+ +

You should get a lengthy output that looks something like the following. The +bolded portion is the value.

+ +
mail._domainkey	IN	TXT	( "v=DKIM1; h=sha256; k=rsa; "
+	  "p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz50PSYL0Ob+OlF/0B77rwlzLe7zF6JKnxQNtMqcOCZ0Dar2FPhSUSz1FR0YmNuoShjMogdgKeojIzgRUqwK5GZ5Lz456qiXWkfAtLPc6UQ/WPoyEBGbJpRBYPGWdN4VoNcHkk/I4csvXW6MOI55ghPOwDmootPkCzNPR6gmNAXMe0duS4Lb+bIjy9QMOxGYVUaQ/b+7xar+fWw"
+	  "bA3DjQa3jTLCydzzJpjEMfVaKqNhQ4N+ve7O2Mb3LF5k5B977mtok/6POjVG5HY8g6Pba+GzMFItR6nJO5EE2fyfv6cNbRLsZiM+WQmqvDBst5ejaeapy86F5PdJFlX/TUgXjtuwIDAQAB" )  ; ----- DKIM key mail for example.com
+ +

You can cleanup the spacing of the value as your registrar should automatically +handle any needed splitting of the record. The parts you need to paste into your +registrar's web interface should then look like this.

+ +
# Name/Host 
+mail._domainkey
+# TXT Value
+"v=DKIM1; h=sha256; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz50PSYL0Ob+OlF/0B77rwlzLe7zF6JKnxQNtMqcOCZ0Dar2FPhSUSz1FR0YmNuoShjMogdgKeojIzgRUqwK5GZ5Lz456qiXWkfAtLPc6UQ/WPoyEBGbJpRBYPGWdN4VoNcHkk/I4csvXW6MOI55ghPOwDmootPkCzNPR6gmNAXMe0duS4Lb+bIjy9QMOxGYVUaQ/b+7xar+fWwbA3DjQa3jTLCydzzJpjEMfVaKqNhQ4N+ve7O2Mb3LF5k5B977mtok/6POjVG5HY8g6Pba+GzMFItR6nJO5EE2fyfv6cNbRLsZiM+WQmqvDBst5ejaeapy86F5PdJFlX/TUgXjtuwIDAQAB"
+ +

DMARC TXT Record

+

The DMARC record should be as follows:

+ +
# Name/Host 
+_dmarc
+# Value 
+"v=DMARC1; p=reject; rua=mailto:dmarc@example.com; fo=1"
+
+ +

SPF Record

+

Your SPF record will look like this. Remember to replace +mail.example.com with your server name.

+ +
# Name/Host 
+@
+# Value
+"v=spf1 a:mail.example.com -all"
+
+ +

PTR Record

+

Many mail servers rely on PTR records for verification purposes so we need +to make sure our server's IP address resolves to the proper domain name. If +your mail server is residing on a VPS, you will need to add this record on your +VPS provider's interface, consult their documentation for details.

+ +

Creating your own Mail User

+

Your mail server is now up and running. Let's create an email for you to +receive mail.

+ +
useradd --shell /usr/sbin/nologin --create-home --user-group user
+echo "user@example.com	user" >> /etc/postfix/login_maps
+echo "user	user" >> /etc/postfix/local_maps
+postmap /etc/postfix/login_maps
+postmap /etc/postfix/local_maps
+postfix reload
+
+ +

I have a script available for adding and removing users that you can find +here. + +

Connecting From a Mail Client

+

When connecting your account to a mail client you need to use these settings.

+ + +

+


+Consider donating if this article was useful. +[BTC] +

+
+ + + + -- cgit v1.2.3