Headlines News :
Home » , » Postfix Tutorial

Postfix Tutorial

Written By Unknown on Tuesday, March 15, 2011 | 8:48 AM


For the sake of this tutorial anything that is downloaded will be stored in /usr/source. I would suggest that in /usr/source you create seperate directories for each install. For example, /usr/source/postfix, /usr/source/mailwatch, and /usr/source/postfixadmin just as examples. Then store your files in those directories and work from there. Will help to keep your file system clean and keep you from having a headache trying to find everything

To get postfix built and installed I've used the slackbuild script available from Slackbuilds.org and of course the source from Postfix.org.


Build the Package

Ok, once you have both of these ready to go we need to add a user/group for postfix and a group for postdrop:

groupadd -g 200 postfix
useradd -u 200 -d /dev/null -s /bin/false -g postfix postfix
groupadd -g 201 postdrop


Before we kick off postfix.SlackBuild there is a change you will want to make to the script. This change will build postfix with mysql abilities which will come in handy later on.
Find line 183 it should look like this:

make makefiles \

Change the CCARGS and AUXLIBS lines to read:
CCARGS='-DUSE_SASL_AUTH -DDEF_SERVER_SASL_TYPE=\"dovecot\" -DUSE_TLS -DHAS_MYSQL -I/usr/include/mysql' \
 AUXLIBS="-L/var/lib/mysql -lmysqlclient -lz -lm -lssl -lcrypto"
Then save the file.

Now that we have those setup, lets move on to getting the build script started:
Note: be sure that you update the version in postfix.SlackBuild or it will error out on you :)

chmod +x postfix.SlackBuild
./postfix.SlackBuild

Now, depending on what type of hardware you have, this can take a little bit :)
Once the package is built and created it is now time to install it.

installpkg postfix-2.3.8-i486-1.tgz



Setup MySQL database and tables

This part of the tutorial assumes that you have MySQL installed, configured, and you know how to create databases and populate them with data. Now that we have postfix installed, we need to get the MySQL database and tables created that we will use to do authentication and virtual domains against.


Create database


mysqladmin create postfix



Create the tables


CREATE TABLE `admin` (
  `username` varchar(255) NOT NULL default ,
  `password` varchar(255) NOT NULL default ,
  `created` datetime NOT NULL default '0000-00-00 00:00:00',
  `modified` datetime NOT NULL default '0000-00-00 00:00:00',
  `active` tinyint(1) NOT NULL default '1',
  PRIMARY KEY  (`username`),
  KEY `username` (`username`)
);


CREATE TABLE `alias` (
  `address` varchar(255) NOT NULL default ,
  `goto` text NOT NULL,
  `domain` varchar(255) NOT NULL default ,
  `created` datetime NOT NULL default '0000-00-00 00:00:00',
  `modified` datetime NOT NULL default '0000-00-00 00:00:00',
  `active` tinyint(1) NOT NULL default '1',
  PRIMARY KEY  (`address`),
  KEY `address` (`address`)
);


CREATE TABLE `domain` (
  `domain` varchar(255) NOT NULL default ,
  `description` varchar(255) NOT NULL default ,
  `aliases` int(10) NOT NULL default '0',
  `mailboxes` int(10) NOT NULL default '0',
  `maxquota` int(10) NOT NULL default '0',
  `transport` varchar(255) default NULL,
  `backupmx` tinyint(1) NOT NULL default '0',
  `created` datetime NOT NULL default '0000-00-00 00:00:00',
  `modified` datetime NOT NULL default '0000-00-00 00:00:00',
  `active` tinyint(1) NOT NULL default '1',
  PRIMARY KEY  (`domain`),
  KEY `domain` (`domain`)
);


CREATE TABLE `domain_admins` (
  `username` varchar(255) NOT NULL default ,
  `domain` varchar(255) NOT NULL default ,
  `created` datetime NOT NULL default '0000-00-00 00:00:00',
  `active` tinyint(1) NOT NULL default '1',
  KEY `username` (`username`)
);


CREATE TABLE `log` (
  `timestamp` datetime NOT NULL default '0000-00-00 00:00:00',
  `username` varchar(255) NOT NULL default ,
  `domain` varchar(255) NOT NULL default ,
  `action` varchar(255) NOT NULL default ,
  `data` varchar(255) NOT NULL default ,
  KEY `timestamp` (`timestamp`)
);


