Freatures:

  • Postfix (SMTP)
  • SASL smtp
  • secure with TLS
  • Dovecot for imap and pop3
  • imaps and pops
  • filtering of spam to a spam folder
  • mysql based domain and users
  • PostfixAdmin for the mail server administration
  • roundcube as webamil
  • amavisd-new, spamassassin and clamav

OS: CentOS 6.3

Yum repository installation:

The following remi and epel repos have been enabled:

wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-7.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
sudo rpm -Uvh remi-release-6*.rpm epel-release-6*.rpm.

Installation of all the required packages:

yum install roundcubemail dovecot dovecot-mysql dovecot-pigeonhole cyrus-sasl-devel cyrus-sasl-sql subversion perl-MailTools perl-MIME-EncWords perl-MIME-Charset perl-Email-Valid perl-Test-Pod perl-TimeDate perl-Mail-Sender perl-Log-Log4perl imapsync offlineimap amavisd-new clamav clamd razor-agents perl-Convert-BinHex

Setting up User, directories and permissions

mkdir /home/vmail
chmod 770 /home/vmail
useradd -r -u 101 -g mail -d /home/vmail -s /sbin/nologin -c “Virtual mailbox” vmail
chown vmail:mail /home/vmail

Postfix admin setup

Download and move

wget http://sourceforge.net/projects/postfixadmin/files/latest/download
tar zxf postfixadmin-2.3.5.tar.gz
mv postfixadmin-2.3.5 postfixadmin
mv postfixadmin/ /usr/share/

Apache setup for postfixadmin

/etc/httpd/conf.d/postfixadmin.conf

alias /mailadmin /usr/share/postfixadmin
<Directory “/usr/share/postfixadmin”>
AllowOverride AuthConfig
</Directory>

Create Database

mysql -u admin -p -e “CREATE DATABASE postfix;”

http://IP/mailadmin/setup.php

Changes required in the config file

$CONF[‘database_type’] = ‘mysql’;
$CONF[‘database_host’] = ‘localhost’;
$CONF[‘database_user’] = ‘DB_User’;
$CONF[‘database_password’] = ‘DB_Passowrd’;
$CONF[‘database_name’] = ‘postfix’;

Enter the setup password as soon as the setup is complete in the following parameter:

$CONF[‘setup_password’] =”

POSTFIX SETUP

Following are the file for the setup:

/etc/postfix/main.cf
/etc/postfix/master.cf
/etc/postfix/mynetworks
/etc/postfix/mysql-virtual_alias_maps.cf
/etc/postfix/mysql-virtual_domains_maps.cf
/etc/postfix/mysql-relay_domains_maps.cf
/etc/postfix/mysql-virtual_mailbox_maps.cf
/etc/postfix/mysql-virtual_mailbox_limit_maps.cf
touch /etc/postfix/virtual_regexp

The main configration file: (change the bold text according to your requirement)

# postfix config file

# uncomment for debugging if needed
#soft_bounce=yes

# postfix main
mail_owner = postfix
setgid_group = postdrop
delay_warning_time = 4

# postfix paths
html_directory = no
command_directory = /usr/sbin
daemon_directory = /usr/libexec/postfix
queue_directory = /var/spool/postfix
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.2.2/samples
readme_directory = /usr/share/doc/postfix-2.2.2/README_FILES

# network settings
inet_interfaces = all
mydomain = noc.com
myhostname = mail.noc.com
mynetworks = $config_directory/mynetworks
mydestination = $myhostname, localhost.$mydomain, localhost
relay_domains = proxy:mysql:/etc/postfix/mysql-relay_domains_maps.cf

# mail delivery
recipient_delimiter = +

# mappings
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
transport_maps = hash:/etc/postfix/transport
#local_recipient_maps =

# virtual setup
virtual_alias_maps = proxy:mysql:/etc/postfix/mysql-virtual_alias_maps.cf,
regexp:/etc/postfix/virtual_regexp
virtual_mailbox_base = /home/vmail
virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql-virtual_domains_maps.cf
virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailbox_maps.cf
virtual_mailbox_limit_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailbox_limit_maps.cf
virtual_minimum_uid = 101
virtual_uid_maps = static:101
virtual_gid_maps = static:12
virtual_transport = dovecot
dovecot_destination_recipient_limit = 1

# debugging
debug_peer_level = 2
debugger_command =
PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
xxgdb $daemon_directory/$process_name $process_id & sleep 5

# authentication
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $myhostname
broken_sasl_auth_clients = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth

