#!/bin/bash
#
# /etc/local-COMMON/postfix/postfix.sh
# Copyright 2002-2004 Jonas Smedegaard <dr@jones.dk>
#
# $Id: postfix.sh,v 1.30 2005-04-15 16:16:17 jonas Exp $
#
# Auto-tweak plain installed postfix Debian package
#
# TODO:
#  * Implement stuff from here: http://www.wsrcc.com/spam/
#  * Implement stuff from here: http://www.muine.org/~hoang/postfix.html
#  * Implement stuff from here: http://jimsun.linxnet.com/misc/postfix-anti-UCE.txt
#  * Figure out a way to use chroot jail for TLS stuff.
#  * Resolve 1.x/2.x differences in RBL map expansion within getlinesfromfile()

set -e

paramdir='/etc/local-COMMON/postfix'
confdir='/etc/postfix'
postconf=/usr/sbin/postconf
sp='[[:space:]]'
pf2=
if $postconf -d mail_version | grep -q '= 2'; then
	pf2=1
fi
pf22=
if $postconf -d mail_version | grep -q '= 2\.2'; then
	pf22=1
fi
pftls=
if [ -x /usr/lib/postfix/tlsmgr ]; then
	pftls=1
else
	echo "WARNING: Not enabling encryption: TLS-patched postfix required."
	echo "    (on Debian: install the package postfix-tls)"
fi
# FIXME: We really want to check for at least 2.1.1 but that's tricky...
sasl2=
if saslauthd -v 2>&1 | grep -q '^saslauthd 2.1'; then
	sasl2=1
else
	echo "WARNING: Not enabling encryption: sasl tools 2.1.1 or greater is required."
	echo "    (on Debian: install the package sasl2-bin)"
fi
sasldir="$confdir/sasl"
if [ -n "$pf22" ]; then
		sasldir="$confdir/sasl2"
fi

#function getlinesfromfile() {
#	param="$1"
#	echo -n "$param = "
#	cat $paramdir/$param | grep -v '^#' | sed 's/#.*//' | tr '\n' ',' | sed -e 's/^[, 	]*//' -e 's/[, 	]\+/,/g' -e 's/,$//'
#}

function getlinesfromfile() {
	param="$1"
	shift
	replacements=
	for subparam in $@; do
		case "$subparam" in
		    *=*=*)
			oldparam="`echo $subparam | awk -F= '{print $1}'`"
			newparam="`echo $subparam | awk -F= '{print $2}'`"
			newparamfile="`echo $subparam | awk -F= '{print $3}'`"
			shift
			;;
		    *)
			oldparam=$subparam
			newparam=$subparam
			newparamfile=$subparam
			shift
			;;
		esac
		newparamvalues="`getlinesfromfile $newparamfile | sed -e 's/.*=[ ]*//' -e 's/,/ /g'`"
		newstring=
		for newparamvalue in $newparamvalues; do
			newstring="${newstring}$newparam $newparamvalue,"
		done
		replacements="$replacements;s/$oldparam/$newstring/"
	done
	echo -n "$param = "
	cat $paramdir/$param | grep -v '^#' | sed 's/#.*//' | tr '\n' ',' | sed -e 's/^[, 	]*//;s/[, 	]\+/,/g' -e "s/,\$//$replacements"
}

# Inspired by D. J. Bernstein: http://cr.yp.to/smtp/greeting.html
$postconf -e 'smtpd_banner = $myhostname NO UCE ESMTP $mail_name (Debian/GNU)'

# Some badly configured setup use hostname instead of FQDN
# Disable completely: Effective, but hurts executive type guys using windows servers... :-(
#if $postconf myhostname | grep -q '\.'; then
#	$postconf -e 'smtpd_helo_required = yes'
#fi
$postconf -e 'smtpd_helo_required = no'
$postconf -e "`getlinesfromfile permit_mx_backup_networks`"
if [ "$pf2" ]; then
	$postconf -e "maps_rbl_domains ="
	$postconf -e "`getlinesfromfile smtpd_client_restrictions reject_rhsbl_client`"
	$postconf -e "`getlinesfromfile smtpd_helo_restrictions`"
	$postconf -e "`getlinesfromfile smtpd_sender_restrictions reject_rhsbl_sender`"
	$postconf -e "`getlinesfromfile smtpd_recipient_restrictions reject_maps_rbl=reject_rbl_client=maps_rbl_domains`"
	$postconf -e "`getlinesfromfile smtpd_data_restrictions`"