CREATE TABLE `mailbox` (
  `username` varchar(255) NOT NULL default ,
  `password` varchar(255) NOT NULL default ,
  `name` varchar(255) NOT NULL default ,
  `maildir` varchar(255) NOT NULL default ,
  `quota` int(10) NOT NULL default '0',
  `domain` varchar(255) NOT NULL default ,
  `created` datetime NOT NULL default '0000-00-00 00:00:00',
  `modified` datetime NOT NULL default '0000-00-00 00:00:00',
  `active` tinyint(1) NOT NULL default '1',
  PRIMARY KEY  (`username`),
  KEY `username` (`username`)
);


CREATE TABLE `vacation` (
  `email` varchar(255) NOT NULL default ,
  `subject` varchar(255) NOT NULL default ,
  `body` text NOT NULL,
  `cache` text NOT NULL,
  `domain` varchar(255) NOT NULL default ,
  `created` datetime NOT NULL default '0000-00-00 00:00:00',
  `active` tinyint(1) NOT NULL default '1',
  PRIMARY KEY  (`email`),
  KEY `email` (`email`)
);

Add user to database "postfix"

GRANT ALTER,CREATE,DELETE,INSERT,SELECT,UPDATE on postfix.* to postfix@localhost IDENTIFIED BY 'postfix';

Configure postfix to use MySQL

Ok, now that we have postfix installed it is time to configure it to use MySQL.
Edit /etc/postfix/main.cf. I'm going to show you parts of my configuration that I use. Other parts such as SMTP-Auth and TLS/SSL clients you will need to read the documentation on to get working because it is beyond the scope of this howto.
smtpd_helo_required = yes
 disable_vrfy_command = yes 

 smtpd_sender_restrictions =
   permit_mynetworks,
   reject_unauth_pipelining,
   reject_unknown_client

 smtpd_client_restrictions =
   permit_mynetworks,
   reject_unauth_pipelining,
   reject_unknown_client

 smtpd_etrn_restrictions = permit_mynetworks, reject

 smtpd_recipient_restrictions =
   permit_mynetworks,
   reject_non_fqdn_hostname,
   reject_non_fqdn_sender,
   reject_non_fqdn_recipient,
   reject_unauth_destination,
   reject_unauth_pipelining,
   reject_invalid_hostname,
   reject_rbl_client zen.spamhaus.org,
   check_policy_service inet:127.0.0.1:2501

 virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cf
 virtual_gid_maps = static:200
 virtual_mailbox_base = /var/spool/mail/virtual
 virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
 virtual_mailbox_limit = 51200000
 virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
 virtual_minimum_uid = 200
 virtual_transport = virtual
 virtual_uid_maps = static:200
These settings will get you started. You will also want to search for relay_domains and add this:
relay_domains = proxy:mysql:/etc/postfix/mysql_virtual_relay_domains_maps.cf
You will next want to search for header_checks and add this:
header_checks = regexp:/etc/postfix/header_checks
Next, create the virtual directory:
mkdir /var/spool/mail/virtual
 chown postfix.postfix /var/spool/mail/virtual
This is where the virtual domain email boxes will be stored.
A few notes
1) The virtual_gid_maps, virtual_minimum_uid, and virtual_uid_maps are the postfix group id and user group id (gid/uid) that you created earlier in this howto. For the sake of this howto, they are 200 and 200.
2) The header_checks = regexp:/etc/postfix/header_checks line will be used later on in the howto when we configure MailScanner
3) The check_policy_service inet:127.0.0.1:2501 is for the SQLgrey policy service later in this howto.
4) virtual_alias_maps, virtual_mailbox_base, virtual_mailbox_domains, virtual_mailbox_maps, virtual_mailbox_limit_maps, and mysql_virtual_relay_domains_maps.cf will be created later on to facilitate the proper operation of the email server.

Time to add in our above .cf files etc
Ok, we've made it this far. Time to add in some "security" type stuff :)

header_checks
/^Received:/ HOLD
mysql_virtual_alias_maps.cf
user = postfix
 password = postfix
 hosts = localhost
 dbname = postfix
 query = SELECT goto FROM alias WHERE address='%s' AND active = 1
mysql_virtual_domains_maps.cf
user = postfix
 password = postfix
 hosts = localhost
 dbname = postfix
 query = SELECT domain FROM domain WHERE domain='%s' and backupmx = '0' and active = '1'
mysql_virtual_mailbox_maps.cf
user = postfix
 password = postfix
 hosts = localhost
 dbname = postfix
 query = SELECT maildir FROM mailbox WHERE username='%s' AND active = 1
