#!/bin/sh

# BEFORE INSTALLING
#
# Have a Debian or Ubuntu server with a static IPv4 address and DNS records
# (usually A) that point your domain name to it.
#
# IPv6 is optional in this configuration.
#
# NOTE WHILE INSTALLING
#
# On installation of Postfix, select "Internet Site" and put in TLD
# (without `mail.` before it).
#
# AFTER INSTALLING
#
# More DNS records will be given to you to install. One of them will be
# different for every installation and is uniquely generated on your machine.

umask 0022

install_packages="postfix postfix-pcre dovecot-imapd dovecot-pop3d dovecot-sieve opendkim opendkim-tools spamassassin spamc net-tools fail2ban bind9-host"

systemctl -q stop dovecot
systemctl -q stop postfix
apt-get purge ?config-files -y $install_packages
apt-get install -y $install_packages

domain="$(cat /etc/mailname)"
subdom=${MAIL_SUBDOM:-mail}
maildomain="$subdom.$domain"
certdir="/etc/letsencrypt/live/$maildomain"

selfsigned="no" # yes no
allow_suboptimal_ciphers="yes" # yes no
mailbox_format="maildir" # maildir sdbox
allowed_protocols=" imap pop3 " # imap pop3

use_cert_config="no"
country_name="" # IT US UK IN etc etc
state_or_province_name=""
organization_name=""
common_name="$(hostname -f)"

if [ "$use_cert_config" = "yes" ]; then
	echo "[req]
	default_bits = 4096
	distinguished_name = req_distinguished_name
	prompt = no

	[req_distinguished_name]
	countryName             = $country_name
	stateOrProvinceName     = $state_or_province_name
	organizationName        = $organization_name
	commonName              = $common_name" > "$certdir/certconfig.conf"
fi

# Preliminary record checks.
#
# Check the actual mail hostname because this is the hostname used for
# the certificate and mail services.
ipv4=$(host "$maildomain" 2>/dev/null | grep -m1 -Eo '([0-9]+\.){3}[0-9]+')

[ -z "$ipv4" ] && echo "\033[0;31mPlease point $maildomain to your server's IPv4 address.\033[0m" && exit 1

# IPv6 is optional.
# We deliberately do NOT require an AAAA record.

ipv6=$(host "$maildomain" 2>/dev/null | grep "IPv6" | awk '{print $NF}')

# Open required mail ports.
for port in 80 993 465 25 587 110 995; do
	ufw allow "$port" 2>/dev/null
done

if [ "$selfsigned" = "yes" ]; then
	rm -f "$certdir/privkey.pem"
	rm -f "$certdir/csr.pem"
	rm -f "$certdir/fullchain.pem"

	echo "Generating a 4096 rsa key and a self-signed certificate that lasts 100 years"

	mkdir -p "$certdir"

	openssl genrsa -out "$certdir/privkey.pem" 4096

	if [ "$use_cert_config" = "yes" ]; then
		openssl req -new \
			-key "$certdir/privkey.pem" \
			-out "$certdir/csr.pem" \
			-config "$certdir/certconfig.conf"
	else
		openssl req -new \
			-key "$certdir/privkey.pem" \
			-out "$certdir/csr.pem"
	fi

	openssl req -x509 \
		-days 36500 \
		-key "$certdir/privkey.pem" \
		-in "$certdir/csr.pem" \
		-out "$certdir/fullchain.pem"
else

	# Open port 80 for Certbot.
	ufw allow 80 2>/dev/null

	[ ! -d "$certdir" ] &&
		possiblecert="$(certbot certificates 2>/dev/null |
			grep "Domains:\.* \(\*\.$domain\|$maildomain\)\(\s\|$\)" -A 2 |
			awk '/Certificate Path/ {print $3}' |
			head -n1)" &&
		certdir="${possiblecert%/*}"

	[ ! -d "$certdir" ] &&
		certdir="/etc/letsencrypt/live/$maildomain" &&
		case "$(netstat -tulpn 2>/dev/null | grep ":80\s")" in
		*nginx*)
			apt-get install -y python3-certbot-nginx
			certbot -d "$maildomain" certonly --nginx \
				--register-unsafely-without-email --agree-tos
			;;
		*apache*)
			apt-get install -y python3-certbot-apache
			certbot -d "$maildomain" certonly --apache \
				--register-unsafely-without-email --agree-tos
			;;
		*)
			apt-get install -y python3-certbot
			certbot -d "$maildomain" certonly --standalone \
				--register-unsafely-without-email --agree-tos
			;;
		esac

