Amavis

CentOS 6 Email Server: Postfix, Amavisd-new, SpamAssasin, ClamAV, DoveCot, RoundCube, spam, amavisd, virus

How to setup a CentOS 6 Email Server with Postfix, Amavisd-new, SpamAssasin, ClamAV, DoveCot, and RoundCube.

Assuming a minimal CentOS 6.3 Installation with repositories.

$ rpm -Uvh http://apt.sw.be/redhat/el6/en/x86_64/rpmforge/RPMS/rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm

Setup a CentOS 6 Postfix email server

Add the following values, A - main DNS record to point the subdomain to your external IP, subdomain, domain, and destination :

Type: A Subdomain: beach (this is an example, make one up for yourself) Domain: worldcm.com (pick a free domain here, you could setup your own domain, or there are 90,000 available at freedns for free!) Destination: 73.98.210.8 (your external IP address, if you have a dynamic IP you can set your router to update freedns)

Click Add:

Add the following values, MX - mail exchange, subdomain, domain, and destination :

Type: MX Subdomain: beach (this is an example, make one up for yourself) Domain: worldcm.com.com (pick a free domain here, you could setup your own domain, or there are 90,000 others available on the site, free!)

Destination: 10:mail.worldcm.com.com   (10 is the priority, if you had other mail servers they would go here, mail.worldcm.com.com

is your mailserver's name

Click Save!.

Router

Port 25 is for SMTP protocol, for Postfix to receive and send emails.

Port 110 is for POP3 protocol, optional if aren't going to use POP3. If you don't know you can add it or remove it later.

Port 143 is for IMAP protocol, recommended if you have any email clients externally (on the internet).

Add port forwarding for ports 25 and 143, optionally 110 to the IP address of your internal server for TCP only in your router.

If you have a dynamic IP address, setup DynamicDNS to update freedns.afraid.org.

Setup Postfix

A CentOS 6 server comes with Postfix installed.

On the server, save a copy of the postfix configuration file:

cp /etc/postfix/main.cf /etc/postfix/main.cf.original

Edit the postfix main.cf configuration file:

vi /etc/postfix/main.cf

Find, uncomment, and set the following values:

#external email hostname myhostname = mail.worldcm.com  #external email domain mydomain = worldcm.com  #address our emails will be sent from myorigin = mail.worldcm.com  #accept connections on all interfaces inet_interfaces = all  #set mailboxes for uses (in home directory) home_mailbox = Maildir/

restart postfix to pickup changes (must restart for interface changes, for other changes you can just use reload):

service postfix restart

Test Postfix

Send an email to Postfix from the command line

Type the lines below, some lines will populate from the telnet connection.

Enter a single period at the end of your message and press enter to send the message:

# telnet mail.worldcm.com 25 220 mail.worldcm.com ESMTP Postfix

HELO im.notreal.com 250 mail.worldcm.com MAIL FROM:<im@notreal.com> 250 2.1.0 Ok RCPT TO:<root@mail.worldcm>

250 2.1.5 Ok DATA 354 End data with <CR><LF>.<CR><LF> Subject: This is my first email to beach This is the body of the email  From, Andrew . 250 2.0.0 Ok: queued as 812E22E0F QUIT 221 2.0.0 Bye Connection to host lost. #

If you get command not found, install telnet:

yum -y install telnet

If anything doesn't work above, stop and troubleshoot.

Look at maillog to see the incoming email:

less /var/log/maillog

To roughly see your email, cat the file located in your new Maildir, the name of the file will be different:

cd /root/Maildir/new cat 1345833552.Vfd00I5c1cM674918.servername

Send an email externally from the command line

Now that we've established that we can receive an email, lets send an email externally through Postfix:

# mail -s "hello" "someemailyouget@gmail.com" some body . EOT

If you get command not found install mailx:

yum -y install mailx

Check your external email account for the email. Check your spam folder. If it doesn't show up, stop and troubleshoot.

Reply to the email from your external account. Make sure the reply address is correct and that the email shows up in /root/Maildir/new

Setup DoveCot

Dovecot connects your email to a client (example: Apple Mail.app, Outlook, Thunderbird, Mutt, Pine, SquirrelMail, RoundCube Webmail, etc.) whichever you use to access your mail by serving IMAP and/or POP3 protocols.

IMAP is best allowing offline and online reading of emails.

POP3 is an original mail protocol and can be omitted if not required (recommended). POP3 moves the emails from the server to the client which may not be desired anymore.

LMTP is a local protocol we will use later for spam/virus filtering communication

Install Dovecot:

yum -y install dovecot

Save a copy of the DoveCot configuration file:

cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf.original

Edit the file:

vi /etc/dovecot/dovecot.conf

uncomment and set protocols of your choosing (leave pop3 if you need it):

protocols = imap lmtp

We also need to tell DoveCot where to get the emails in the user accounts.

Save a copy of DoveCot configuration mail location file:

cp /etc/dovecot/conf.d/10-mail.conf /etc/dovecot/conf.d/10-mail.conf.original

Edit the file:

vi /etc/dovecot/conf.d/10-mail.conf

Uncomment the location of the local mail directory for users:

mail_location = maildir:~/Maildir

set dovecot to start on reboot and start dovecot:

chkconfig dovecot on service dovecot start

Create a Test User

Now we can create a temporary linux user account. 

 Remember to remove the account when done otherwise you will leave a vulnerability:

# useradd testpostfix # passwd testpostfix Changing password for user testpostfix. New password: Retype new password: passwd: all authentication tokens updated successfully.

Setup an External Email Client Opera

I downloaded and installed Opera which includes an email client.

In Opera, select Opera → Mail and Chat Accounts… → Add → Email → Next

Real Name: testpostfix Email address: testpostfix@mail.worldcm.com

Select Next

Login Name: testpostfix Password: <use password created above> Select: IMAP

Next → Incoming Mail server: mail.worldcm.com (remove mail. since we aren't using it)

Select Secure Connection(TLS)

Outgoing Mail server: mail.worldcm.com

Leave outgoing tls unchecked

Select Finish

A popup will occur asking you to accept the certificate. The sample imap certificate is only setup so accept it for now. We will secure it later.

Send an email to an external address and receive an email.

Setup a Web based Email Client RoundCube

RoundCube is a Web based IMAP Email Client. It can be installed on the same server or your webserver.

RoundCube requires a webserver, php, and mysql (LAMP). Follow apache and php installation and Installing MySQL on CentOS if its not on the server.

Install RoundCube:

yum -y install roundcubemail

The README, INSTALL, and roundcubemail-README.fedora files contain the steps to install, available in /usr/share/doc/roundcubemail-0.7.3/

Create a database roundcubemail using the instructions at Installing MySQL on CentOS

Create and grant permissions to the user roundcubeuser on database roundcubemail

Create the tables for RoundCube:

mysql -u root -p roundcubemail < /usr/share/doc/roundcubemail-0.7.3/SQL/mysql.initial.sql

Save a copy of RoundCube's database configuration file:

cp /etc/roundcubemail/db.inc.php /etc/roundcubemail/db.inc.php.original

Edit the file:

vi /etc/roundcubemail/db.inc.php

change line to (with the roundcubeuser password you created):

$rcmail_config['db_dsnw'] = 'mysql://roundcubeuser:pass@localhost/roundcubemail';

Move the RoundCube apache config out of the way:

mv /etc/httpd/conf.d/roundcubemail.conf /etc/httpd/conf.d/roundcubemail.conf.original

Edit the existing apache configuration:

vi /etc/httpd/conf.d/webserver.conf

add near the other Aliases:

Alias /roundcubemail /usr/share/roundcubemail

reload apache to pickup roundcube location:

service httpd reload

Save a copy of RoundCube's main configuration file:

cp /etc/roundcubemail/main.inc.php /etc/roundcubemail/db.inc.main.original

Edit the file:

vi /etc/roundcubemail/main.inc.php

If RoundCube is on the same host as the Postfix server, set the default host to localhost, otherwise set it to the Postfix host:

$rcmail_config['default_host'] = 'localhost';

Visit your roundcube site at:

https://mail.worldcm.com/roundcubemail/

Login with your test user testpostfix

In order send emails with the correct address, change the email address from accountname@localhost to your domain:

In RoundCube, click Settings, Identities, select your identity, change email address to the account's email address:testpostfix@mail.worldcm.com, Save.

Login, test sending and receiving emails.

Secure Email Connections on a CentOS 6 Postfix email server with SASL

 Disclaimer: The goal of this section is to secure the email server. However, this setup may not be secure. You should understand and investigate the security of your server, resources are at the bottom of the page.

So far, we have a working email server, however username and passwords from email clients are not secure and could be sniffed/wiretapped.

Since we are using DoveCot to connect mail clients to our emails, we can setup encrypted SASL (Simple Authentication and Security Layer) over which to pass the login information and emails.

SSL/TLS Certificate

If you have a certificate, you can use it below, just point the key and cert parameters to the file in postfix and dovecot configurations below.

If you want to self sign a certificate for testing you can do the following:

install key generator:

yum -y install crypto-utils

generate certificate and key for your domain, follow the prompts:

genkey --days 365 mail.worldcm.com

It will put the keys where we need them in:

/etc/pki/tls/certs/mail.worldcm.com.crt /etc/pki/tls/private/mail.worldcm.com.key

Postfix and Dovecot Configuration

Edit Postfix configuration file to use SASL and TLS:

vi /etc/postfix/main.cf

Add the following to main.cf, I added it near the top, optionally uncomment the line for outlook clients if you need to:

#use DoveCot's SASL implementation smtpd_sasl_type = dovecot  #connect to DoveCot over unix socket (other option is TCP) smtpd_sasl_path = private/auth  #enable SMTP authentication over SASL (required) smtpd_sasl_auth_enable = yes  #uncomment the below line for "Outlook up to and including version 2003 and Outlook Express up to version 6" this simply sends the available authentication methods to the client twice instead of once for these broken clients, it doesn't hurt others #broken_sasl_auth_clients = yes  #do not allow anonymous authentication for unencrypted sessions. These are the connections from other public internet mail servers. We do not allow anonymous connections, but they can be insecure smtpd_sasl_security_options = noanonymous  #use the same settings for a TLS encrypted session: smtpd_sasl_tls_security_options = $smtpd_sasl_security_options  #only offer SASL after a TLS encrypted session is established. Without a TLS session, unauthenticated users won't be able to send mail to remote servers. smtpd_tls_auth_only = yes  #allow SASL authenticated users to send mail smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated reject_unauth_destination  #append the domain to any authenticated user who does not specify the domain smtpd_sasl_local_domain = mail.worldcm.com  #announce STARTTLS for servers to use TLS if available but still accept mail from those without it smtpd_tls_security_level = may  #set our key smtpd_tls_key_file = /etc/pki/tls/private/mail.worldcm.com.key  #set our certificate smtpd_tls_cert_file = /etc/pki/tls/certs/mail.world.com.crt  #setup TLS session cache so negotiation is valid for whole session and doesn't need to be redone for every transaction (saves resources) smtpd_tls_session_cache_database = btree:/var/spool/postfix/smtpd_tls_cache  #supply random characters for key security tls_random_source = dev:/dev/urandom

There are many additional settings including preventing authenticated users from sending email from a name other than their own. Since that requires further configuration to keep track of who is authorized, it is left out in the settings above. If you don't want your users to have the ability to send emails from any name/domain they make up, you can set this here. See Postfix SASL Howto

Reload Postfix:

service postfix reload

Set Dovecot listen on the unix socket for Postfix:

Save a copy of the master configuration if you haven't already:

cp /etc/dovecot/conf.d/10-master.conf /etc/dovecot/conf.d/10-master.conf.original

Edit the configuration file:

vi /etc/dovecot/conf.d/10-master.conf

find the service auth section and comment out the auth-userdb and change to Postfix:

service auth {   # auth_socket_path points to this userdb socket by default. It's typically   # used by dovecot-lda, doveadm, possibly imap process, etc. Its default   # permissions make it readable only by root, but you may need to relax these   # permissions. Users that have access to this socket are able to get a list   # of all usernames and get results of everyone's userdb lookups.   #unix_listener auth-userdb {     #mode = 0600     #user =     #group =   #}    # Postfix smtp-auth   unix_listener /var/spool/postfix/private/auth {     mode = 0666   }    # Auth process is run as this user.   #user = $default_internal_user }

Set Dovecot to use the SSL(TLS) certificate and key:

Save a copy of the dovecot ssl configuration, if you haven't already:

cp /etc/dovecot/conf.d/10-ssl.conf /etc/dovecot/conf.d/10-ssl.conf.original

Edit the configuration file:

vi /etc/dovecot/conf.d/10-ssl.conf

Uncomment and change to:

ssl = yes  ssl_cert = </etc/pki/tls/certs/mail.worldcm.com.crt ssl_key = </etc/pki/tls/private/mail.worldcm.com.key

ssl_cipher_list = ALL:!LOW:!SSLv2:!EXP:!aNULL

Reload DoveCot:

service dovecot reload

Setup Spam and Virus Filtering on a CentOS 6 Postfix email server with SpamAssasin and ClamAV

First, test that you are not an Open Relay that spammers would use to send spam with. Enter your external IP:http://www.mailradar.com/openrelay/

Setup Spam filtering with SpamAssassin

Install SpamAssassin:

yum -y install spamassassin

There is nothing else to do. We will use Amavisd-new to connect to SpamAssassin so we don't need it to start at boot. SpamAssassin updates itself daily in cron /etc/cron.d.

Setup Antivirus filtering with ClamAV

Install ClamAV (daemon, virus database, and software):

yum -y install clamd clamav-db clamav

Setup interface between Postfix and SpamAssassan, ClamAV

Amavisd-new connects the MTA (Postfix) to the filters.

Install Amavisd-new:

yum -y install amavisd-new

Save a copy of the configuration file:

cp /etc/amavisd/amavisd.conf /etc/amavisd/amavisd.conf.original

Edit the Amavisd-new configuration file:

vi /etc/amavisd/amavisd.conf

Uncomment and update:

$myhostname = 'mail.worldcm.com';

Set Postfix to use amavids on port 10024:

vi /etc/postfix/main.cf

add after other parameters we added:

#use amavisd as filter on port 10024 content_filter=amavisfeed:[127.0.0.1]:10024

Save a copy of Postfix master configuration file if not already done:

cp /etc/postfix/master.cf /etc/postfix/master.cf.original

Edit Postfix configuration file:

vi /etc/postfix/master.cf

Add the following lines at the bottom of the file to connect Postfix to Amavisd-new (explanation and updates found in /usr/share/doc/amavisd-new-2.6.4/README_FILES/README.postfix):

amavisfeed unix    -       -       n        -      2     lmtp      -o lmtp_data_done_timeout=1200      -o lmtp_send_xforward_command=yes      -o lmtp_tls_note_starttls_offer=no  127.0.0.1:10025 inet n    -       n       -       -     smtpd     -o content_filter=     -o smtpd_delay_reject=no     -o smtpd_client_restrictions=permit_mynetworks,reject     -o smtpd_helo_restrictions=     -o smtpd_sender_restrictions=     -o smtpd_recipient_restrictions=permit_mynetworks,reject     -o smtpd_data_restrictions=reject_unauth_pipelining     -o smtpd_end_of_data_restrictions=     -o smtpd_restriction_classes=     -o mynetworks=127.0.0.0/8     -o smtpd_error_sleep_time=0     -o smtpd_soft_error_limit=1001     -o smtpd_hard_error_limit=1000     -o smtpd_client_connection_count_limit=0     -o smtpd_client_connection_rate_limit=0     -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_milters     -o local_header_rewrite_clients=     -o smtpd_milters=     -o local_recipient_maps=     -o relay_recipient_maps=

reload postfix to get the change:

service postfix reload

Set Amavisd-new to start after reboot and start Amavisd-new:

chkconfig amavisd on service amavisd start

Set ClamAV to start after reboot and start ClamAV:

chkconfig clamd.amavisd on service clamd.amavisd start

--------------XXXXXX-----------XXXXXXX--------XXXXXXXXX---------XXXXXXXXXXX------------

First, install amavisd-new, clamav and spamassassin packages:

yum --enablerepo=rpmforge,rpmforge-extras install amavisd-new clamav clamav-devel clamd spamassassin

This will likely also install a bunch of dependencies including various perl modules and archive packages. If all went well, two new users, amavis and clamav should have been installed onto the system:

# cat /etc/passwd | grep "amavis\|clamav" clamav:x:101:102:Clam Anti Virus Checker:/var/clamav:/sbin/nologin amavis:x:102:103:Amavis email scan user:/var/amavis:/bin/sh

In addition, the clamav user should automatically have been added to the amavis group:

# groups clamav clamav : clamav amavis

If not, you can manually add clamav to the amavis group:

gpasswd -a clamav amavis

Finally, three new services should have been added to the system

# chkconfig --list | grep "amavisd\|clamd\|spamassassin" amavisd         0:off   1:off   2:on    3:on    4:on    5:on    6:off clamd           0:off   1:off   2:on    3:on    4:on    5:on    6:off spamassassin    0:off   1:off   2:off   3:off   4:off   5:off   6:off

The spamassassin service, which starts spamd, can be set to off as Amavisd-new doesn't actually use the spamassassin daemon (spamd) but rather loads spamassassin as a module.

3. Configuration

SpamAssassin actually requires no special configuration to work with Amavisd-new and will work out of the box. This does not mean that you cannot configure it via/etc/mail/spamassassin/local.cf, or your own cf-files in that directory.

3.1. ClamAV

ClamAV's configuration is stored in /etc/clamd.conf. We must edit /etc/clamd.conf to tell ClamAV that Amavisd-new will communicate using a local UNIX socket rather than a tcp socket, and where to find that socket. Edit the LocalSocket setting and comment out the TCPSocket like so:

### /etc/clamd.conf # # Set the LocalSocket for clam # Note this *MUST* match that set in /etc/amavisd.conf # LocalSocket /var/run/clamav/clamd.sock # # Comment out the TCPSocket setting: # TCPSocket 3310

3.2. Amavisd-new

Amavisd-new keeps it's configuration settings in /etc/amavisd.conf.

Due to the power and flexibility of Amavisd-new, there is actually quite a lot to look at, so we'll cover some of the more important settings a few at a time.

First up, we can disable either virus or spam checking by uncommenting the following lines (by default, both virus and spam checking is enabled as the lines are commented out):

### /etc/amavisd.conf: # # To disable virus or spam checks, uncomment the following: # # @bypass_virus_checks_maps = (1);  # controls running of anti-virus code # @bypass_spam_checks_maps  = (1);  # controls running of anti-spam code # $bypass_decode_parts = 1;         # controls running of decoders & dearchivers

Next, note to following lines although no change is required:

$max_servers = 2;                   # num of pre-forked children (2..30 is common), -m $daemon_user  = "amavis";           # (no default;  customary: vscan or amavis), -u $daemon_group = "amavis";           # (no default;  customary: vscan or amavis), -g ... $inet_socket_port = 10024;          # listen on this local TCP port(s) ... # $notify_method  = 'smtp:[127.0.0.1]:10025'; # $forward_method = 'smtp:[127.0.0.1]:10025';  # set to undef with milter!

$max_servers sets the number of concurrent Amavisd-new processes and must match the number set in /etc/postfix/master.cf "maxproc" column for the amavisfeed service (see configuration of Postfix below).

$daemon_user and $daemon_group should match the user and group, respectively, under which Amavisd-new will run.

$inet_socket_port defines the tcp port over which Amavisd-new will accept connections from Postfix.

$notify_method and $forward_method define the reinjection path of mail from Amavisd-new back into Postfix.

The following settings must be edited (in the case of $mydomain and $myhostname) and uncommented (remove the leading #):

$mydomain = 'example.com';                  # Edit: a convenient default for other settings $MYHOME = '/var/amavis';                    # Uncomment: a convenient default for other settings, -H $helpers_home = "$MYHOME/var";              # Uncomment: working directory for SpamAssassin, -S $lock_file = "$MYHOME/var/amavisd.lock";    # Uncomment, -L $pid_file  = "$MYHOME/var/amavisd.pid";     # Uncomment, -P $myhostname = 'mail.example.com';           # Uncomment & Edit: must be a fully-qualified domain name!

Next up are some SpamAssassin settings which override the default SpamAssassin settings:

$sa_tag_level_deflt  = 2.0;                 # add spam info headers if at, or above that level $sa_tag2_level_deflt = 6.2;                 # add 'spam detected' headers at that level $sa_kill_level_deflt = 6.9;                 # triggers spam evasive actions (e.g. blocks mail) $sa_dsn_cutoff_level = 10;                  # spam level beyond which a DSN is not sent # $sa_quarantine_cutoff_level = 25;         # spam level beyond which quarantine is off $penpals_bonus_score = 8;                   # (no effect without a @storage_sql_dsn database) $penpals_threshold_high = $sa_kill_level_deflt;         # don't waste time on hi spam $sa_mail_body_size_limit = 400*1024;        # don't waste time on SA if mail is larger $sa_local_tests_only = 0;                   # only tests which do not require internet access?

None of these need to be changed, but it's worthwhile being aware of them as this is the most convenient place to tweak spam thresholds.

$sa_tag_level_deflt is the level at which Amavisd-new will write spam info headers such as X-Spam-Flag, X-Spam-Score and X-Spam-Status. If you would always like header info to be written to all messages, set this value to -999.

$sa_tag2_level_deflt sets the level at which spam is tagged in the subject line of the message.

$sa_kill_level_deflt sets the level at which Amavisd-new will block the message and quarantine it. This is useful as SpamAssassin doesn't do this by default.

$sa_dsn_cutoff_level is the level at which delivery failure notices are no longer sent to the sender. As most spam sender addresses are forged anyway, it makes sense not to send failure notices in response to obvious spam as you're only contributing to the problem of backscatter.

$sa_quarantine_cutoff_level is the level at which spam isn't even quarantined. By default it is commented out meaning all spam will be quarantined.

Next up are some email addresses for notifications to be sent:

$virus_admin               = "virusalert\@$mydomain";   # notifications recip. $mailfrom_notify_admin     = "virusalert\@$mydomain";   # notifications sender $mailfrom_notify_recip     = "virusalert\@$mydomain";   # notifications sender $mailfrom_notify_spamadmin = "spam.police\@$mydomain";  # notifications sender

You will probably want to set these to "postmaster\@$mydomain" or some other address you would rather receive spam notifications.

Finally, we need to uncomment the section for ClamAV like so:

### http://www.clamav.net/ ['ClamAV-clamd',   \&ask_daemon, ["CONTSCAN {}\n", "/var/run/clamav/clamd.sock"],   qr/\bOK$/, qr/\bFOUND$/,   qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ], # # NOTE: run clamd under the same user as amavisd, or run it under its own # #   uid such as clamav, add user clamav to the amavis group, and then add # #   AllowSupplementaryGroups to clamd.conf; # # NOTE: match socket name (LocalSocket) in clamav.conf to the socket name in # #   this entry; when running chrooted one may prefer socket "$MYHOME/clamd".

Note that the "/var/run/clamav/clamd.sock" setting must match the "LocalSocket /var/run/clamav/clamd.sock" we made earlier in /etc/clamd.conf.

3.3. Postfix

Next we need to configure the services in Postfix (/etc/postfix/master.cf) to allow mail to be passed to Amavisd-new for filtering and then reinjected back into Postfix.

First we will configure the Amavisd-new service to accept mail From Postfix. Amavisd-new supports both lmtp and smtp, and in this instance we have chosen to use the lmtp protocol. (FIXME: I'm not aware of any reasons for choosing one protocol over the other so selected to use lmtp on the basis that having local delivery to Amavisd-new show up in the logs as "lmtp" makes the log files somewhat easier to read).

Open /etc/postfix/master.cf and add the following service called "amavisfeed":

# ========================================================================== # service type  private unpriv  chroot  wakeup  maxproc command + args #               (yes)   (yes)   (yes)   (never) (100) # ========================================================================== amavisfeed unix    -       -       n        -      2     lmtp     -o lmtp_data_done_timeout=1200     -o lmtp_send_xforward_command=yes     -o disable_dns_lookups=yes     -o max_use=20

Note that the number (2) in the "maxproc" column must match the $max_servers setting in /etc/amavisd.conf. For a detailed description of the options, see the Amavisd-new documentation (/usr/share/doc/amavisd-new-2.5.4/README.postfix.html).

Then we must define a dedicated service to reinject mail back into Postfix. For this we add an smtp service listening on localhost (127.0.0.1) tcp port 10025 (the default setting in /etc/amavisd.conf) to /etc/postfix/master.cf:

# ========================================================================== # service type  private unpriv  chroot  wakeup  maxproc command + args #               (yes)   (yes)   (yes)   (never) (100) # ========================================================================== 127.0.0.1:10025 inet n    -       n       -       -     smtpd     -o content_filter=     -o smtpd_delay_reject=no     -o smtpd_client_restrictions=permit_mynetworks,reject     -o smtpd_helo_restrictions=     -o smtpd_sender_restrictions=     -o smtpd_recipient_restrictions=permit_mynetworks,reject     -o smtpd_data_restrictions=reject_unauth_pipelining     -o smtpd_end_of_data_restrictions=     -o smtpd_restriction_classes=     -o mynetworks=127.0.0.0/8     -o smtpd_error_sleep_time=0     -o smtpd_soft_error_limit=1001     -o smtpd_hard_error_limit=1000     -o smtpd_client_connection_count_limit=0     -o smtpd_client_connection_rate_limit=0     -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_milters,no_address_mappings     -o local_header_rewrite_clients=     -o smtpd_milters=     -o local_recipient_maps=     -o relay_recipient_maps=

For a detailed description of the options, see the Amavisd-new documentation (/usr/share/doc/amavisd-new-2.5.4/README.postfix.html).

After making changes to /etc/postfix/master.cf, we must reload postfix for the changes to take effect:

postfix reload

At this point it might be wise to test the Amavisd-new and Postfix daemons are listening correctly (see the Testing section below).

Once everything is in place and working, the final step is to enable message filtering in Postfix by adding the following setting to /etc/postfix/main.cf:

content_filter=amavisfeed:[127.0.0.1]:10024

and reload postfix for the changes to take effect:

postfix reload

and watch your mail logs.

tail -f /var/log/maillog

XXXXXXXXXXXXXX--XXXXXXXXXXXXXXXXXXX--XXXXXXXXXXXXXXX--XXXXXXXXXXX

Setting up Postfix Spamassassin Amavisd Clamav

Fighting Spam - Setting up Postfix+Amavisd+Spamassassin+Razor+Clamav

Section 1: Installing what's necessary

Before starting let's install the following ports:

/usr/ports/mail/postfix/ /usr/ports/security/amavisd-new/ /var/ports/mail/p5-Mail-SpamAssassin/ /var/ports/security/clamav/

Section 2: Setting Up Postfix

An Overview of What's Going On

To give you an idea of what we're trying to accomplish here, this is a rough idea of how the postfix system works when we're done:

             ----------------- incoming mail | Postfix MTA   |local or on port 25    |               |remote delivery        ------>|               |--------->               |    port 10025 |   |               ----------^------   |                 |       |         v                 |       |           ------v-------|---     /dev/null or quarantine           |  port 10024    |           |                |           | Amavisd Filter |           ------------------

Changes in main.cf

Here is the section in main.cf relevant for configuring antispam on Postfix

header_checks = regexp:/usr/local/etc/postfix/header-checks  smtpd_client_restrictions =    check_client_access hash:/usr/local/etc/postfix/blackwhite.map,    reject_non_fqdn_hostname,    reject_non_fqdn_sender,    reject_unknown_sender_domain,    permit_mynetworks,    reject_rbl_client list.dsbl.org,    reject_rbl_client sbl.spamhaus.org,    reject_rbl_client relays.ordb.org,    reject_rbl_client bl.spamcop.net,    reject_rbl_client dun.dnsrbl.net,    permit  smtpd_sender_restrictions =    check_sender_access hash:/usr/local/etc/postfix/blackwhite.map,    reject_unknown_sender_domain,    reject_non_fqdn_sender,    permit  smtpd_recipient_restrictions =    check_recipient_access hash:/usr/local/etc/postfix/blackwhite.map,    reject_non_fqdn_hostname,    reject_non_fqdn_sender,    reject_non_fqdn_recipient,    reject_unknown_sender_domain,    permit_mynetworks,    reject_unauth_destination,    permit  ### Tarpit those bots/clients/spammers who send errors or scan for accounts smtpd_error_sleep_time = 60 smtpd_soft_error_limit = 60 smtpd_hard_error_limit = 10

Black/Whitelisting at the Server

Right now would be a good time to take domains or individual addresses that you know e-mail you frequently or you want to be able to e-mail you and put them in blackwhite.map. The format is like this:

gooddomain.com OK myfriend@soemplace.com OK spammer@weruintheinternet.com REJECT

When you're done, issue the command:

postmap blackwhite.map

Changes in master.cf

At this point you can change the smtp services at the top to optimize your mail server. We can assume that we won't be doing any virus checking for the internal network which in this case is 10.0.0.1, the external net is 1.2.3.4, this is also where we will point postfix to use amavis which we will comment out for now.

At this point you have two filtering options if you use Postfix 2.1 or above:

I'm using pre-queue filtering below since I have a fairly low amount of mail traffic. If you choose pre-queue filtering, note well the option to make this work in the amavisd.conf below. You'll want to leave this commented until you are all ready to test out amavis, or you may lose mail.

1.2.3.4:smtp      inet  n       -       n       -       -       smtpd # -o content_filter=smtp-amavis:[127.0.0.1]:10024 10.0.0.1:smtp           inet  n       -       n       -       -       smtpd         -o smtpd_client_restrictions=permit_mynetworks,reject 127.0.0.1:smtp          inet    n       -     n       -       -       smtpd         -o smtpd_client_restrictions=permit_mynetworks,reject

Now you'll want to edit your /usr/local/etc/postfix/master.cf and add this to the bottom, this accepts the mail back from amvis when it's done:

smtp-amavis unix -      -       -     -       2  smtp     -o smtp_data_done_timeout=1200     -o disable_dns_lookups=yes 127.0.0.1:10025 inet n  -       -     -       -  smtpd            -o content_filter=            -o local_recipient_maps=     -o relay_recipient_maps=      -o smtpd_restriction_classes=      -o smtpd_client_restrictions=     -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  

Changes in /etc/aliases and Finishing the Postfix Configuration

Next step is to add the following to /etc/aliases:

virusalert: root 

Then issue the command:

postalias /etc/aliases

At this point you can start postfix and see if it's running on ports 25 and 10025. Just make sure you commented the content_filter or smtpd_proxy_filter bit in the master.cf.

# postfix stop && postfix start # sockstat -l4 |grep 25|grep master root     master     51589 11 tcp4   1.2.3.4:25            *:* root     master     51589 14 tcp4   10.0.0.1:25           *:* root     master     51589 17 tcp4   127.0.0.1:25          *:* root     master     51589 95 tcp4   127.0.0.1:10025       *:*

You should see something like the two lines above. If not there's something not configured right in your master.cf. Otherwise, if you see this you're done with postfix for now.

Section 3: Setting up Amavisd-new

Now let's edit the amavisd.conf:

cd /usr/local/etc/ cp amavisd.conf-dist amavisd.conf

There's a million things to tweak here. I highly suggest patiently going through the whole thing so you don't end up coming back to it many times later. I'll list some important bits to fill in, and ones I found useful.

While you're going through this file, if you just copied it like I did in the example above, you may want to delete a lot of the comments you won't use for easier scanning and readability.

$mydomain = 'example.com'; $TEMPBASE = "$MYHOME/tmp"; # this uses a good chunk of space on busier sites                            # so make sure you have it. #Make sure the below are uncommented even though they are default $forward_method = 'smtp:127.0.0.1:10025';  # where to forward checked mail $notify_method = $forward_method;          # where to submit notifications  # The below is fine for a home server, but for a company you might want to bump # it to 10 or more. Also like the comments say, it *must* match the value in # your master.cf: # smtp-amavis unix -      -       -     -       2  smtp   $max_servers = 2;  # VERY IMPORTANT IF YOU ARE USING POST FILTERING # Set the below to 0 if you are using smtpd_proxy_filter, # Set to 1 (default) if you are using content_filter. $insert_received_line = 0;       # behave like MTA: insert 'Received:' header  # For viruses I really recommend just discarding the e-mail. So many viruses # these days have forged recipients that sending a bounce warning does more # harm than good. If you want to discard only viruses that fake sender then # leave $final_virus_destiny at BOUNCE and be sure to update # $viruses_that_fake_sender_re as new virii appear.  $final_virus_destiny      = D_DISCARD;  # (defaults to D_BOUNCE) $final_banned_destiny     = D_BOUNCE;  # (defaults to D_BOUNCE) $final_spam_destiny       = D_DISCARD;  # (defaults to D_REJECT)  # If you get a lot of spam you'll want to make sure you have space for the # dir below, and you may want to clean it periodically. # Something like this in crontab should work for weekly: # 0 1 * * 0       /usr/bin/find /var/virusmails -ctime +7 -exec /bin/rm {} \;  $QUARANTINEDIR = '/var/virusmails';  @av_scanners = ( ### http://clamav.elektrapro.com/ ['Clam Antivirus-clamd',    \&ask_daemon, ["CONTSCAN {}\n", '/var/amavis/clamd'],    qr/\bOK$/, qr/\bFOUND$/,    qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ], );  @av_scanners_backup = ( ); 

now lets create some directories

# cd /var/amavis # mkdir tmp clamav .spamassassin .razor # touch .spamassassin/user_prefs  # chown -R vscan:vscan .razor .spamassassin clamav tmp

Section 4: Setting up clamav

edit /usr/local/etc/clamav.conf

User vscan LocalSocket /var/amavis/clamd

edit /usr/local/etc/freshclam.conf

DatabaseOwner vscan

As Root:

# chown -R vscan:vscan /var/log/clamav # chown -R vscan:vscan /var/run/clamav # chown -R vscan:vscan /usr/local/share/clamav # /usr/local/bin/freshclam --datadir=/usr/local/share/clamav

You'll also want to put the above command in your crontab, the below

will make it run nightly: 

0 1 * * * /usr/local/bin/freshclam --datadir=/usr/local/share/clamav

Edit /etc/group and add vscan to the mail group.

That's all you need to do for clamav

Section 5: Setting up razor

Here's some simple steps to set up razor, make sure you replace postmaster@example.com with your e-mail address.

# su - vscan $ razor-admin -create $ razor-admin -discover $ razor-admin -register -user postmaster@example.com

Section 6: Setting up spamassassin

This is the part that probably takes the most tuning if you really want effective spam blocking. Below is my local.cf. You can take the sample in /usr/local/etc/mail/spamassassin or you can use mine, or you can combine the two. I've added a bit of custom stuff at the bottom that may or may not be relevant to you, so I strongly suggest you go through this.

skip_rbl_checks 1 # By default SpamAssassin runs the Realtime Blackhole List checks.  # It's better to turn this option off.  use_bayes 1 # This turns Bayesean Learning on. 0 turns it off. bayes_path /var/amavis/.spamassassin/bayes # Bayesean database location.  use_razor2 1 # Tells SA that we want to use Razor version 2  use_dcc 0 # In case you want DCC.  use_pyzor 0 # Tells SA that we don't want to use Pyzor  dcc_add_header 1 # DCC header in case you want it.  dns_available yes # If you are sure you have DNS access set it to "yes".  header LOCAL_RCVD Received =~ /\S+\.section6.net\s+\(.*\[.*\]\)/ score LOCAL_RCVD -50 # This checks "Received: from...." lines in the message header. # Set .domain.com to your domain so outgoing mail will not be tagged as # spam. Unless you are a spammer of course. In case you are I strongly urge # you to use this option.  ## Optional Score Increases score DCC_CHECK 4.000 score RAZOR2_CHECK 2.500 score BAYES_99 5.300 score BAYES_90 4.500 score BAYES_80 4.000 # For scores have a look at /usr/local/share/spamassassin/50_scores.cf # file. score HTML_FONT_INVISIBLE 3 score HTML_FONTCOLOR_UNKNOWN 2 score ORDER_NOW 1.5 score CLICK_BELOW 1 score LIMITED_TIME_ONLY 1 # This rule might be extreme but html only spams get through too easy. # In other words, if you can't take the time to write something and are # posting an image only, then you're 86'd! score HTML_IMAGE_ONLY_02 2 score HTML_IMAGE_ONLY_04 2 score OFFERS_ETC 2 score HTML_LINK_CLICK_HERE 1 score LINES_OF_YELLING 1 

I also downloaded some custom rules from http://www.emtinc.net/spamhammers.htm and put them in /usr/local/etc/mail/spamassassin. More of these add-ons make spamassassin do more work, but they also block more spam. Use your judgement.

Another thing to do, is to make your own custom ham rules. For example, if you work for a company such as Apple, you may wish to hamify words like Apple, Macintosh, PowerPC, or whatever. If this is just for yourself then put your name in there (as long as it's not part of your e-mail address), or other common words people might use with you.

Setting up Bayesian Learning with Spamassassin

If you're like me you probably have a folder with a ton of spam in it. You can i use this for the bayesian learner in Spamassassin (which is activated in the above config). I also have an mbox folder with a ton of regular mail with no spam in it.

So here's what I do:

sa-learn --spam --mbox -p /var/amavis/.spamassassin/user_prefs ~/Mail/spam sa-learn --ham --mbox -p /var/amavis/.spamassassin/user_prefs ~/Mail/mbox sa-learn --rebuild -p /var/amavis/.spamassassin/user_prefs

Section 7: Finishing up and testing

At this point you'll want to test spamassassin to make sure it's working. try saving an email and running this command on it:

spamassassin -t < mail.txt

If it works then Spamassassin is good to go. If it takes a really long time (longer than 10 seconds) like it did on my Pentium 166 you might want to use a faster machine for this.

From here you can start amavisd from the command line and see if it's running.

# /usr/local/sbin/amavisd # ps auxww|grep amavisd vscan       761  0.0  0.7 28556  632  ??  Ss   11:13PM   0:12.83 amavisd (master) (perl) vscan     10526  0.0  0.0 29412   12  ??  I     1:00PM   0:08.47 amavisd (child) (perl) vscan     10527  0.0  0.0 29676    0  ??  IW   -         0:00.00 amavisd (child) (perl)

If you don't see it in the process list then you should have got some errors

on the command line when you tried to start it. 

Now lets start clamd using the same process as above:

# /usr/local/sbin/clamd # ps auxww|grep clamd vscan      3141  0.0  0.6 21868  576  ??  Ss   12:11PM   0:03.36 clamd

If you didn't see it in the process list check /var/log/clamav/clamd.log to see if there were any errors.

At this point if you have both amavis running, clamd is go, go back and uncomment the content_filter or smtp_proxy_filter line in /usr/local/etc/postfix/master.cf and reload postfix:

# postfix reload

----------XXX----------------------XXX---------------------XXX-------

How to configure Amavisd,SpamAssassin with postfix in centos 6.5

1) configure amavisd to accept mail from MTA and pass it to ClamAV and SpamAssassin for checking

2) return it back to MTA for delivery

3) Amavisd will use lmtp listening on TCP port 10024 to accept mail from MTA and then pass it to ClamAV using a locScanned mail al UNIX socket and SpamAssassin using the Mail::SpamAssassin Perl module.

4) will be returned to MTA using smtp on TCP port 10025 for delivery.

1. Introduction of SpamAssassin and Amavisd-new

a. Amavisd-new (www.ijs.si/software/amavisd/)

§  a reliable high-performance interface between an email server (MTA) and content checkers like virus scanners

§  supports both (E)SMTP and LMTP protocols as well as UNIX sockets for communicating with the MTA and content checkers.

§  use dedicated helper programs such as the Mail::SpamAssassin Perl module.

§  supports a number of MTA's.

b. SpamAssassin (spamassassin.apache.org)

§    Be used for e-mail spam filtering based on content-matching rules.

§    uses a variety of spam-detection techniques, that includes DNS-based and fuzzy-checksum-based spam detection, Bayesian filtering, external programs, blacklists and online databases.

§    can be integrated with the mail server to automatically filter all mail for a site.

§    awarded the Linux New Media Award 2006 as the "Best Linux-based Anti-spam Solution".

2. Packages installation

# rpm –qa | grep rpmforge

# yum install amavisd-new spamassassin –y

# rpm –qa | grep amavisd-new spamassassin

# chkconfig amavisd on; chkconfig spamassassin on

# chkconfig --list | grep "amavisd\|spamassassin“

3. Configuration

a. Spamassassin

# vi /etc/mail/spamassassin/local.cf

required_hits  5

# spamassassin --lint                             //syntax checking

b. Amavisd-new

# vi /etc/amavisd/amavisd.conf

$max_servers = 2;                        # num of pre-forked children (2..30 is common), -m

$daemon_user  = "amavis";            # (no default;  customary: vscan or amavis), -u

$daemon_group = "amavis";           # (no default;  customary: vscan or amavis), -g

$inet_socket_port = 10024;              # listen on this local TCP port(s)

$mydomain = ‘chul.com';                                  # Edit: a convenient default for other settings

$myhostname = ‘server.chul.com';

$virus_admin               = “tland\@$mydomain";               # notifications recip.

$mailfrom_notify_admin     = "virusalert\@$mydomain";         # notifications sender

$mailfrom_notify_recip     = "virusalert\@$mydomain";           # notifications sender

$mailfrom_notify_spamadmin = "spam.police\@$mydomain";       # notifications sender

['ClamAV-clamd', 380     \&ask_daemon, ["CONTSCAN {}\n", "/var/run/clamav/clamd.sock"],

c. Postfix

# vi /etc/postfix/main.cf

content_filter=amavisfeed:[127.0.0.1]:10024

# vi /etc/postfix/master.cf

 amavisfeed unix    -       -       n        -      2     lmtp

    -o lmtp_data_done_timeout=1200

    -o lmtp_send_xforward_command=yes

    -o disable_dns_lookups=yes

    -o max_use=20

127.0.0.1:10025 inet n    -       n       -       -     smtpd

    -o content_filter=

    -o smtpd_delay_reject=no

    -o smtpd_client_restrictions=permit_mynetworks,reject

    -o smtpd_helo_restrictions=

    -o smtpd_sender_restrictions=

    -o smtpd_recipient_restrictions=permit_mynetworks,reject

    -o smtpd_data_restrictions=reject_unauth_pipelining

    -o smtpd_end_of_data_restrictions=

    -o smtpd_restriction_classes=

    -o mynetworks=127.0.0.0/8

    -o smtpd_error_sleep_time=0

    -o smtpd_soft_error_limit=1001

    -o smtpd_hard_error_limit=1000

    -o smtpd_client_connection_count_limit=0

    -o smtpd_client_connection_rate_limit=0

    -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_milters,no_address_mappings

    -o local_header_rewrite_clients=

    -o smtpd_milters=

    -o local_recipient_maps=

    -o relay_recipient_maps=

4. Service startup and connection test

a. Service startup

# service amavisd start 

# service postfix restart; service spamassassin start

# ps –ef | grep amavis

# ps –ef | grep spamd

# netstat –nat | grep 10024

# netstat –nat | grep 10025

b. Connect to amavisd and smtpd port

# telnet localhost 10024

# telnet localhost 10025

-------XXXXXXXX---XXXXXXXXXX-----XXXXXXXXXXXX-----XXXXXXXXXX------