mysql_virtual_mailbox_limit_maps.cf
user = postfix
 password = postfix
 hosts = localhost
 dbname = postfix
 query = SELECT quota FROM mailbox WHERE username='%s'
mysql_virtual_relay_domains_maps.cf
user = postfix
 password = postfix
 hosts = localhost
 dbname = postfix
 query = SELECT domain FROM domain WHERE domain='%s' and backupmx = '1' and active = '1'
That's it! Postfix is now configured to run using MySQL. Now we move on to greylisting with SQLgrey and getting MailScanner installed along with Spamassassin and ClamAV.

Install SQLgrey

Now, before you can start to work with SQLgrey you need to make sure you have the DBD::MySQL, Net::Server::Multiplex, and IO::Multiplex perl modules installed. If you are not sure how to do this you will have to google it.
Once you get that installed, we can move on...............................OK! Installed.. great!
Create the SQLgrey database

mysqladmin create sqlgrey

Add in the user you want to use for the database, for the sake of this howto, we'll stick with sqlgrey

GRANT ALTER,CREATE,DELETE,INSERT,SELECT,UPDATE ON sqlgrey.* TO sqlgrey@localhost IDENTIFIED BY 'sqlgrey';

Then add the sqlgrey user/group

groupadd -g 202 sqlgrey
useradd -u 202 -d /home/sqlgrey -s /bin/false -g sqlgrey sqlgrey

Create the /home/sqlgrey directory

mkdir /home/sqlgrey

chown /home/sqlgrey to the sqlgrey user/group

chown sqlgrey.sqlgrey /home/sqlgrey

Then run install

make && make install

Then we need to edit the sqlgrey.conf file in /etc/sqlgrey and be sure the db_name, db_user, and db_pass are what you configured when creating the sqlgrey database.
You will also want to create clients_ip_whitelist.local and clients_fqdn_whitelist.local in /etc/sqlgrey:

touch clients_ip_whitelist.local
touch clients_fqdn_whitelist.local

create the /etc/rc.d/rc.sqlgrey start/stop script
#!/bin/sh
 #
 # sqlgrey:        Init script for sqlgrey postfix policy service
 #
 # chkconfig: 345 90 10
 # description: SQLgrey is a postfix grey-listing policy service.
 # pidfile: /var/run/sqlgrey.pid  

 # Source function library.
 #. /etc/init.d/functions 

 # See how we were called.
 case "$1" in
   start)
         echo -n "Starting SQLgrey: "
         # SQLite put files in the working directory
         cd ~sqlgrey
         sqlgrey -d
         #echo_success
         echo "Ok"
         ;; 

   stop)
         echo -n "Shutting down SQLgrey: "
         sqlgrey -k
         #echo_success
         echo "Ok"
         ;;

   status)
         status sqlgrey
         ;; 

   restart)
         $0 stop
         sleep 1 # hack: missing REUSEADDR from Net::Server?
         $0 start
         ;;

   *)
         echo "Usage: sqlgrey {start|stop|status|restart}"
         exit 1
 esac

 exit 0
Note: I'm not sure where I got this, but it works :) If anyone has a better one, email me.
Then start the service!

/etc/rc.d/rc.sqlgrey start

Be sure to check your /var/log/maillog for any errors.
Ok, now we have sqlgrey running postfix configured and almost ready to go. Now we move on to ClamAV, Spamassassin, and MailScanner. We want to do the installation of ClamAV and Spamassassin first before we build MailScanner. Once we finish with those, we'll work on dovecot and then we'll finish it off by installing postfixadmin, sqlgrey web interface, and mailwatch.

Install ClamAV

First things first, get the source at ClamAV.net and once you have that we can begin!
Create the user and group clamav will use

groupadd clamav
useradd clamav -g clamav -s /sbin/nologin

Next we do:

./configure --prefix=/usr --sysconfdir=/etc

Once that completes, time to make and install:

make && make check && make install

Now edit /etc/clamd.conf

"Example" - should be commented out.
"LogFile" - should be set to /var/log/clamav/clamd.log
"LogTime" - should be uncommmented.
"LogSyslog" - should be uncommented.
"ScanMail" - should be uncommented.

clamavmodule installation
From here you can install clamavmodule. Its a somewhat faster alternative to using the basic clamscan binary and can be a bit easier to deal with than the clamd daemon. To each their own. I use it; works great.