# tls config
smtp_use_tls = yes
smtpd_use_tls = yes
smtp_tls_note_starttls_offer = yes
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
smtp_tls_session_cache_database = btree:$data_directory/smtp_tls_session_cache
# Change mail.example.com.* to your host name
smtpd_tls_key_file = /etc/pki/tls/private/server.key
smtpd_tls_cert_file = /etc/pki/tls/private/server.crt
# smtpd_tls_CAfile = /etc/pki/tls/root.crt

# rules restrictions
smtpd_client_restrictions =
smtpd_helo_restrictions =
smtpd_sender_restrictions =
smtpd_recipient_restrictions = permit_sasl_authenticated,
permit_mynetworks,
reject_unauth_destination,
reject_non_fqdn_sender,
reject_non_fqdn_recipient,
reject_unknown_recipient_domain
# uncomment for realtime black list checks
#    ,reject_rbl_client zen.spamhaus.org
#    ,reject_rbl_client bl.spamcop.net
#    ,reject_rbl_client dnsbl.sorbs.net

smtpd_helo_required = yes
unknown_local_recipient_reject_code = 550
disable_vrfy_command = yes
smtpd_data_restrictions = reject_unauth_pipelining

Setup The Certificate for the secure mail communication

cd /etc/pki/tls/private/

openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

The MASTER.CF File

#
# Postfix master process configuration file.  For details on the format
# of the file, see the Postfix master(5) manual page.
#
# ***** Unused items removed *****
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       –       n       –       –       smtpd
  -o content_filter=smtp-amavis:127.0.0.1:10024 (comment bold text if you are not using amavis/spam filertin)
  -o receive_override_options=no_address_mappings
pickup    fifo  n       –       n       60      1       pickup
-o content_filter=
-o receive_override_options=no_header_body_checks
cleanup   unix  n       –       n       –       0       cleanup
qmgr      fifo  n       –       n       300     1       qmgr
#qmgr     fifo  n       –       n       300     1       oqmgr
tlsmgr    unix  –       –       n       1000?   1       tlsmgr
rewrite   unix  –       –       n       –       –       trivial-rewrite
bounce    unix  –       –       n       –       0       bounce
defer     unix  –       –       n       –       0       bounce
trace     unix  –       –       n       –       0       bounce
verify    unix  –       –       n       –       1       verify
flush     unix  n       –       n       1000?   0       flush
proxymap  unix  –       –       n       –       –       proxymap
smtp      unix  –       –       n       –       –       smtp
# When relaying mail as backup MX, disable fallback_relay to avoid MX loops
relay     unix  –       –       n       –       –       smtp
-o fallback_relay=
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       –       n       –       –       showq
error     unix  –       –       n       –       –       error
discard   unix  –       –       n       –       –       discard
local     unix  –       n       n       –       –       local
virtual   unix  –       n       n       –       –       virtual
lmtp      unix  –       –       n       –       –       lmtp
anvil     unix  –       –       n       –       1       anvil
scache    unix  –       –       n       –       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
# ====================================================================
maildrop  unix  –       n       n       –       –       pipe
flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}
uucp      unix  –       n       n       –       –       pipe
flags=Fqhu user=uucp argv=uux -r -n -z -a$sender – $nexthop!rmail ($recipient)
ifmail    unix  –       n       n       –       –       pipe
flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  –       n       n       –       –       pipe
flags=Fq. user=foo argv=/usr/local/sbin/bsmtp -f $sender $nexthop $recipient
#
# spam/virus section
#
smtp-amavis  unix  –    –       y       –       2       smtp
-o smtp_data_done_timeout=1200
-o disable_dns_lookups=yes
-o smtp_send_xforward_command=yes
127.0.0.1:10025 inet n  –       y       –       –       smtpd
-o content_filter=
-o smtpd_helo_restrictions=
-o smtpd_sender_restrictions=
-o smtpd_recipient_restrictions=permit_mynetworks,reject
-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 receive_override_options=no_header_body_checks
-o smtpd_bind_address=127.0.0.1
-o smtpd_helo_required=no
-o smtpd_client_restrictions=
-o smtpd_restriction_classes=
-o disable_vrfy_command=no
-o strict_rfc821_envelopes=yes
#
# Dovecot LDA
dovecot   unix  –       n       n       –       –       pipe
flags=DRhu user=vmail:mail argv=/usr/libexec/dovecot/deliver -d ${recipient}
#
# Vacation mail
vacation    unix  –       n       n       –       –       pipe
flags=Rq user=vacation argv=/var/spool/vacation/vacation.pl -f ${sender} — ${recipient}

Define the Allowed networks(Change the networks required)

/etc/postfix/mynetworks

