Thursday, February 9, 2012

Postfix + Dovecot + ClamAV + Amavsid-new + SpamAssassin

Postfix + Dovecot + ClamAV + Amavsid-new + SpamAssassin
Installation Guide using Source Compilation on Ubuntu Server



Definitions

Postfix is an (Mail Transfer Agent) which uses the SMTP protocol
Dovecot is an IMAP/POP3 server (Mail Delivery Agent) which allows reading our emails using a (Mail User Agent) like Outlook or Thunderbird
ClamAV is antivirus software which helps to scan emails for virus checking
Amavisd-new is a helper software which connects Postfix with ClamAV and SpamAssassin.
SpamAssassin is an anti spam software which checks the emails for Spam signatures and online databases for black listed spam senders

Postfix Version 2.8.7 (Latest Stable Version)

Installation Steps

Download the source code using
wget http://postfix.psshee.com/pub/official/postfix-2.8.7.tar.gz
Unzip the package
gunzip postfix-2.8.7.tar.gz
tar -xvf postfix-2.8.7.tar
Install the db-devel package
apt-get update
apt-get upgrade
apt-get install db*-devel
apt-get install libdb-dev
apt-get install zlibc
Make and Install the postfix from source directory
cd /to/folder/where/you/downloaded/postfix
cd /home/ammar/download/postfix-2.8.7
make
sudo groupadd -g 12345 postfix
sudo useradd -u 12345 -g 12345 -M postfix
sudo groupadd -g 54321 postdrop
sudo su
cd /home/ammar/download/postfix-2.8.7
make install ( run as root only )
Select all default options by pressing enter key


Now Postfix is installed but you need to configure it.

Configuration Steps

Let’s configure the /etc/postfix/main.cf file
vi /etc/postfix/main.cf
Add/Uncomment the following lines
myhostname = yourmailserver.com
myorigin = $myhostname
inet_interfaces = all
mydestination = $myhostname, localhost
mynetworks = 203.231.126.128/25, 127.0.0.0/8
relay_domains = $mydestination
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
home_mailbox = Maildir/
mailbox_command =


vi /etc/postfix/master.cf
Add the following lines
48005 inet n - n - - smtpd


vi /etc/aliases and add the following lines
root: yourname@yourmailserver.com
postmaster: root
postfix: root
bin: root


Save the file and run the following command
newaliases


Now type the following command
mkdir -p /var/spool/postfix/dev
apt-get install sysklogd
syslogd -a /var/spool/postfix/dev/log
vi /etc/syslog.conf
Add the following lines / uncomment the following lines
mail.* /var/log/mail.log
mail.err /var/log/mail.err
mail.debug /var/log/mail.debug
Check you postfix by sending emails to local / remote email addresses.

Setting iptables firewall

Iptables is installed by default of on Ubuntu Server. In order to make postfix and dovecot work correctly we have to allow the following ports on our server.

Open a file named set_iptables.sh and type in the following
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 25 -j REDIRECT --to-port 48005
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
iptables -I INPUT -p tcp --dport 48005 -j ACCEPT
iptables -I INPUT -p tcp --dport 143 -j ACCEPT
iptables -I INPUT -p tcp --dport 110 -j ACCEPT
iptables -I INPUT -p tcp --dport 993 -j ACCEPT
iptables -I INPUT -p tcp --dport 995 -j ACCEPT
iptables -I INPUT -p tcp --dport 25 -j DROP

Now use this to set the iptables by the following command
sh set_iptables.sh
iptables-save > /root/iptables.rules

Open a file named setup_mailserver and add the following lines
iptables-restore < /root/set_iptables
Now put this script to be started on bootup time by typing the following commands
mv setup_mailserver /etc/init.d/
chmod +x /etc/init.d/setup_mailserver
update-rc.d setup_mailserver defaults
Reboot your machine and check if the iptables are correctly forwarding your port 25 to port 48005
To check if iptables is working correctly type the command below
iptables -t nat -L -n –v

Dovecot Version 2.0.17 (Latest Stable Version)

Installation Steps

Download the source code for dovecot by typing the following command
wget http://www.dovecot.org/releases/2.0/dovecot-2.0.17.tar.gz
Unzip the package
gunzip dovecot-2.0.17.tar.gz
tar –xvf dovecot-2.0.17.tar
Install the pre-requisites
apt-get install libpam0g
apt-get install libpam0g-dev
apt-get install libssl-dev
Now go the source directory e.g, /home/ammar/download/dovecot-2.0.17/
cd /home/ammar/download/dovecot-2.0.17/
sudo su
./configure --with-pam --with-ssl =openssl
make
make install