type: cpan
Once at the prompt type: install Mail::ClamAV
and then let cpan do the rest!

If you get prompted for missing modules, just accept the default to add them to the "build que." And that's that for ClamAV. Now for Spamassassin.

Install Spamassassin

If you don't have spamassassin downloaded, you need to go and get it.
Once you have it downloaded unpack it and move into the directory.
Requirements

REQUIRED module: Digest::SHA1
REQUIRED module: HTML::Parser

You will want BOTH of these modules or Spamassassin will not build right.


Build Spamassassin


perl Makefile.PL (this will ask you a few questions)
make && make install

Create a local.cf in /etc/mail/spamassassin
Note: This will change later on after MailScanner is installed.

# This is the right place to customize your installation of SpamAssassin.
#
# See 'perldoc Mail::SpamAssassin::Conf' for details of what can be
# tweaked.
#
###########################################################################
#
# rewrite_subject 0
# report_safe 1
# trusted_networks 212.17.35. 
rewrite_header Subject  *****SPAM*****
required_hits 5

Once that is complete, that's that! Not much to installing Spamassassin these days.


Install MailScanner

As of this writing MailScanner is at version 4.58.9.

Obtain the source and once you have it, lets get started.
Build MailScanner
Move into the MailScanner source directory and execute:

./install.sh

During the configure/compile MailScanner automatically builds the modules it needs to run. This can take some time, so be patient.
After the installation completes there is another perl module that needs installed so that the check_mailscanner script can start the application:

Sys::Hostname::Long

Be sure to install that or after everything is said and done you'll get an error ;).




Configure Postfix to use MailScanner

Here, we will setup postfix to put everything that it gets into a "hold" queue so that MailScanner can grab it.
Edit MailScanner.conf
Using your favorite editor:

nano /opt/MailScanner/etc/MailScanner.conf

The below options were taken, for simplicity reasons, from the MailScanner official walk through. You will want to edit these to ensure that postfix will work properly with MailScanner.

Run As User = postfix                               - Should be line 115
Run As Group = postfix                              - Should be line 120
Incoming Queue Dir = /var/spool/postfix/hold        - Should be line 149
Outgoing Queue Dir = /var/spool/postfix/incoming    - Should be line 153
MTA = postfix                                       - Should be line 175
Virus Scanners = clamav                             - Should be line 526

Next we need to change permissions so that postfix can access quarantine directories. We also set the quarantine directory to the group that the web server runs as to enable MailWatch to properly work with quarantined messages:

chown postfix.postfix /var/spool/MailScanner/incoming
chown postfix.nobody /var/spool/MailScanner/quarantine

Now, lets get spamassassin to use spam.assassin.prefs.conf from MailScanner.

mv /etc/mail/spamassassin/local.cf /etc/mail/spamassassin/local.cf.bak
ln -sf /opt/MailScanner/etc/spam.assassin.prefs.conf /etc/mail/spamassassin/local.cf

Once that is completed.. lets startup postfix and MailScanner!

/etc/rc.d/rc.postfix start
/opt/MailScanner/bin/check_mailscanner

Make sure to check your /var/log/maillog for any errors during startup. By default, MailScanner starts with 5 children. You can change this setting in /opt/MailScanner/etc/MailScanner.conf. I encourage you to read through it and become familiar with the configuration.
Also, pay attention to /opt/MailScanner/etc/spam.assassin.prefs.conf as this will now determine what spamassassin settings are utilized.


Install dovecot

I have once again utilized the build script for this from Slackbuilds.org.
Once you have this build script and the source, its time to get started.
Create a user for dovecot

useradd -d /dev/null -s /bin/false -u 91 dovecot

This will allow the build script to run as it should.
Change to the build script
By default, the slackbuild script from Slackbuilds.org does not build with MySQL support. We are going to make a minor change to the script to allow this.
Locate:

./configure \
  --prefix=/usr \
  --sysconfdir=/etc \
  --localstatedir=/var \
  --disable-ipv6 \
  --without-pam \
  --with-pop3d

and add --with-mysql:

./configure \
  --prefix=/usr \
  --sysconfdir=/etc \
  --localstatedir=/var \
  --disable-ipv6 \
  --without-pam \
  --with-pop3d \
  --with-mysql

Start the build script

chmod +x dovecot.SlackBuild
./dovecot.SlackBuild

This may take some time..........
Install dovecot
From the package we just created:

installpkg dovecot-$VERSION-i486-1.tgz