else
	$postconf -e "`getlinesfromfile maps_rbl_domains`"
	$postconf -e "`getlinesfromfile smtpd_helo_restrictions`"
	$postconf -e "`getlinesfromfile smtpd_recipient_restrictions`"
fi

# TLS breaks postfix if no SASL modules available (and doesn't make sense either)
# (change the test if using some other modules and avoid the plain ones)
if [ -n "$pftls" -a -n "$sasl2" -a -f /etc/ssl/certs/postfix.pem ]; then
	mkdir -p "$sasldir"
	echo 'mech_list: plain login' > "$sasldir/smtpd.conf"
	echo 'minimum_layer: 0' >> "$sasldir/smtpd.conf"
	echo 'pwcheck_method: saslauthd' >> "$sasldir/smtpd.conf"
	echo 'auto_transition: false' >> "$sasldir/smtpd.conf"
	groups postfix | grep -q sasl || adduser postfix sasl
	# Release TLS-related daemons from chroot jail (bringing SASL into the jail is just too messy)
	cp -a $confdir/master.cf $confdir/master.cf.old
	cat $confdir/master.cf.old | sed \
		-e "s/^\(smtp$sp\+inet\($sp\+[n-]\)\{2\}$sp\+\)[n-]\(\($sp\+-\)\{2\}$sp\+smtpd\).*/\1n\3 -o smtpd_sasl_auth_enable=yes/" \
		-e "s/^#\?\(\(smtps\|587\)$sp\+inet\($sp\+[n-]\)\{2\}$sp\+\)[n-]/\1n/" \
		-e "s/^#\(tlsmgr$sp\)/\1/" \
		> $confdir/master.cf
	cat $confdir/master.cf | egrep -q "^tlsmgr$sp" || \
		if [ -n "$pf22" ]; then
			echo 'tlsmgr	  unix	-	-	-	300	1	tlsmgr' >> $confdir/master.cf
		else
			echo 'tlsmgr	  fifo	-	-	-	300	1	tlsmgr' >> $confdir/master.cf
		fi
	$postconf -e 'smtpd_tls_cert_file = /etc/ssl/certs/postfix.pem'
	if [ -f /etc/ssl/private/postfix.pem ]; then
		$postconf -e 'smtpd_tls_key_file = /etc/ssl/private/postfix.pem'
	fi
	$postconf -e 'smtpd_tls_loglevel = 1'
	$postconf -e 'smtpd_use_tls = yes'
	$postconf -e 'smtpd_tls_key_file = /etc/ssl/private/postfix.pem'
	if [ -n "$pf22" ]; then
		$postconf -e 'smtpd_tls_session_cache_database = btree:/var/spool/postfix/smtpd_scache'
	else
		$postconf -e 'smtpd_tls_session_cache_database = sdbm:/var/spool/postfix/smtpd_scache'
	fi
	$postconf -e 'smtpd_tls_session_cache_timeout = 3600s'
	$postconf -e 'tls_random_exchange_name = /var/spool/postfix/prng_exch'
	$postconf -e 'smtpd_tls_auth_only = yes'
	$postconf -e 'smtpd_sasl_auth_enable = no' # SASL is enabled explicitly with TLS transport
	$postconf -e 'smtpd_sasl_security_options = noanonymous'
	$postconf -e 'smtpd_sasl_local_domain = '
	$postconf -e 'smtpd_tls_received_header = yes'
	$postconf -e 'broken_sasl_auth_clients = yes'
	$postconf -e 'tls_random_source = dev:/dev/urandom'
	$postconf -e 'tls_daemon_random_source = dev:/dev/urandom'
	# Check if using a proper key exists (not just a self-signed one)
	# (it is assumed that a CA certificate is made public if used!)
	if [ -f /etc/ssl/certs/cacert.pem ]; then
		$postconf -e 'smtpd_tls_CAfile = /etc/ssl/certs/cacert.pem'
		# Client side TLS only makes sense if a publicly available certificate is available
		# (and DON'T publish a self-signed certificate!)
		$postconf -e 'smtp_tls_CAfile = /etc/ssl/certs/cacert.pem'
		$postconf -e 'smtp_tls_cert_file = /etc/ssl/certs/postfix.pem'
		if [ -f /etc/ssl/private/postfix.pem ]; then
			$postconf -e 'smtp_tls_key_file = /etc/ssl/private/postfix.pem'
		fi
		$postconf -e 'smtp_tls_loglevel = 1'
		$postconf -e 'smtp_use_tls = yes'
		$postconf -e 'smtp_tls_CApath = /etc/ssl/certs'
		$postconf -e 'smtp_tls_note_starttls_offer = no' # Enable to collect info for smtp_tls_per_site option
		if [ -n "$pf22" ]; then
			$postconf -e 'smtp_tls_session_cache_database = btree:/var/spool/postfix/smtp_scache'
		else
			$postconf -e 'smtp_tls_session_cache_database = sdbm:/var/spool/postfix/smtp_scache'
		fi
		# Accepting client certificates breaks SMTP AUTH on OutLook Express on Mac (Classic)
		$postconf -e 'smtpd_tls_ask_ccert = no'
	else
		echo "WARNING: CA certificate not found - consider using proper signed certificates!"
	fi