Configuration Steps

The above installation will install dovecot in the following directory
/usr/local/etc/dovecot
The configuration files however, do not exist at the moment and so we will copy the sample configuration files (dovecot.conf file and conf.d/ directory) from
/usr/local/share/doc/dovecot/example-config
to
/usr/local/etc/dovecot/
You can use the following commands
cp -r /usr/local/share/doc/dovecot/example-config/conf.d/ /usr/local/etc/dovecot/
cp -r /usr/local/share/doc/dovecot/example-config/dovecot.conf /usr/local/etc/dovecot/

Now you have your configuration files in correct location but you still need to configure them


vi /usr/local/etc/dovecot/dovecot.conf
Add/Uncomment the following lines
protocols = imap pop3
disable_plaintext_auth = no
login_greeting = Dovecot ready.


vi /usr/local/etc/dovecot/conf.d/10-auth.conf
auth_mechanisms = plain login


vi /usr/local/etc/dovecot/conf.d/auth-system.conf.ext
Add/Uncomment the following lines
passdb
{
driver = pam
}
userdb
{
driver = passwd
}
Now create a file by typing
vi /etc/pam.d/dovecot
Add the following lines to this file
auth required pam_unix.so
account required pam_unix.so
Now make two users and groups for dovecot access
dovenull: Used by untrusted imap-login and pop3-login processes (default_login_user setting).
dovecot: Used by slightly more trusted Dovecot processes (default_internal_user setting).
Create the above by typing the commands below
groupadd dovenull
goupadd dovecot
useradd -g dovecot dovecot
useradd -g dovenull dovenull


vi /etc/pam.d/imap
passdb {
driver = pam
args = %s
}


vi /etc/pam.d/mail:
passdb {
driver = pam
args = mail
}