fi

[ ! -f "$certdir/fullchain.pem" ] &&
	echo "Error locating or installing SSL certificate." &&
	exit 1

[ ! -f "$certdir/privkey.pem" ] &&
	echo "Error locating or installing SSL certificate." &&
	exit 1

if [ "$selfsigned" != "yes" ]; then
	[ ! -f "$certdir/cert.pem" ] &&
		echo "Error locating or installing SSL certificate." &&
		exit 1
fi

[ ! -d "$certdir" ] &&
	echo "Error locating or installing SSL certificate." &&
	exit 1

echo "Configuring Postfix's main.cf..."

# IPv4 only.
postconf -e 'inet_protocols = ipv4'

# Adding additional vars to fix an issue with receiving emails
# (relay access denied) and adding it to mydestination.
postconf -e "myhostname = $maildomain"
postconf -e "mail_name = $domain"
postconf -e "mydomain = $domain"
postconf -e 'mydestination = $myhostname, $mydomain, mail, localhost.localdomain, localhost, localhost.$mydomain'

# Change the cert/key files to the default locations of the Let's Encrypt
# cert/key.
postconf -e "smtpd_tls_key_file=$certdir/privkey.pem"
postconf -e "smtpd_tls_cert_file=$certdir/fullchain.pem"

if [ "$selfsigned" != "yes" ]; then
	postconf -e "smtp_tls_CAfile=$certdir/cert.pem"
fi

# Enable, but do not require TLS.
postconf -e 'smtpd_tls_security_level = may'
postconf -e 'smtp_tls_security_level = may'

# TLS required for authentication.
postconf -e 'smtpd_tls_auth_only = yes'

# Exclude insecure and obsolete encryption protocols.
postconf -e 'smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
postconf -e 'smtp_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
postconf -e 'smtpd_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'
postconf -e 'smtp_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1'

# Exclude suboptimal ciphers.
if [ "$allow_suboptimal_ciphers" = "no" ]; then
	postconf -e 'tls_preempt_cipherlist = yes'
	postconf -e 'smtpd_tls_exclude_ciphers = aNULL, LOW, EXP, MEDIUM, ADH, AECDH, MD5, DSS, ECDSA, CAMELLIA128, 3DES, CAMELLIA256, RSA+AES, eNULL'
fi

# Dovecot authentication.
postconf -e 'smtpd_sasl_auth_enable = yes'
postconf -e 'smtpd_sasl_type = dovecot'
postconf -e 'smtpd_sasl_path = private/auth'

# HELO, sender, relay and recipient restrictions.
postconf -e "smtpd_sender_login_maps = pcre:/etc/postfix/login_maps.pcre"
postconf -e 'smtpd_sender_restrictions = reject_sender_login_mismatch, permit_sasl_authenticated, permit_mynetworks, reject_unknown_reverse_client_hostname, reject_unknown_sender_domain'
postconf -e 'smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination, reject_unknown_recipient_domain'
postconf -e 'smtpd_relay_restrictions = permit_sasl_authenticated, reject_unauth_destination'
postconf -e 'smtpd_helo_required = yes'
postconf -e 'smtpd_helo_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, reject_unknown_helo_hostname'

# Maildir.
postconf -e 'home_mailbox = Mail/Inbox/'

# Prevent Received From headers in sent emails.
postconf -e 'header_checks = regexp:/etc/postfix/header_checks'

cat <<EOF > /etc/postfix/header_checks
/^Received:.*/     IGNORE
/^X-Originating-IP:/    IGNORE
EOF

# Create login map.
escaped_domain="$(printf '%s' "$domain" | sed 's/\./\\\./g')"