Configure dovecot for mysql interaction
Ok, now that we have dovecot installed, lets get some configuration out of the way.
Below is a sample of the dovecot.conf file that I use in /etc/dovecot.conf:

protocols = imap pop3
listen = *
disable_plaintext_auth = no
log_path = /var/log/imapd
info_log_path = /var/log/imapd.info
log_timestamp = "%b %d %H:%M:%S "
ssl_disable = yes
login_process_size = 64
mail_location = maildir:/var/mail/virtual/%u/
namespace private {
  separator = .
  prefix =
  inbox = yes
}
mail_extra_groups = postfix
verbose_proctitle = yes
first_valid_uid = 623
first_valid_gid = 623
mbox_read_locks = fcntl
mbox_write_locks = dotlock fcntl
protocol imap {
  mail_plugins = quota imap_quota
  imap_client_workarounds = delay-newmail outlook-idle netscape-eoh tb-extra-mailbox-sep
}
protocol pop3 {
  login_executable = /usr/libexec/dovecot/pop3-login
  mail_executable = /usr/libexec/dovecot/pop3
  pop3_uidl_format =  %u
  pop3_logout_format = top=%t/%p, retr=%r/%b, del=%d/%m, size=%s
  mail_plugins = quota
}
protocol lda {
  postmaster_address = postmaster@domain.tld
  sendmail_path = /usr/sbin/sendmail
}
auth_executable = /usr/libexec/dovecot/dovecot-auth
auth_username_chars = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890.-_@
auth_verbose = no
auth_debug = no
auth default {
  mechanisms = plain login
  passdb sql {
    args = /etc/dovecot-mysql.conf
  }
  userdb sql {
    args = /etc/dovecot-mysql.conf
  }
  user = root
  socket listen {
    master {
      path = /var/run/dovecot/auth-master
      mode = 0600
    }
    client {
      path = /var/spool/postfix/private/auth
      mode = 0660
      user = postfix
      group = postfix
    }
  }
}
dict {
}
plugin {
  quota = maildir:storage=14336
}

This is a default configuration file. This should get things working, basically, but I do encourage you to read through it. There are other options that can be used, but they are beyond the scope of this tutorial. Anything that is uncommented can be used to get a default installation running.
dovecot MySQL integration
This is for the /etc/dovecot-mysql.conf file:

# Database driver: mysql, pgsql
driver = mysql
# Currently supported schemes include PLAIN, PLAIN-MD5, DIGEST-MD5, and CRYPT.
default_pass_scheme = CRYPT 
# Database options
connect = host=localhost dbname=postfix user=postfix password=postfix
password_query = SELECT password FROM mailbox WHERE username = '%u' AND active = '1'
user_query = SELECT maildir, 200 AS uid, 200 AS gid, CONCAT('dirsize:storage=', ROUND( mailbox.quota / 1024 ) ) AS quota FROM mailbox WHERE \
username = '%u' AND active = '1'
# eof

Beware the line wrap! Where you see the \ the line below was wrapped and should be on the same line that is above it. The "200 AS uid" and "200 AS gid" are the uid/gid of postfix that you used earlier in this tutorial.
Starting up dovecot
Now, the great thing about using the Slackbuilds.org script is that it creates a nice start up script for you, so lets fire up dovecot!

cd /etc/rc.d
chmod +x /etc/rc.d/rc.dovecot
/etc/rc.d/rc.dovecot start

That should be it! Make sure to double-check your /var/log/maillog, /var/log/imapd, and /var/log/imapd.info files for any issues. Other than that, you should now have a fully functional email server.
We'll next be installing a few tools to help administration a bit.


Install postfixadmin

postfixadmin is a nice web interface to postfix when using MySQL.
It can be obtained from the PostfixAdmin website.
Once you've acquired this we need to unpack it and move it somewhere the web server can see it. For the sake of this tutorial, I'll put it in /var/www/htdocs/postfixadmin
Now that we have that completed, we need to set some permissions:

cd /var/www/htdocs/postfixadmin
chmod 640 *.php *.css
cd /var/www/htdocs/postfixadmin/admin/
chmod 640 *.php .ht*
cd /var/www/htdocs/postfixadmin/images/
chmod 640 *.gif *.png
cd /var/www/htdocs/postfixadmin/languages/
chmod 640 *.lang
cd /var/www/htdocs/postfixadmin/templates/
chmod 640 *.tpl
cd /var/www/htdocs/postfixadmin/users/
chmod 640 *.php