# This specifies the list of subnets that Postfix considers as
# “trusted” SMTP clients that have more privileges than “strangers”.
#
# In particular, “trusted” SMTP clients are allowed to relay mail
# through Postfix.
#
# Be sure to add your public ip address block if needed.
#
192.168.0.0/16
10.0.0.0/8
127.0.0.0/8

Add the following file for the postfix mysql proxy maps(Change user,password,dbname)

/etc/postfix/mysql-virtual_alias_maps.cf

hosts = localhost
user = root
password = hahaha
dbname = postfix
query = SELECT goto FROM alias WHERE address=’%s’ AND active = ‘1’

/etc/postfix/mysql-virtual_domains_maps.cf

hosts = localhost
user = root
password = hahaha
dbname = postfix
query = SELECT domain FROM domain WHERE domain=’%s’ AND backupmx = ‘0’ AND active = ‘1’

/etc/postfix/mysql-relay_domains_maps.cf

hosts = localhost
user = root
password = hahaha
dbname = postfix
query = SELECT domain FROM domain WHERE domain=’%s’ and backupmx = ‘1’

/etc/postfix/mysql-virtual_mailbox_maps.cf

hosts = localhost
user = root
password = hahaha
dbname = postfix
query = SELECT maildir FROM mailbox WHERE username=’%s’ AND active = ‘1’

/etc/postfix/mysql-virtual_mailbox_limit_maps.cf

hosts = localhost
user = root
password = hahaha
dbname = postfix
query = SELECT quota FROM mailbox WHERE username=’%s’ AND active = ‘1’

create the regular exp file and postmap the transport

touch /etc/postfix/virtual_regexp
postmap /etc/postfix/transport

Dovecot Configuration(POP/IMAP)

Importnat files

/etc/dovecot/dovecot.conf
/etc/dovecot/dovecot-dict-quota.conf
/etc/dovecot/dovecot-mysql.conf
/etc/dovecot/trash.conf

The configuration for imap to work with the mysql, imap, pop, pops, imaps, TLS

/etc/dovecot/dovecot.conf

##
## Dovecot config file
##

protocols = imap pop3 lmtp sieve
auth_mechanisms = plain login
passdb {
driver = sql
args = /etc/dovecot/dovecot-mysql.conf
}
userdb {
driver = prefetch
}
userdb {
driver = sql
args = /etc/dovecot/dovecot-mysql.conf
}
mail_location = maildir:/home/vmail/%d/%n
first_valid_uid = 101
#last_valid_uid = 0
first_valid_gid = 12
#last_valid_gid = 0
#mail_plugins =
mailbox_idle_check_interval = 30 secs
maildir_copy_with_hardlinks = yes
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 {
#mode = 0666
}
}
service imap {
vsz_limit = 256M
}
service pop3 {
}
service auth {
unix_listener auth-userdb {
mode = 0666
user = vmail
group = mail
}

# Postfix smtp-auth
unix_listener /var/spool/postfix/private/auth {
mode = 0666
user = postfix
group = postfix
}
}
service auth-worker {
}
service dict {
unix_listener dict {
mode = 0666
user = vmail
group = mail
}
}
service managesieve-login {
inet_listener sieve {
port = 4190
}
service_count = 1
process_min_avail = 0
vsz_limit = 64M
}
service managesieve {
}
ssl = yes
ssl_cert = /etc/pki/tls/private/server.crt
ssl_key = /etc/pki/tls/private/server.key
ssl_verify_client_cert = no
#ssl_ca =
lda_mailbox_autocreate = yes
lda_mailbox_autosubscribe = yes
protocol lda {
mail_plugins = quota sieve
postmaster_address = postmaster@your-domain.tld
}
protocol imap {
mail_plugins = quota imap_quota trash
imap_client_workarounds = delay-newmail
}
lmtp_save_to_detail_mailbox = yes
protocol lmtp {
mail_plugins = sieve
}
protocol pop3 {
mail_plugins = quota
pop3_client_workarounds = outlook-no-nuls oe-ns-eoh
}
protocol sieve {
managesieve_max_line_length = 65536
managesieve_implementation_string = Dovecot Pigeonhole
managesieve_max_compile_errors = 5
}
dict {
quotadict = mysql:/etc/dovecot/dovecot-dict-quota.conf
}
plugin {
quota = dict:user::proxy::quotadict
acl = vfile:/etc/dovecot/acls
trash = /etc/dovecot/trash.conf
sieve_global_path = /home/sieve/globalfilter.sieve
sieve = ~/dovecot.sieve
sieve_dir = ~/sieve
sieve_global_dir = /home/sieve/
#sieve_extensions = +notify +imapflags
sieve_max_script_size = 1M
#sieve_max_actions = 32
#sieve_max_redirects = 4
}