else
	echo 'WARNING: TLS not activated - check the script for requirements...'
fi

if [ -x /usr/sbin/amavisd -o -x /usr/sbin/amavisd-new ]; then
	localtransport="smtp"
	if [ "$pf2" ]; then # lmtp is slightly buggy in earlier versions
		localtransport="lmtp" # Provides multi-session mail transaction capability and per-recipient status responses.
		$postconf -e 'max_use = 10' # Avoid too much reuse
	fi
	cat $confdir/master.cf | egrep -q "^smtp-amavis$sp" || \
		echo "smtp-amavis unix -	-	n	-	2	$localtransport -o smtp_data_done_timeout=1200s -o smtp_never_send_ehlo=yes -o disable_dns_lookups=yes" >> $confdir/master.cf
	cat $confdir/master.cf | egrep -q "^127.0.0.1:10025$sp" || \
		echo '127.0.0.1:10025 inet n	-	n	-	-	smtpd -o content_filter= -o local_recipient_maps= -o relay_recipient_maps= -o smtpd_restriction_classes= -o smtpd_helo_restrictions= -o smtpd_client_restrictions= -o smtpd_sender_restrictions= -o smtpd_recipient_restrictions=permit_mynetworks,reject -o mynetworks=127.0.0.0/8 -o strict_rfc821_envelopes=yes' >> $confdir/master.cf
	$postconf -e 'content_filter = smtp-amavis:[127.0.0.1]:10024'
	$postconf -e 'allow_mail_to_file = yes'
	mkdir -p /var/lib/amavis/mboxes
	chown nobody.nogroup /var/lib/amavis/mboxes
	for mail in virus-quarantine virusalert spam-quarantine spamalert; do
		touch /var/lib/amavis/mboxes/$mail
		chown nobody.nogroup /var/lib/amavis/mboxes/$mail
		if ! grep -q "^$mail:" /etc/aliases; then
			echo "$mail: /var/lib/amavis/mboxes/$mail" >> /etc/aliases
			newaliases
		fi
	done
	if ! grep -q "^spam.police:" /etc/aliases; then
		echo "spam.police: root" >> /etc/aliases
		newaliases
	fi
fi

/etc/init.d/postfix reload

# Based on this: http://jimsun.linxnet.com/misc/postfix-anti-UCE.txt
# Support for trusted MX backup networks added
# PCRE stuff avoided, as PCRE is only optional on newest Debian packages
# RBLs replaced with those recommended by http://www.antispews.org/
# AMaViS tweaks as documented in amavisd-new package
# AUTH-SMTP based on these:
#   http://lists.q-linux.com/pipermail/plug/2003-July/029503.html
#   http://www.porcupine.org/postfix-mirror/newdoc/SASL_README.html

# Here's a convenient overview of different blackholes:
#   http://rbls.org/

# smtpd_tls_CAfile