Create postfixadmin database
This part is not necessary as we've created the database that postfix will already be using along with postfixadmin.
We do need to setup the config.inc.php:

cp config.inc.php.sample config.inc.php

The big thing in here is the database, the username, and the password. They should all be postfix respectively. You can go through the configuration as you wish to configure what you want to use.
You will also want to be sure that in /etc/apache/httpd.conf that the settings for .htaccess are set:

AllowOverride All

You will also want to move to the very end of the /etc/apache/httpd.conf file and uncomment:

Include /etc/apache/mod_php.conf

Once you've done that, restart apache.

Configure .htpasswd in /var/www/htdocs/postfixadmin/admin
This will give you an initial login to the administrator interface:

cd /var/www/htdocs/postfixadmin/admin
rm .htpasswd
htpasswd -c .htpasswd admin

When prompted for the password, use whatever you like. You can even change the username "admin" to something to more your liking.

Access postfixadmin
Now, just go to http://domain.tld/postfixadmin/admin and login!
That's it! You should now be able to add/delete users/mailboxes/domains. Have fun!


Install MailWatch

MailWatch is a handy little web gui interface to MailScanner. This will allow you and your users to manage their spam filters and any messages that are quarantined.

Get the source
Just head on over to http://mailwatch.sf.net and get the source.

Of course.. extract the source

tar xf mailwatch-1.0.3.tar.gz


magic_quotes_gpc
You will want to make sure this is enabled in the php.ini in /etc/apache/php.ini:

magic_quotes_gpc = On

Once you've gotten that changed, restart apache: /etc/rc.d/rc.httpd restart

The following is straight from the INSTALL file that comes with the mailwatch source. All commands should be run as root.

Create the database

mysql < create.sql

NOTE: you will need to modify the above as necessary for your system if you have a root password for your MySQL database.

Create a MySQL user and password & Set-up MailScanner for SQL logging

# mysql
mysql> GRANT ALTER,CREATE,DELETE,INSERT,SELECT,UPDATE ON mailscanner.* TO mailwatch@localhost IDENTIFIED BY '';
mysql> GRANT FILE ON mailscanner.* TO mailwatch@localhost IDENTIFIED BY '';
mysql> FLUSH PRIVILEGES;

Edit MailWatch.pm and change the $db_user and $db_pass values accordingly and move MailWatch.pm to /opt/MailScanner/lib/MailScanner/CustomFunctions/MailWatch.pm

Create a MailWatch web user

# mysql mailscanner -u mailwatch -p
Enter password: ******
mysql> INSERT INTO users VALUES ('',md5(''),'','A',0,0,0,0,0);


Install & Configure MailWatch

Move the mailscanner directory to the web server's root.

mv mailscanner /var/www/htdocs/


Check the permissions of /var/www/htdocs/mailscanner/images and /var/www/htdocs/images/cache - they should be ug+rwx and owned by root and in the same group as the web server user (default is nobody on base Slackware installs).

chown root:nobody images
chmod ug+rwx images
chown root:nobody images/cache
chmod ug+rwx images/cache


Also, check the permissions of /var/www/htdocs/mailscanner/temp:

chmod 755 temp
chown nobody.nobody /var/www/htdocs/mailscanner/temp

NOTE: The permissions on /var/www/htdocs/mailscanner/temp should be owned by your web server's user and group.


Create conf.php
Create conf.php by copying conf.php.example and edit the values to suit, you will need to set DB_USER and DB_PASS to the MySQL user and password that you created earlier.
To clean the quarantine - set 'QUARANTINE_DAYS_TO_KEEP' in conf.php and run './quarantine_maint --clean'. This should then be run daily from cron.

cp conf.php.example conf.php



Configure quarantine release

We need to make a few changes to MailScanner so that when we release messages from the quarantine they aren't put right back IN to the quarantine.

Why are messages quarantined again when I release them in MailWatch?

This is because you need to bypass certain checks for messages from 127.0.0.1 to allow the released messages to pass through MailScanner without being quarantined again. Set the following in /opt/MailScanner/etc/Mailscanner.conf:
Search for "Scan Messages", mine is around line 292, then set as:

Scan Messages = %rules-dir%/scan.messages.rules

Next, move into the /opt/MailScanner/etc/rules directory and create scan.messages.rules:

From:           127.0.0.1       no
FromOrTo:       default         yes


Set-up MailScanner
Stop MailScanner

# killall MailScanner


Next edit /opt/MailScanner/etc/MailScanner.conf