Trash folder config dovecot

/etc/dovecot/trash.conf

1 Spam
# Uncomment if you want trash as well
# 2 Trash

Create a file for mysql and dovecot connection

/etc/dovecot/dovecot-mysql.conf

driver = mysql
connect = host=localhost dbname=postfix user=admin password=hahaha
default_pass_scheme = MD5-CRYPT

# following should all be on one line.
password_query = SELECT username as user, password, concat(‘/home/vmail/’, maildir) as userdb_home,concat(‘maildir:/home/vmail/’, maildir) as userdb_mail, 101 as userdb_uid, 12 as userdb_gid FROM mailbox WHERE username = ‘%u’ AND active = ‘1’

# following should all be on one line
user_query = SELECT concat(‘/home/vmail/’, maildir) as home, concat(‘maildir:/home/vmail/’, maildir) as mail, 101 AS uid, 12 AS gid, CONCAT(‘*:messages=10000:bytes=’, quota) as quota_rule FROM mailbox WHERE username = ‘%u’ AND active = ‘1’

Quota setup for dovecot

/etc/dovecot/dovecot-dict-quota.conf

connect = host=localhost dbname=postfix user=admin password=hahaha
map {
pattern = priv/quota/storage
table = quota2
username_field = username
value_field = bytes
}
map {
pattern = priv/quota/messages
table = quota2
username_field = username
value_field = messages
}

Now Create the sieve filter for SPAM filtering.

mkdir /home/sieve
vi /home/sieve/globalfilter.sieve
chown -R vmail:mail /home/sieve

require “fileinto”;
if exists “X-Spam-Flag” {
if header :contains “X-Spam-Flag” “NO” {
} else {
fileinto “Spam”;
stop;
}
}
if header :contains “subject” [“***SPAM***”] {
fileinto “Spam”;
stop;
}

ROUNDCUBE

vi /etc/httpd/conf.d/roundcubemail.conf

Alias /roundcubemail /usr/share/roundcubemail
Alias /webmail /usr/share/roundcubemail

<Directory /usr/share/roundcubemail/>
Order Deny,Allow
Allow from all
</Directory>

Setup Database

mysql -u root -p -e “CREATE DATABASE roundcubemail;”

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

/etc/roundcubemail/db.inc.php

$rcmail_config[‘db_dsnw’] = ‘mysql://username:password@localhost/roundcubemail’;

/etc/roundcubemail/main.inc.ph

$rcmail_config[‘default_host’] = ‘localhost’;
$rcmail_config[‘smtp_server’] = ‘localhost’;
$rcmail_config[‘plugins’] = array(‘managesieve’);
$rcmail_config[‘quota_zero_as_unlimited’] = true;+

vi /usr/share/roundcubemail/plugins/managesieve/config.inc.php

$rcmail_config[‘managesieve_port’] = 4190;

http://IP/roundcubemail

AMAVISD-NEW SPAMASSASSIN CLAMAV

vi /etc/clamd.conf

LogFile /var/log/clamav/clamd.log
#LogFileUnlock yes
LogFileMaxSize 20M
LogTime yes
#LogClean yes
LogSyslog yes
#LogFacility LOG_MAIL
#LogVerbose yes
#ExtendedDetectionInfo yes
PidFile /var/spool/amavisd/clamd.sock
TemporaryDirectory /var/tmp
DatabaseDirectory /var/lib/clamav
#OfficialDatabaseOnly no
LocalSocket /var/run/clamav/clamd.sock
#LocalSocketGroup virusgroup
#LocalSocketMode 660
FixStaleSocket yes
TCPSocket 3310
TCPAddr 127.0.0.1
MaxConnectionQueueLength 30
#StreamMaxLength 10M

# Limit port range.
# Default: 1024
#StreamMinPort 30000
# Default: 2048
#StreamMaxPort 32000

MaxThreads 50
ReadTimeout 300
#CommandReadTimeout 5
#SendBufTimeout 200
#MaxQueue 200
#IdleTimeout 60
#ExcludePath ^/proc/
#ExcludePath ^/sys/
#MaxDirectoryRecursion 20
#FollowDirectorySymlinks yes
#FollowFileSymlinks yes
#CrossFilesystems yes
#SelfCheck 600
#VirusEvent /usr/local/bin/send_sms 123456789 “VIRUS ALERT: %v”