echo "/^(.*)@$escaped_domain$/   \${1}" > /etc/postfix/login_maps.pcre

# master.cf
echo "Configuring Postfix's master.cf..."

sed -i '/^\s*-o/d;/^\s*submission/d;/^\s*smtp/d' /etc/postfix/master.cf

cat <<EOF >> /etc/postfix/master.cf
smtp unix - - n - - smtp
smtp inet n - y - - smtpd
  -o content_filter=spamassassin
submission inet n       -       y       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_tls_auth_only=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o smtpd_sender_restrictions=reject_sender_login_mismatch
  -o smtpd_sender_login_maps=pcre:/etc/postfix/login_maps.pcre
  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject_unauth_destination
smtps     inet  n       -       y       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
spamassassin unix -     n       n       -       -       pipe
  user=debian-spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f \${sender} \${recipient}
EOF

# -------------------------------------------------------------------------
# DOVECOT
# -------------------------------------------------------------------------

echo "Configuring Dovecot..."

mv /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.backup.conf

echo "Creating Dovecot config..."

cat <<EOF > /etc/dovecot/dovecot.conf
# Dovecot 2.4 configuration

# Required by Dovecot 2.4.
dovecot_config_version = 2.4.1
dovecot_storage_version = 2.4.0

ssl = required
ssl_server_cert_file = $certdir/fullchain.pem
ssl_server_key_file = $certdir/privkey.pem
ssl_server_dh_file = /usr/share/dovecot/dh.pem

ssl_min_protocol = TLSv1.2
ssl_cipher_list = EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA256:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA384:EDH+aRSA+AESGCM:EDH+aRSA+SHA256:EDH+aRSA:EECDH:!aNULL:!eNULL:!MEDIUM:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!RC4:!SEED
ssl_server_prefer_ciphers = client

auth_mechanisms = plain login

# IPv4-only IMAP/POP3.
protocols = imap pop3

# System users.
userdb passwd {
	driver = passwd
}

passdb pam {
	driver = pam
}

# Dovecot 2.4 Maildir configuration.
mail_driver = maildir
mail_path = ~/Mail/Inbox

namespace inbox {
	inbox = yes

	mailbox Drafts {
		special_use = "\\Drafts"
		auto = subscribe
	}

	mailbox Junk {
		special_use = "\\Junk"
		auto = subscribe
		autoexpunge = 30d
	}

	mailbox Sent {
		special_use = "\\Sent"
		auto = subscribe
	}

	mailbox Trash {
		special_use = "\\Trash"
	}

	mailbox Archive {
		special_use = "\\Archive"
	}
}

service auth {
	unix_listener /var/spool/postfix/private/auth {
		mode = 0660
		user = postfix
		group = postfix
	}
}

protocol lda {
	mail_plugins = \$mail_plugins sieve
}

protocol lmtp {
	mail_plugins = \$mail_plugins sieve
}

protocol pop3 {
	pop3_no_flag_updates = yes
}
EOF

# Dovecot 2.4 uses the new TLS setting names above.
# Older Dovecot versions still use the old names, so only use this
# configuration on Dovecot 2.4.x.
dovecot_version="$(dovecot --version 2>/dev/null)"

case "$dovecot_version" in
	2.4*)
		;;
	*)
		echo "ERROR: This script's Dovecot configuration requires Dovecot 2.4.x."
		echo "Detected: $dovecot_version"
		echo "Use a Debian release with Dovecot 2.4.x or adapt the configuration."
		exit 1
		;;
esac

mkdir -p /var/lib/dovecot/sieve/

cat <<EOF > /var/lib/dovecot/sieve/default.sieve
require ["fileinto", "mailbox"];
if header :contains "X-Spam-Flag" "YES"
	{
		fileinto "Junk";
	}
EOF

grep -q '^vmail:' /etc/passwd || useradd vmail

chown -R vmail:vmail /var/lib/dovecot

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

echo 'Preparing user authentication...'

grep -q nullok /etc/pam.d/dovecot ||
cat <<EOF >> /etc/pam.d/dovecot
auth    required        pam_unix.so nullok
account required        pam_unix.so
EOF