Always Looked Up Last = &MailWatchLogging
Detailed Spam Report = yes
Quarantine Whole Message = yes
Quarantine Whole Message As Queue Files = no
Include Scores In SpamAssassin Report = yes
Quarantine User = root
Quarantine Group = nobody (this should be the same group as your web server)
Quarantine Permissions = 0660

Spam Actions and High Scoring Spam Actions should also have 'store' as one of the keywords if you want to quarantine items for learning/viewing in MailWatch.
If you want to use the integrated Blacklist/Whitelist (optional): then edit the file and change the connection string in the CreateList subroutine to match MailWatch.pm.
Copy SQLBlackWhiteList.pm to /opt/MailScanner/lib/MailScanner/CustomFunctions and in MailScanner.conf set:

Is Definitely Not Spam = &SQLWhitelist
Is Definitely Spam = &SQLBlacklist

Then edit SQLBlackWhitelist.pm and change the connection string in the CreateList subroutine to match MailWatch.pm.

Move the Bayesian Databases and set-up permissions (skip this if you don't use bayes)
Edit /opt/MailScanner/etc/spam.assassin.prefs.conf and set:

bayes_path /opt/MailScanner/etc/bayes
bayes_file_mode 0660


Create the 'new' bayes directory
Make the directory owned by the same group as the web server user and make the directory setgid:

mkdir /opt/MailScanner/etc/bayes
chown root:nobody /opt/MailScanner/etc/bayes
chmod g+rws /opt/MailScanner/etc/bayes


Test SpamAssassin to make sure that it is using the new databases correctly

spamassassin -D -p /opt/MailScanner/etc/spam.assassin.prefs.conf --lint


If you get an error talking about /usr/bin/perl5.8.7 not being found, you can use this work-a-round:

ln -sf /usr/bin/perl /usr/bin/perl5.8.7


and you should see soomething like:

debug: using "/opt/MailScanner/etc/spam.assassin.prefs.conf" for user prefs file
debug: bayes: 28821 tie-ing to DB file R/O /opt/MailScanner/etc/bayes/bayes_toks
debug: bayes: 28821 tie-ing to DB file R/O /opt/MailScanner/etc/bayes/bayes_seen
debug: bayes: found bayes db version 2
debug: Score set 3 chosen.


Start MailScanner up again

# /opt/MailScanner/bin/check_mailscanner && tail -f /var/log/maillog


You should see something like:

Jun 13 12:18:23 hoshi MailScanner[26388]: MailScanner E-Mail Virus Scanner version 4.20-3 starting...
Jun 13 12:18:24 hoshi MailScanner[26388]: Config: calling custom init function MailWatchLogging
Jun 13 12:18:24 hoshi MailScanner[26388]: Initialising database connection
Jun 13 12:18:24 hoshi MailScanner[26388]: Finished initialising database connection

Congratulations - you now have MailScanner logging to MySQL!

Changes to be made to /var/www/htdocs/mailscanner/conf.php
Be sure that your DB_USER and DB_PASS options match those for which you created earlier:

// Database settings
define(DB_TYPE, 'mysql');
define(DB_USER, 'mailwatch');
define(DB_PASS, 'postfix');
define(DB_HOST, 'localhost');
define(DB_NAME, 'mailscanner');
define(DB_DSN, DB_TYPE.'://'.DB_USER.":".DB_PASS."@".DB_HOST."/".DB_NAME);


Change paths in /var/www/htdocs/mailscanner/conf.php
These tell MailWatch where it needs to redirect and look for config information:

define(MAILWATCH_HOME, '/var/www/htdocs/mailscanner');
define(MS_CONFIG_DIR, '/opt/MailScanner/etc/');
define(MS_LIB_DIR, '/opt/MailScanner/lib/');


Test the MailWatch interface
Point your browser to http:///mailscanner/
You should be prompted for a username and password - enter the details of the MailWatch web user that you created earlier, and you should see a list of the last 50 messages processed by MailScanner.

Update the SpamAssassin Rules table
MailWatch keeps a list of all the SpamAssassin rules and descriptions which are displayed on the 'Message Detail' page - to show the descriptions, you need to run the updater every time you add new rules or upgrade SpamAssassin.
Click on the 'Other' menu and select 'Update SpamAssassin Rule Descriptions' and click 'Run Now'.

Update the GeoIP database
Click on the 'Other' menu and select 'Update GeoIP database' and click 'Run Now'.

That's it! MailWatch should be working as expected!


Install sqlgreywebinterface

This can be obtained from SGWI website.

Extract the source
Once you have the source, we need to extract it:

tar xf sqlgreywebinterface-0.7.tgz


Move into the sqlgreywebinterface source directory

cd sqlgreywebinterface-0.7


Edit config.inc.php
We need to make changes to match the sqlgrey installation:

$db_db   = "sqlgrey";
$db_hostname = "localhost";
$db_user = "postfix";
$db_pass = "postfix";
$db_type = "mysql"; # mysql or pg (pg=postgress)

Note: You should pay special attention to db_db, db_user, and db_pass entries

Save it, then we move it

cp -rf sqlgreywebinterface-0.7 /var/www/htdocs/sqlgrey

I like to keep a copy of the source where I can get to easily, hence the copy instead of a move.

Move into the sqlgrey web interface directory

cd /var/www/htdocs/sqlgrey


Create .htaccess file for authentication
Create a new file called .htaccess and add the below:

AuthUserFile /var/www/htdocs/sqlgrey/.htpasswd
AuthGroupFile /dev/null
AuthName "SQLgrey Admin"
AuthType Basic

require valid-user



Now we create the .htpasswd file

htpasswd -c .htpasswd admin

When prompted enter your desired password. You can even change the username to use to suit your needs.

Change permissions on the .htaccess file

chmod 644 .htaccess


Test the SQLgrey web interface installation
Just login to http:///sqlgrey and enter the username/password you created above.
That's it! You now have a fully functional greylisting/spam eating/virus finding/whatever email server.


Tweaks

These are just things I've found that really help the process. Solves a bit of those "well how do I do that?" without you having to go and find the solution like I did. Yes, some of them are well documented, some of them are not. Who cares right? Hehe.

/opt/MailScanner/etc/virus.scanners.conf
Edit this file and change the line for clamav to reflect the proper "base" directory:

clamav          /opt/MailScanner/lib/clamav-wrapper     /usr

MailScanner may pick up your scanner automagically, but its still safe to do this.


/opt/MailScanner/lib/clamav-autoupdate
Need to change just a few things in here:
Change:

$PackageDir = shift || "/usr/local";

To:

$PackageDir = shift || "/usr";


Change:

$LogFile = "/tmp/ClamAV.update.log";

To:

$LogFile = "/var/log/clamav/clam-update.log";



Daily Scripts

All of these scripts should be placed in /etc/cron.daily

clean.SA.cache.cron
This script will help clean out the Spamassassin cache:

cp /opt/MailScanner/bin/cron/clean.SA.cache.cron /etc/cron.daily


clean.quarantine.cron
Yes, this script cleans out MailScanner's quarantine. You can set the amount of days to keep by the $days_to_keep variable in the script:

cp /opt/MailScanner/bin/cron/clean.quarantine.cron /etc/cron.daily


qr_report.php

This script will send a daily quarantine report every day to each user who requests it:
Grab it from qr_report.phps and then put it in /etc/cron.daily


update_phishing_sites.cron
This updates phishing sites (sites known to do "phishing", who'da thunk?):

cp /opt/MailScanner/bin/cron/update_phishing_sites.cron /etc/cron.daily



Hourly Scripts

These scripts should be placed in /etc/cron.hourly

check_MailScanner.cron
This script checks to be sure that MailScanner is running. If it is not, it starts it:

cp /opt/MailScanner/bin/cron/check_MailScanner.cron /etc/cron.hourly


update_virus_scanners.cron
This script updates the virus scanners (if you couldn't figure that one out already):

cp /opt/MailScanner/bin/cron/update_virus_scanners.cron /etc/cron.hourly

Additions

MailScanner
As of version 4.59.4, if the installation script detects /dev/shm on your system it will want to use this for spamassassin. I have this device available, however, I didn't have it mounted. So, to get this accomplished you edit /etc/fstab and add:

shm              /dev/shm         tmpfs       defaults         0   0

Then:

mount /dev/shm

and that's it. MailScanner will now do spamassassin scans within the tmpfs partition you just mounted. This helps to speed up the scans quite a bit. Mileage will vary depending on your system.


Clamd
With releases of MailScanner since 4.59.4, you now have the ability to use clamd. You just have to set your virus scanners setting in MailScanner.conf to use clamd. You will then want to read up on how to use clamd. This tutorial does not cover that.
Share this post :

Post a Comment

 
Copyright © 2011. COMASTNET - All Rights Reserved