User clam
AllowSupplementaryGroups yes
#ExitOnOOM yes
#Foreground yes
#Debug yes
#LeaveTemporaryFiles yes
#DetectPUA yes
#ExcludePUA NetTool
#ExcludePUA PWTool
#IncludePUA Spy
#IncludePUA Scanner
#IncludePUA RAT
#AlgorithmicDetection yes

ScanPE yes
ScanELF yes
DetectBrokenExecutables yes

ScanOLE2 yes
#OLE2BlockMacros no
#ScanPDF yes

ScanMail yes

#ScanPartialMessages yes
PhishingSignatures yes
PhishingScanURLs yes
#PhishingAlwaysBlockSSLMismatch no

#PhishingAlwaysBlockCloak no
#HeuristicScanPrecedence yes

#StructuredDataDetection yes
#StructuredMinCreditCardCount 5
#StructuredMinSSNCount 5
#StructuredSSNFormatNormal yes
#StructuredSSNFormatStripped yes

#ScanHTML yes
ScanArchive yes
ArchiveBlockEncrypted no

#MaxScanSize 150M
#MaxFileSize 30M
#MaxRecursion 10
#MaxFiles 15000

#ClamukoScanOnAccess yes
#ClamukoScannerCount 3
#ClamukoMaxFileSize 10M
#ClamukoScanOnOpen yes
#ClamukoScanOnClose yes
#ClamukoScanOnExec yes
#ClamukoIncludePath /home
#ClamukoIncludePath /students
#ClamukoExcludePath /home/bofh
#ClamukoExcludeUID 0
#Bytecode yes
#BytecodeSecurity TrustSigned
# BytecodeTimeout 1000

Configure Razor. Type the following:

razor-admin -register -user=some_user -pass=somepas

Update and restart clamav:
freshclam
service clamd restart

Configuring Amavisd-new

vi /etc/amavisd.conf
Here is a list of items you should change. just scroll through the file to find each item.

$mydomain = ‘example.com’; # set to your domain name
$log_level = 1; # set the log leve to one
$sa_tag_level_deflt = -99; # i want to see the headers so change to -99
$sa_tag2_level_deflt = 5.0; # start with 5
$sa_kill_level_deflt = 9; # change to 9
$sa_dsn_cutoff_level = 9; # change to 9
$sa_quarantine_cutoff_level = 50; # remove the starting # and change to 50
$myhostname = ‘lightning.campworld.net’; # remove the starting # and enter your host name
$notify_method = ‘smtp:[127.0.0.1]:10025’; # uncomment the line
$forward_method = ‘smtp:[127.0.0.1]:10025’; # uncomment the line
$final_banned_destiny = D_DISCARD; # change to D_DISCARD

Now enable clamav:
Change the following:

# ### http://www.clamav.net/
# [‘ClamAV-clamd’,
#   \&ask_daemon, [“CONTSCAN {}\n”, “/var/run/clamav/clamd”],
#   qr/\bOK$/m, qr/\bFOUND$/m,
#   qr/^.*?: (?!Infected Archive)(.*) FOUND$/m ],

to

### http://www.clamav.net/
[‘ClamAV-clamd’,
\&ask_daemon, [“CONTSCAN {}\n”, “/var/run/clamav/clamd”],
qr/\bOK$/m, qr/\bFOUND$/m,
qr/^.*?: (?!Infected Archive)(.*) FOUND$/m ],

Now update spamassassin and start amavisd-new.

sa-update
service amavisd-new start

Be sure to set amavisd-new to start at boot.
Telling Postfix to Start Filtering SPAM

To get postfix going we need to un-comment a couple lines in /etc/postfix/master.cf
Find:

smtp      inet  n       –       n       –       –       smtpd
#  -o content_filter=smtp-amavis:127.0.0.1:10024
#  -o receive_override_options=no_address_mappings

Change to:

smtp      inet  n       –       n       –       –       smtpd
-o content_filter=smtp-amavis:127.0.0.1:10024
-o receive_override_options=no_address_mappings

Restart services and start at bootup. you’re done.

service dovecot restart
service postfix restart
service mysql restart
service clamd.amavisd restart
service clamd restart
service amavisd restart
chkconfig <services> on

Hostfile Setup

vi /etc/hosts (mail server)  (replace 192.168.1.140 with your mail server IP)

192.168.1.140 mail.noc.com

vi /etc/hosts (MyLocalComputer) (replace 192.168.1.140 with your mail server IP)

192.168.1.140 noc.com
192.168.1.140 mail.noc.com
192.168.1.140 smtp.noc.com
192.168.1.140 imap.noc.com

Check the logs

tail -f /var/log/maillog

Comment or write me: farhanumar@gmail.com

Advertisements