# Validate Dovecot before doing anything else with the service.
echo "Validating Dovecot configuration..."

if ! dovecot -n >/dev/null; then
	echo
	echo "ERROR: Dovecot configuration validation failed."
	echo "The service was NOT restarted."
	echo
	dovecot -n
	exit 1
fi

echo "Dovecot configuration is valid."

# -------------------------------------------------------------------------
# OPENDKIM
# -------------------------------------------------------------------------

echo 'Generating OpenDKIM keys...'

mkdir -p "/etc/postfix/dkim/$domain"

opendkim-genkey \
	-D "/etc/postfix/dkim/$domain" \
	-d "$domain" \
	-s "$subdom"

chgrp -R opendkim /etc/postfix/dkim/*
chmod -R g+r /etc/postfix/dkim/*

echo 'Configuring OpenDKIM...'

grep -q "$domain" /etc/postfix/dkim/keytable 2>/dev/null ||
echo "$subdom._domainkey.$domain $domain:$subdom:/etc/postfix/dkim/$domain/$subdom.private" >> /etc/postfix/dkim/keytable

grep -q "$domain" /etc/postfix/dkim/signingtable 2>/dev/null ||
echo "*@$domain $subdom._domainkey.$domain" >> /etc/postfix/dkim/signingtable

grep -q '127.0.0.1' /etc/postfix/dkim/trustedhosts 2>/dev/null ||
echo '127.0.0.1
10.1.0.0/16' >> /etc/postfix/dkim/trustedhosts

grep -q '^KeyTable' /etc/opendkim.conf 2>/dev/null ||
cat <<EOF >> /etc/opendkim.conf
KeyTable file:/etc/postfix/dkim/keytable
SigningTable refile:/etc/postfix/dkim/signingtable
InternalHosts refile:/etc/postfix/dkim/trustedhosts
EOF

sed -i '/^#Canonicalization/s/simple/relaxed\/simple/' /etc/opendkim.conf
sed -i '/^#Canonicalization/s/^#//' /etc/opendkim.conf

sed -i '/Socket/s/^#*/#/' /etc/opendkim.conf

grep -q '^Socket\s*inet:12301@localhost' /etc/opendkim.conf ||
echo 'Socket inet:12301@localhost' >> /etc/opendkim.conf

sed -i '/^SOCKET/d' /etc/default/opendkim
echo 'SOCKET="inet:12301@localhost"' >> /etc/default/opendkim

echo 'Configuring Postfix with OpenDKIM settings...'

postconf -e 'smtpd_sasl_security_options = noanonymous, noplaintext'
postconf -e 'smtpd_sasl_tls_security_options = noanonymous'
postconf -e "myhostname = $maildomain"
postconf -e 'milter_default_action = accept'
postconf -e 'milter_protocol = 6'
postconf -e 'smtpd_milters = inet:localhost:12301'
postconf -e 'non_smtpd_milters = inet:localhost:12301'

# Dovecot 2.4 does not use the old deliver binary.
# Use LMTP for local delivery.
postconf -e 'virtual_transport = lmtp:unix:private/dovecot-lmtp'

# Long-term fix to prevent SMTP smuggling.
postconf -e 'smtpd_forbid_bare_newline = normalize'
postconf -e 'smtpd_forbid_bare_newline_exclusions = $mynetworks'

# Dovecot LMTP socket for Postfix.
cat <<EOF >> /etc/dovecot/dovecot.conf

service lmtp {
	unix_listener /var/spool/postfix/private/dovecot-lmtp {
		mode = 0600
		user = postfix
		group = postfix
	}
}
EOF

# Validate again after adding the LMTP service.
if ! dovecot -n >/dev/null; then
	echo
	echo "ERROR: Dovecot configuration validation failed after LMTP configuration."
	echo
	dovecot -n
	exit 1
fi

# Fix for OpenDKIM PID file.
if [ -x /lib/opendkim/opendkim.service.generate ]; then
	/lib/opendkim/opendkim.service.generate
fi

systemctl daemon-reload

# -------------------------------------------------------------------------
# FAIL2BAN
# -------------------------------------------------------------------------