vi /usr/local/etc/dovecot/conf.d/10-ssl.conf
Add the following lines
ssl = yes
ssl_cert =
ssl_key =
vi /usr/local/etc/dovecot/conf.d/10-mail.conf
Add the line
mail_location = maildir:~/Maildir
Add the following lines to the file
service imap-login {
inet_listener imap { port = 143 }
inet_listener imaps {
port = 993
ssl = yes
}
}
service pop3-login {
inet_listener pop3 { port = 110 }
inet_listener pop3s {
port = 995
ssl = yes
}
}
service lmtp {
unix_listener lmtp {
}
service imap { }
service pop3 { }
service auth {
unix_listener auth-userdb { }
unix_listener /var/spool/postfix/private/auth {
mode = 0666
}
user = $default_internal_user
}
service auth-worker {
user = root
}
service dict {
unix_listener dict {
}
}

Configuring SSL for Postfix using Dovecot

Add the following lines to /etc/postfix/main.cf
smtpd_sasl_type = dovecot
smtpd_sasl_security_options = noanonymous, noplaintext
smtpd_sasl_tls_security_options = noanonymous
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain =
smtpd_tls_cert_file = /etc/ssl/certs/yourmailserver.server.crt
smtpd_tls_key_file = /etc/ssl/private/yourmailserver.server.key
smtpd_tls_auth_only = yes
smtpd_tls_loglevel = 3
broken_sasl_auth_clients = yes
smtp_tls_note_starttls_offer = yes
smtpd_use_tls = yes
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, reject_unauth_pipelining

Certificate Generation

In order to create a certificate on Ubuntu Server, you will need to type the following
openssl genrsa -des3 -out server.key 1024
Generating RSA private key, 1024 bit long modulus
.....................++++++
.................++++++
unable to write 'random state'
e is 65537 (0x10001)
Enter pass phrase for server.key:
You can now enter your passphrase. For best security, it should at least contain eight characters. The minimum length when specifying -des3 is four characters. It should include numbers and/or punctuation and not be a word in a dictionary. Also remember that your passphrase is case-sensitive. Re-type the passphrase to verify. Once you have re-typed it correctly, the server key is generated and stored in the server.key file.
Now create the insecure key, the one without a passphrase, and shuffle the key names:
openssl rsa -in server.key -out server.key.insecure
mv server.key server.key.secure
mv server.key.insecure server.key
The insecure key is now named server.key, and you can use this file to generate the CSR without passphrase.
To create the CSR, run the following command at a terminal prompt:
openssl req -new -key server.key -out server.csr
It will prompt you enter the passphrase. If you enter the correct passphrase, it will prompt you to enter Company Name, Site Name, Email Id, etc. Once you enter all these details, your CSR will be created and it will be stored in the server.csr file.
You can now submit this CSR file to a CA for processing. The CA will use this CSR file and issue the certificate. On the other hand, you can create self-signed certificate using this CSR.
1. Creating a Self-Signed Certificate
To create the self-signed certificate, run the following command at a terminal prompt:
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
The above command will prompt you to enter the passphrase. Once you enter the correct passphrase, your certificate will be created and it will be stored in the server.crt file.
If your secure server is to be used in a production environment, you probably need a CA-signed certificate. It is not recommended to use self-signed certificate.
2. Installing the Certificate
You can install the key file server.key and certificate file server.crt, or the certificate file issued by your CA, by running following commands at a terminal prompt:
sudo cp server.crt /etc/ssl/certs
sudo cp server.key /etc/ssl/private
Now simply configure any applications, with the ability to use public-key cryptography, to use the certificate and key files. For example, Apache can provide HTTPS, Dovecot can provide IMAPS and POP3S, etc.
Notice that the above statement considers that if we name the .key and .crt file as server.key and server.crt we copy them to the location mentioned in main.cf and dovecot.conf above. But in order for our example to work we will rename these files using the following command.
mv /etc/ssl/private/server.key /etc/ssl/private/yourmailserver.server.key
mv /etc/ssl/certs/server.crt /etc/ssl/certs/yourmailserver.server.crt
Go to source directory of postfix and clean it by typing
make tidy
make makefiles CCARGS='-DUSE_TLS -DUSE_SASL_AUTH -DDEF_SERVER_SASL_TYPE=\"dovecot\"' AUXLIBS='-lssl -lcrypto'
make
make upgrade
postfix reload

ClamAV Version 0.97.3

Installation

Download the source code from http://www.clamav.net/lang/en/download/sources/ and untar the zipped source file to some directory (e.g clamav-0.97.3)
apt-get install g++
groupadd clamav
mkdir /var/virusmails
chmod 770 /var/virusmails
useradd -g clamav -s /bin/false -c "Clam AntiVirus" clamav
cd clamav-0.97.3
./configure --sysconfdir=/etc
make
make install
ldconfig
clamd
clamdscan -l scan.txt
freshclam
vi /etc/freshclam.conf
Uncomment the line with Sample and run freshclam again
freshclam
touch /var/log/freshclam.log
chmod 600 /var/log/freshclam.log
chown clamav /var/log/freshclam.log

Spam Assassin Version 3.3.2

Installation

wget http://ftp.daum.net/apache//spamassassin/source/Mail-SpamAssassin-3.3.2.tar.gz
gunzip Mail-SpamAssassin-3.3.2.tar.gz
tar –xvf Mail-SpamAssassin-3.3.2.tar
perl -MCPAN -e shell
cpan> install Digest::SHA1
cpan> install Mail::SPF
cpan> install IP::Country
cpan> install Net::Ident
cpan> install IO::Socket::INET6
cpan> force install IO::Socket::SSL
cpan> install DBI
cpan> install Encode::Detect
cpan> install Net::Server
cpan> install Unix::Syslog
cd Mail-SpamAssassin-*
press Enter for default options
perl Makefile.PL
make
make install

Amavisd Version 2.7.0

Installation

gunzip amavisd-new.tar.gz
tar -xvf amavisd-new.tar
groupadd amavis
useradd -m /var/amavis –g amavis amavis
mkdir /var/amavis/tmp /var/amavis/var /var/amavis/db /var/amavis/home
chown -R amavis:amavis /var/amavis
chmod -R 750 /var/amavis
Go to source directory of amavisd
cp amavisd /usr/local/sbin/
chown root /usr/local/sbin/amavisd
chmod 755 /usr/local/sbin/amavisd
cp amavisd.conf /etc/
chown root:amavis /etc/amavisd.conf
chmod 640 /etc/amavisd.conf
perl -MCPAN -e shell
cpan> install IO::Wrap
cpan> install IO::Stringy
cpan> install Mail::DKIM::Verifier
cpan> install Crypt::OpenSSL::RSA
cpan> install Convert::TNEF
cpan> install Convert::UUlib
cpan> install Archive::Zip
cpan> force install Convert::BinHex
perl -MCPAN -e 'install "BerkeleyDB"'

Configuration of Amavis, SpamAssassin and ClamAV

First of all change permissions for the clamav folder so that it becomes accessible to the group and root.
chmod 770 /var/lib/clamav/
Make sure that your configuration file (/etc/clamd.conf) looks like this
# Example
LogFile /var/log/freshclam.log
LogFileMaxSize 5M
DatabaseDirectory /var/lib/clamav
LocalSocket /var/amavis/clamd.socket
User clamav
vi /etc/freshclam.conf
Uncomment the following lines
DatabaseDirectory /var/lib/clamav
DatabaseMirror database.clamav.net
UpdateLogFile /var/log/freshclam.log
Now change your /etc/passwd file and edit the following line to match the group id of group amavis. For example, if the group id of amavis is 54325, then the entry for /etc/password should look like below.
clamav:x:12349:54325:Clam AntiVirus:/home/clamav:/bin/false
amavis:x:12350:54325:Amavisd-new Daemon:/var/amavis:/bin/false
Now, configure amavisd to locate clamd.socket correctly as well as link amavisd to postfix.
Edit the file /etc/amavisd.conf
vi /etc/amavisd.conf
Edit/Change the file to make it exactly as below
$max_servers = 2;
$daemon_user = 'amavis';
$daemon_group = 'amavis';
$mydomain = 'yourmailserver.com';
$MYHOME = '/var/amavis';
$TEMPBASE = "$MYHOME/tmp
$ENV{TMPDIR} = $TEMPBASE;
$QUARANTINEDIR = '/var/virusmails';
$db_home = "$MYHOME/db";
$helpers_home = "$MYHOME/var";
$lock_file = "$MYHOME/var/amavisd.lock";
$pid_file = "$MYHOME/var/amavisd.pid";
$virus_admin = "root\@$mydomain"; .
$mailfrom_notify_admin = "virusalert\@$mydomain";
$mailfrom_notify_recip = "virusalert\@$mydomain";
$mailfrom_notify_spamadmin = "spam.police\@$mydomain";
$myhostname = 'yourmailserver.com';
$inet_socket_port = 10024;
$notify_method = 'smtp:[127.0.0.1]:10025';
$forward_method = 'smtp:[127.0.0.1]:10025';
['ClamAV-clamd',
\&ask_daemon, ["CONTSCAN {}\n", "$MYHOME/clamd.socket"],
qr/\bOK$/m, qr/\bFOUND$/m,
qr/^.*?: (?!Infected Archive)(.*) FOUND$/m ],
Now edit the file /etc/postfix/master.cf
vi /etc/postfix/master.cf
Add the following lines in the end of master.cf file
smtp-amavis unix - - y - 2 smtp
-o smtp_data_done_timeout=1200
-o disable_dns_lookups=yes
127.0.0.1:10025 inet n - y - - smtpd
-o content_filter=
-o local_recipient_maps=
-o relay_recipient_maps=
-o smtpd_restriction_classes=
-o smtpd_helo_restrictions=
-o smtpd_sender_restrictions=
-o smtpd_recipient_restrictions=permit_mynetworks,reject
-o mynetworks=127.0.0.0/8
-o strict_rfc821_envelopes=yes
-o smtpd_error_sleep_time=0
-o smtpd_soft_error_limit=1001
-o smtpd_hard_error_limit=1000
Now edit the file /etc/postfix/main.cf
vi /etc/postfix/main.cf
Add the following lines in main.cf file
content_filter =
smtp-amavis:[127.0.0.1]:10024

Testing the System

Before we go any further, let's test the system. Start all the daemons in correct order as following
1. sa-update ( It updates the databases for viruses )
2. freshclam ( It updates the databases for viruses )
3. postfix start
4. dovecot
5. clamd
6. amavisd ( SpamAssassin is built inside amavisd so no need to start SpamAssassin separately )
The simplest way to test our server is to send an e-mail message containing the following string to yourself@yourdomain.com, which is not a real virus but a test string called the Eicar Test Signature:
X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*
If everything is working, amavisd sent an e-mail to the account you specified in amavisd.conf's $virus_admin parameter, and the message should be quarantined in the directory specified in amavisd.conf's $QUARANTINEDIR parameter.
In order to check spam you can send in another email and follow the procedure above with the following string in the subject or body of your email
XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X
In our test system, we can check our virus and spam emails in the folder /var/virusmails. Our root user can check his notification emails for spam/virus mails in the /home/username/Maildir/new folders

References