echo "Configuring Fail2ban..."

[ ! -f /etc/fail2ban/jail.d/emailwiz.local ] &&
cat <<EOF > /etc/fail2ban/jail.d/emailwiz.local
[postfix]
enabled = true

[postfix-sasl]
enabled = true

[sieve]
enabled = true

[dovecot]
enabled = true
EOF

sed -i "s|^backend = auto$|backend = systemd|" /etc/fail2ban/jail.conf

# -------------------------------------------------------------------------
# SPAMASSASSIN
# -------------------------------------------------------------------------

echo "Configuring SpamAssassin..."

if [ -f /etc/default/spamassassin ]; then
	sed -i "s|^CRON=0|CRON=1|" /etc/default/spamassassin
	printf "Restarting spamassassin..."
	service spamassassin restart && printf " ...done\n"
	systemctl enable spamassassin

elif [ -f /etc/default/spamd ]; then
	sed -i "s|^CRON=0|CRON=1|" /etc/default/spamd
	printf "Restarting spamd..."
	service spamd restart && printf " ...done\n"
	systemctl enable spamd

else
	printf "!!! Neither /etc/default/spamassassin or /etc/default/spamd exists, this is unexpected and needs to be investigated\n"
fi

# -------------------------------------------------------------------------
# SERVICES
# -------------------------------------------------------------------------

for x in opendkim dovecot postfix fail2ban; do
	printf "Restarting %s..." "$x"

	if service "$x" restart; then
		printf " ...done\n"
	else
		printf " ...FAILED\n"
		echo "Check: systemctl status $x --no-pager"
		exit 1
	fi

	systemctl enable "$x"
done

# -------------------------------------------------------------------------
# DNS RECORDS
# -------------------------------------------------------------------------

pval="$(tr -d '\n' < "/etc/postfix/dkim/$domain/$subdom.txt" |
	sed "s/k=rsa.* \"p=/k=rsa; p=/;s/\"\s*\"//;s/\"\s*).*//" |
	grep -o 'p=.*')"

dkimentry="$subdom._domainkey.$domain	TXT	v=DKIM1; k=rsa; $pval"

dmarcentry="_dmarc.$domain	TXT	v=DMARC1; p=reject; rua=mailto:postmaster@$domain; fo=1"

# IPv4-only SPF record.
spfentry="$domain	TXT	v=spf1 mx a:$maildomain ip4:$ipv4 -all"

mxentry="$domain	MX	10	$maildomain	300"

useradd -m -G mail postmaster 2>/dev/null || true

# Create cronjob that deletes month-old postmaster mails.
cat <<EOF > /etc/cron.weekly/postmaster-clean
#!/bin/sh

find /home/postmaster/Mail -type f -mtime +30 -name '*.mail*' -delete >/dev/null 2>&1

exit 0
EOF

chmod 755 /etc/cron.weekly/postmaster-clean

grep -q '^deploy-hook = echo "$RENEWED_DOMAINS" | grep -q' /etc/letsencrypt/cli.ini ||
echo "
deploy-hook = echo \"\$RENEWED_DOMAINS\" | grep -q '$maildomain' && service postfix reload && service dovecot reload" >> /etc/letsencrypt/cli.ini

cat <<EOF > "$HOME/dns_emailwizard"
NOTE: Elements in the entries might appear in a different order in your registrar's DNS settings.

$dkimentry
$dmarcentry
$spfentry
$mxentry
EOF

printf "\033[31m
 _   _
| \ | | _____      ___
|  \| |/ _ \ \ /\ / (_)
| |\  | (_) \ V  V / _
|_| \_|\___/ \_/\_/ (_)\033[0m

Add these records to your DNS records on either your registrar's site
or your DNS server:

\033[32m
$dkimentry

$dmarcentry

$spfentry

$mxentry
\033[0m

NOTE: You may need to omit the \`.$domain\` portion at the beginning if
inputting them in a registrar's web interface.

These are also saved to:
~/dns_emailwizard

Once you do that, you're done! Check the README for how to add users/accounts
and how to log in.
"
