Usando Linux para muchas cosas y disfrutando de videojuegos, en dispositivos moviles, consolas y pc. Using Linux for many things and enjoying video games, mobile devices, consoles and pc

Mostrando entradas con la etiqueta mailwatch. Mostrar todas las entradas
Mostrando entradas con la etiqueta mailwatch. Mostrar todas las entradas

Email server, ver 2.0

En estos días requiero de un par de nuevos servidores de email para colocarlos en cluster pasivo-activo, por ello recupero mi anterior articulo y hoy haré una versión 2 actualizada y con la db en cluster.
Para esto utilizaremos Centos 5.4 actualizado y todos los comandos se realizaran desde la cuenta root. En mi caso utilizare servidores virtuales Openvz con Centos 5.4

MTA postfix
PostfixAdmin 2.3
MailScanner 4.80.1-1
MailWatch 1.0.5
Antivirus clamav 0.95
spamassassin 3.3.0
MySQL 5.0 Cluster

email server: 192.168.0.18
MySQL Cluster SQL: 192.168.0.22

-Instalamos webmin

cd /root
wget -c http://downloads.sourceforge.net/project/webadmin/webmin/1.510/webmin-1.510-1.noarch.rpm


rpm -vi webmin-1.510-1.noarch.rpm

-Instalamos herramientas para modificar y actualizar su zona horaria y fecha

yum install system-config-date mingetty ethtool
-Verificamos que el firewall este deshabilitado por el momento

iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

-Deshabilitamos SELinux

vi /etc/selinux/config

SELINUX=disabled

-Salvamos los cambios y salimos. Instalamos software que nos hará falta mas tarde

yum install fetchmail wget bzip2 unzip zip nmap openssl lynx fileutils gcc gcc-c++ bind-utils

-Descargamos e instalamos ncftp

wget -c ftp://ftp.pbone.net/mirror/centos.karan.org/el5/extras/testing/i386/RPMS/ncftp-3.2.1-1.el5.kb.i386.rpm

rpm -vi ncftp-3.2.1-1.el5.kb.i386.rpm

-Mas software necesitado

yum install rpm-build pcre-devel

-Instalamos Cyrus para la encriptacion en la autenticacion

yum install cyrus-sasl-sql cyrus-sasl-devel

-Eliminamos un paquete de Cyrus que no necesitaremos

yum remove cyrus-sasl-gssapi

-Agregamos el repositorio dag para contar con paquetes que no están en los de centos. Desabilitado para que no se actualice algo que no queremos

vi /etc/yum.repos.d/dag.repo

[dag]
name=Dag RPM Repository for Red Hat Enterprise Linux
baseurl=http://apt.sw.be/redhat/el$releasever/en/$basearch/dag
gpgcheck=1
enabled=0

-Descargamos postfix con soporte para mysql. Podemos buscar la ultima versión en http://rpm.pbone.net/ y descargar la versión dependiendo de nuestra versión de centos

wget -c ftp://mirror.switch.ch/pool/3/mirror/centos/5.4/centosplus/i386/RPMS/postfix-2.3.3-2.el5.centos.mysql_pgsql.i386.rpm


-Instalamos postgresql debido a dependencia con el rpm de postfix

yum install postgresql
rpm -vi postfix-2.3.3-2.el5.centos.mysql_pgsql.i386.rpm

-Instalamos libtool por dependencia con courier

yum install libtool-ltdl-devel

-Creamos un usuario y grupo bajo el cual ejecutara Courier

groupadd vmail -g 1001
useradd vmail -u 1001 -g 1001

-Agregamos este usuario al file sudoers. Entre columnas damos un TAB

visudo
vmail     ALL=(ALL)       NOPASSWD: ALL


apache  ALL=(ALL)       NOPASSWD: ALL


-Comentamos la siguiente linea

Defaults requiretty

-Agregamos apache al grupo vmail

usermod -G vmail apache

-Le colocamos password a la cuenta vmail

passwd vmail

-Cambiamos a esta cuenta para instalar unos paquetes desde ella. El password que nos pide es el de la cuenta vmail, al tratar de instalar con el sudo

su vmail
sudo yum install libtool postgresql-devel gdbm-devel pam-devel expect openldap-devel redhat-rpm-config libidn-devel

-Creamos un árbol de directorios para compilar algunos rpm que necesitaremos

mkdir $HOME/rpm
mkdir $HOME/rpm/SOURCES
mkdir $HOME/rpm/SPECS
mkdir $HOME/rpm/BUILD
mkdir $HOME/rpm/SRPMS
mkdir $HOME/rpm/RPMS
mkdir $HOME/rpm/RPMS/i386
echo "%_topdir $HOME/rpm" >> $HOME/.rpmmacros

-Creamos un directorio para las descargas

mkdir $HOME/downloads; cd $HOME/downloads

-Descargamos los paquetes de Courier

wget -c http://downloads.sourceforge.net/project/courier/authlib/0.63.0/courier-authlib-0.63.0.tar.bz2
wget -c http://downloads.sourceforge.net/project/courier/imap/4.7.0/courier-imap-4.7.0.tar.bz2
wget -c http://downloads.sourceforge.net/project/courier/maildrop/2.4.3/maildrop-2.4.3.tar.bz2

-Courier nos permite validar conexiones por postgresql, mysql, LDAP, etc antes que solo /etc/passwd. Pasamos a compilarlo

sudo rpmbuild -ta courier-authlib-0.63.0.tar.bz2

-Instalamos los siguientes rpm generados

cd $HOME/rpm/RPMS/i386/
sudo rpm --install courier-authlib-0.63.0-1.i386.rpm
sudo rpm --install courier-authlib-devel-0.63.0-1.i386.rpm
sudo rpm --install courier-authlib-mysql-0.63.0-1.i386.rpm


-Colocamos acceso total a los directorios bajo rpm para compilar courier-imap server

sudo chmod -R 777 $HOME/rpm/RPMS/
cd $HOME/downloads
rpmbuild -ta courier-imap-4.7.0.tar.bz2
cd $HOME/rpm/RPMS/i386/
sudo rpm --install courier-imap-4.7.0-1.i386.rpm

-Compilamos maildrop que nos permitirá filtrar mails entrantes y salientes a los directorios correctos

cd $HOME/downloads
sudo rpmbuild -ta maildrop-2.4.3.tar.bz2
cd $HOME/rpm/RPMS/i386
sudo rpm --install maildrop-2.4.3-1.i386.rpm

-Salimos de la cuenta vmail a root y verificamos que seamos root

exit
whoami
root

-Creamos el file para logs de maildrop

touch /var/log/maildroprc.log
chmod 777 /var/log/maildroprc.log

-Generamos los certificados usados por Postfix (para SMTPS y TLS), Courier (para IMAPS y POP3S) y Apache (para HTTPS)

mkdir /usr/local/ssl; cd /usr/local/ssl

-La llave sera sin password evitando que cuando iniciemos postfix, courier o apache pida el password

openssl genrsa -out mail.yourdomain.com.key 1024
Generating RSA private key, 1024 bit long modulus
......++++++
...................................................++++++
e is 65537 (0x10001)

chmod 600 mail.yourdomain.com.key

-Generamos la solicitud de certificado

openssl req -new -key mail.yourdomain.com.key -out mail.yourdomain.com.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [GB]:CO
State or Province Name (full name) [Berkshire]:Cundinamarca
Locality Name (eg, city) [Newbury]:Bogota
Organization Name (eg, company) [My Company Ltd]:Cabrera ltda
Organizational Unit Name (eg, section) []:Soporte Sistemas
Common Name (eg, your name or your server's hostname) []:mail.yourdomain.com
Email Address []:postmaster@yourdomain.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:password
An optional company name []:

-El fichero generado es el necesario para que nos creen un certificado real las Certificate Authority como Verisign o Thawte, en nuestro caso, lo firmaremos nosotros mismos

openssl genrsa -des3 -out ca.key 1024
Generating RSA private key, 1024 bit long modulus
........................................................++++++
...............++++++
e is 65537 (0x10001)
Enter pass phrase for ca.key:
Verifying - Enter pass phrase for ca.key:

-Restringimos sus permisos

chmod 600 ca.key

-Generamos un certificado auto firmado

openssl req -new -x509 -days 365 -key ca.key -out ca.crt
Enter pass phrase for ca.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [GB]:CO
State or Province Name (full name) [Berkshire]:Cundinamarca
Locality Name (eg, city) [Newbury]:Bogota
Organization Name (eg, company) [My Company Ltd]:Cabrera ltda
Organizational Unit Name (eg, section) []:Sistemas Soporte
Common Name (eg, your name or your server's hostname) []:mail.yourdomain.com
Email Address []:postmaster@yourdomain.com

-Usamos este CA certificado para firmar nuestro certificado

openssl x509 -req -days 365 -CA ca.crt -CAkey ca.key -set_serial 01 -in mail.yourdomain.com.csr -out mail.yourdomain.com.crt
Signature ok
subject=/C=CO/ST=Bogota/L=Cundinamarca/O=Cabrera ltda/OU=Sistemas Soporte/CN=mail.yourdomain.com/emailAddress=postmaster@yourdomain.com
Getting CA Private Key
Enter pass phrase for ca.key:

-Combinamos el server key y el certificado en un unico fichero. Postfix y Apache pueden manejar 2 ficheros pero Courier necesita solo uno. Asi que crearemos un fichero unico para todo. Crearemos el pem en el formato esperado por Courier (key y cert en un unico fichero)

cat mail.yourdomain.com.key mail.yourdomain.com.crt > mail.yourdomain.com.pem
chmod 600 mail.yourdomain.com.pem

-Si todo va bien, debe tener algo parecido

ls -la
total 32
drwxr-xr-x  2 root root 4096 Apr 15 15:46 .
drwxr-xr-x 12 root root 4096 Apr 15 14:43 ..
-rw-r--r--  1 root root 1415 Apr 15 15:35 ca.crt
-rw-------  1 root root  963 Apr 15 15:27 ca.key
-rw-r--r--  1 root root 1021 Apr 15 15:42 mail.yourdomain.com.crt
-rw-r--r--  1 root root  777 Apr 15 15:40 mail.yourdomain.com.csr
-rw-------  1 root root  887 Apr 15 15:01 mail.yourdomain.com.key
-rw-------  1 root root 1908 Apr 15 15:46 mail.yourdomain.com.pem

-Instalamos y configuramos postfixadmin

cd /var/www/html
yum install subversion
svn co https://postfixadmin.svn.sourceforge.net/svnroot/postfixadmin/trunk postfixadmin
cd postfixadmin
chmod 640 *.php
cd admin
chmod 640 *.php
cd ../images/
chmod 640 *.png
chmod 640 calendar/*.png
chmod 640 calendar/*.gif
cd ../languages/
chmod 640 *.lang
cd ../templates/
chmod 640 *.php
chmod 640 *.tpl
chmod 640 *.txt
cd ../users/
chmod 640 *.php
chmod 640 images/calendar/*.gif
chmod 640 images/calendar/*.png
cd ..

-Creamos la db en el Cluster MySQL segun el INSTALL.TXT. En el server SQL

mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.1.41-ndb-7.0.13-cluster-gpl MySQL Cluster Server (GPL)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> CREATE DATABASE postfix;
Query OK, 1 row affected (0.04 sec)

mysql> CREATE USER 'postfix'@'localhost' IDENTIFIED BY 'choose_a_password';
Query OK, 0 rows affected (0.16 sec)

mysql> GRANT ALL PRIVILEGES ON `postfix` . * TO 'postfix'@'localhost';
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE USER 'postfix'@'192.168.0.18' IDENTIFIED BY 'choose_a_password';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT ALL PRIVILEGES ON `postfix` . * TO 'postfix'@'192.168.0.18';
Query OK, 0 rows affected (0.01 sec)

mysql> FLUSH PRIVILEGES;

mysql> exit;
Bye

-Configuramos postfixadmin

cd /var/www/html/postfixadmin
yum install php-cli php-ldap php-mysql php-gd php php-pear php-pdo php-common php-devel php-mbstring.i386

yum install php-imap php-odbc php-xml php-xmlrpc curl curl-devel perl-libwww-perl ImageMagick libxml2 libxml2-devel dovecot

vi config.inc.php

$CONF['configured'] = true;
$CONF['setup_password'] = 'cambiame';
$CONF['postfix_admin_url'] = 'http://192.168.0.18/postfixadmin';
$CONF['postfix_admin_path'] = dirname(__FILE__);
$CONF['default_language'] = 'en';
$CONF['database_type'] = 'mysql';
$CONF['database_host'] = '192.168.0.22';
$CONF['database_user'] = 'postfix';
$CONF['database_password'] = 'password';
$CONF['database_name'] = 'postfix';
$CONF['database_prefix'] = '';

$CONF['database_tables'] = array (
    'admin' => 'admin',
    'alias' => 'alias',
    'alias_domain' => 'alias_domain',
    'config' => 'config',
    'domain' => 'domain',
    'domain_admins' => 'domain_admins',
    'fetchmail' => 'fetchmail',
    'log' => 'log',
    'mailbox' => 'mailbox',
    'vacation' => 'vacation',
    'vacation_notification' => 'vacation_notification',
    'quota' => 'quota',
        'quota2' => 'quota2',
);
$CONF['admin_email'] = 'postmaster@yourdomain.com';
$CONF['smtp_server'] = 'localhost';
$CONF['smtp_port'] = '25';
$CONF['encrypt'] = 'md5crypt';
$CONF['authlib_default_flavor'] = 'md5raw';
$CONF['dovecotpw'] = "/usr/sbin/dovecotpw";
$CONF['min_password_length'] = 8;
$CONF['generate_password'] = 'NO';
$CONF['show_password'] = 'YES';
$CONF['page_size'] = '200';
$CONF['default_aliases'] = array (
    'abuse' => 'abuse@change-this-to-your.domain.tld',
    'hostmaster' => 'hostmaster@change-this-to-your.domain.tld',
    'postmaster' => 'postmaster@change-this-to-your.domain.tld',
    'webmaster' => 'webmaster@change-this-to-your.domain.tld'
);
$CONF['domain_path'] = 'NO';
$CONF['domain_in_mailbox'] = 'YES';
$CONF['maildir_name_hook'] = 'NO';
$CONF['aliases'] = '10';
$CONF['mailboxes'] = '10';
$CONF['maxquota'] = '100';
$CONF['quota'] = 'YES';
$CONF['quota_multiplier'] = '1024000';
$CONF['transport'] = 'NO';
$CONF['transport_options'] = array (
    'virtual',  // for virtual accounts
    'local',    // for system accounts
    'relay'     // for backup mx
);
$CONF['transport_default'] = 'virtual';
$CONF['vacation'] = 'YES';
$CONF['vacation_domain'] = 'autoreply.yourdomain.com';
$CONF['vacation_control'] ='YES';
$CONF['vacation_control_admin'] = 'YES';
$CONF['alias_control'] = 'YES';
$CONF['alias_control_admin'] = 'YES';
$CONF['special_alias_control'] = 'NO';
$CONF['alias_goto_limit'] = '0';
$CONF['alias_domain'] = 'YES';
$CONF['backup'] = 'YES';
$CONF['sendmail'] = 'YES';
$CONF['logging'] = 'YES';
$CONF['fetchmail'] = 'YES';
$CONF['fetchmail_extra_options'] = 'NO';
$CONF['show_header_text'] = 'NO';
$CONF['header_text'] = ':: Postfix Admin ::';
$CONF['user_footer_link'] = "http://www.yourdomain.com/";
$CONF['show_footer_text'] = 'NO';
$CONF['footer_text'] = 'Return to change-this-to-your.domain.tld';
$CONF['footer_link'] = 'http://change-this-to-your.domain.tld';
$CONF['welcome_text'] = <<
Hi,

Welcome to your new account.
EOM;
$CONF['emailcheck_resolve_domain']='YES';
$CONF['show_status']='YES';

$CONF['show_status_key']='YES';
$CONF['show_status_text']='  ';
$CONF['show_undeliverable']='YES';
$CONF['show_undeliverable_color']='tomato';
$CONF['show_undeliverable_exceptions']=array("unixmail.domain.ext","exchangeserver.domain.ext","gmail.com");
$CONF['show_popimap']='YES';
$CONF['show_popimap_color']='darkgrey';
$CONF['show_custom_domains']=array("subdomain.domain.ext","domain2.ext");
$CONF['show_custom_colors']=array("lightgreen","lightblue");
$CONF['recipient_delimiter'] = "";
$CONF['mailbox_postcreation_script']='sudo /usr/local/bin/postfixadmin-mailbox-postcreation.sh';
$CONF['mailbox_postdeletion_script']='sudo /usr/local/bin/postfixadmin-mailbox-postdeletion.sh';
$CONF['domain_postdeletion_script']='sudo /usr/local/bin/postfixadmin-domain-postdeletion.sh';
$CONF['used_quotas'] = 'NO';
$CONF['new_quota_table'] = 'NO';
$CONF['theme_logo'] = 'images/logo-default.png';
$CONF['theme_css'] = 'css/default.css';
$CONF['xmlrpc_enabled'] = false;
if (file_exists(dirname(__FILE__) . '/config.local.php')) {
    include(dirname(__FILE__) . '/config.local.php');
}

-Habilitamos permisos para apache

chown -R apache.apache /var/www/html/postfixadmin

-Abrimos firefox y vemos el URL http://192.168.0.18/postfixadmin/setup.php
Se realizara un test de que tengamos todos los requirimientos ok y nos pedira un password, le colocamos uno y el nos devuelve un hash del mismo. OJO, que no se nos olvide este password. El hash devuelto lo colocamos en $CONF['setup_password'] = dentro de config.inc.php

-A continuacion nos creamos una cuenta con privilegios de admin en la misma pagina web, en la opcion Setup password colocamos el password que colocamos anteriormente, no en hash sino normal, email de la persona y el password a colocarle 2 veces y damos click en Add Admin
Debe devolvernos Admin has been added!

-Continuamos

mv setup.php setup.php-disabled
cp /var/www/html/postfixadmin/ADDITIONS/postfixadmin* /usr/local/bin
cd /usr/local/bin
chown root.root
postfixadmin*
chmod 744 postfixadmin*

-Modificamos o agregamos las siguientes lineas en estos 3 scripts

vi postfixadmin-mailbox-postcreation.sh

basedir=/opt/mail
..
..
maildirmake "$maildir"
chown -R vmail:vmail $maildir

-Salvamos y salimos

vi postfixadmin-mailbox-postdeletion.sh

basedir=/opt/mail
trashbase=/opt/deleted
..
..
maildir="${basedir}/${1}"
..
..
mv $maildir $trashdir
chown -R vmail:vmail $trashdir

-Salvamos y salimos

vi postfixadmin-domain-postdeletion.sh

basedir=/opt/mail
trashbase=/opt/deleted

mv $domaindir $trashdir
chown -R vmail:vmail $trashdir


-Salvamos y salimos
-Creamos los directorios mail y deleted

mkdir /opt/mail /opt/deleted
chmod 700 /opt/mail/ /opt/deleted/
chown vmail.vmail /opt/mail/ /opt/deleted/

-Modificamos

vi /var/www/html/postfixadmin/smarty.inc.php

-Buscamos

return htmlentities($data, ENT_QUOTES, 'UTF-8', false);

y lo cambiamos a

return htmlentities($data, ENT_QUOTES, 'UTF-8');

-Salimos salvando.

-Accedemos a la interfaz administrativa de postfixadmin. Pero aun no creamos dominios y cuentas:

http://192.168.0.18/postfixadmin/

-Configuramos SASL para SMTP-AUTH

vi /usr/lib/sasl2/smtpd.conf

# smtpd.conf
pwcheck_method: authdaemond
log_level: 3
mech_list: PLAIN LOGIN
authdaemond_path:/var/spool/authdaemon/socket

-Salvamos y salimos

chown root.vmail /usr/lib/sasl2/smtpd.conf
chmod 640 /usr/lib/sasl2/smtpd.conf
chmod 755 /var/spool/authdaemon/

-Comenzamos a configurar postfix

cd /etc/postfix

-Modificamos master.cf

vi master.cf

#descomentamos smtps para tener smtp sobre SSL
smtps inet n - n - - smtpd
-o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes

#habilitamos otro puerto para el smtp para los casos cuando los ISP bloquean el puerto 25 SMTP
567 inet n - n - - smtpd

#Modificamos la linea del maildrop
maildrop unix - n n - - pipe
flags=DRhu user=vmail argv=/usr/bin/maildrop -w 90 -d ${recipient}

#agregamos al final el modulo de vacation
#
# VIRTUAL VACATION
#
vacation unix - n n - - pipe
flags=DRhu user=vacation argv=/var/spool/vacation/vacation.pl -f ${sender} -- ${recipient}

-Salvamos y salimos

-Agregamos el usuario para ejecutar el script de vacation. Por motivos de seguridad, no necesitamos que tenga shell asignado, nadie se logeara por esta cuenta

adduser -d /var/spool/vacation -s /sbin/nologin vacation

-Editamos /etc/passwd y le colocamos un * al campo password del usuario vacation, asi evitamos que alguien coloque un password a esta cuenta para después usarla.

vi /etc/passwd
vacation:*:1002:1002::/var/spool/vacation:/sbin/nologin

-Copiamos el script y le cambiamos sus privilegios

cp /var/www/html/postfixadmin/VIRTUAL_VACATION/vacation.pl /var/spool/vacation/vacation.pl
chown vacation.vacation /var/spool/vacation/vacation.pl
chmod 700 /var/spool/vacation/vacation.pl

-Editamos el script y cambiamos

vi /var/spool/vacation/vacation.pl

our $db_type = 'mysql';
our $db_host = '192.168.0.22';
our $db_username = 'postfixadmin';
our $db_password = 'postfixadmin';
our $db_name = 'postfix';
our $vacation_domain = 'autoreply.example.org';
our $smtp_server = 'localhost';
our $smtp_server_port = 25;
our $syslog = 0;
our $logfile='/var/spool/vacation/vacation.log';
our $log_level = 2;
our $log_to_file = 1;
our $interval = 0;

-Lo agregamos a transport

vi /etc/postfix/transport

autoreply.yourdomain.com vacation

-Activamos el cambio

postmap /etc/postfix/transport

-Instalamos por dependencias con perl

yum install links ncftp openssh-askpass

-Entramos a webmin para agregar unos modulos perl que necesitamos para vacation

https://192.168.0.18:10000/

-Vamos a Others - Perl. Modulos a instalar (ademas de los que se instalan por default en Centos):

CPAN::Bundle
DBD::mysql
Mail::Sendmail
Mail::Sender
MailTools
Email::Valid
MIME::Charset
Log::Log4perl
Log::Dispatch
MIME::EncWords
Net::Server
IO::Multiplex

-Modificamos main.cf

cd /etc/postfix

vi main.cf
myhostname = mail.yourdomain.com
mydomain = yourdomain.com
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost
local_recipient_maps = proxy:unix:passwd.byname $alias_maps
mynetworks = $config_directory/mynetworks
relay_domains = mysql:/etc/postfix/mysql_relay_domains_maps.cf
alias_database = hash:/etc/aliases

-Agregamos al final del fichero

virtual_alias_maps      = hash:/etc/aliases mysql:/etc/postfix/mysql_virtual_alias_maps.cf hash:/etc/aliases
virtual_uid_maps        = static:1001
virtual_gid_maps        = static:1001
virtual_mailbox_base    = /opt/mail
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     = 1001
virtual_transport = maildrop
maildrop_destination_recipient_limit = 1
transport_maps = hash:/etc/postfix/transport
vacation_destination_recipient_limit = 1
virtual_create_maildirsize     = yes
virtual_mailbox_extended       = yes
virtual_mailbox_limit_maps     = mysql:/etc/postfix/mysql_virtual_mailbox_limit_maps.cf
virtual_mailbox_limit_override = yes
virtual_maildir_limit_message  = Sorry, the user's maildir has overdrawn his diskspace quota, please try again later.
smtpd_sasl_auth_enable          = yes
smtpd_sasl_security_options     = noanonymous
broken_sasl_auth_clients        = yes
smtpd_sasl_path                 = smptd
smtpd_sasl_local_domain         =
smtpd_sasl_authenticated_header = yes
smtpd_recipient_restrictions    =  permit_mynetworks,permit_sasl_authenticated,reject_non_fqdn_hostname,reject_non_fqdn_sender,reject_non_fqdn_recipient,reject_unauth_destination,reject_unauth_pipelining,reject_invalid_hostname,reject_rbl_client list.dsbl.org,reject_rbl_client bl.spamcop.net,reject_rbl_client sbl-xbl.spamhaus.org
smtp_use_tls                     = no
smtpd_use_tls                    = yes
smtpd_tls_auth_only              = no
smtpd_tls_key_file               = /usr/local/ssl/mail.yourdomain.com.key
smtpd_tls_cert_file              = /usr/local/ssl/mail.yourdomain.com.crt
smtpd_tls_session_cache_database = btree:/etc/postfix/tls_smtpd_scache
smtpd_tls_loglevel               = 1
smtpd_tls_received_header        = yes
smtpd_client_restrictions        = check_client_access hash:/etc/postfix/access
smtpd_client_connection_count_limit = 60
message_size_limit = 16000000

-Creamos los ficheros mysql-virtual

vi /etc/postfix/mysql_virtual_alias_maps.cf
user = postfix
password = postfix
hosts = 192.168.0.22
dbname = postfix
query = SELECT goto FROM alias WHERE address='%s' AND active = 1

vi /etc/postfix/mysql_virtual_domains_maps.cf
user = postfix
password = postfix
hosts = 192.168.0.22
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s'
#optional query to use when relaying for backup MX
#query = SELECT domain FROM domain WHERE domain='%s' and backupmx = '0' and active = '1'

vi /etc/postfix/mysql_virtual_mailbox_maps.cf
user = postfix
password = postfix
hosts = 192.168.0.22
dbname = postfix
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = 1

vi /etc/postfix/mysql_virtual_mailbox_limit_maps.cf
user = postfix
password = postfix
hosts = 192.168.0.22
dbname = postfix
query = SELECT quota FROM mailbox WHERE username='%s'

vi /etc/postfix/mysql_relay_domains_maps.cf
user = postfix
password = postfix
hosts = 192.168.0.22
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s' and backupmx = '1'

-Como estos files contienen datos de conexion a nuestra db, limitamos su acceso por seguridad

chown root.postfix /etc/postfix/mysql_*.cf
chmod 640 /etc/postfix/mysql_*.cf
ls -la /etc/postfix/mysql*
-rw-r----- 1 root postfix 143 Apr 29 15:35 /etc/postfix/mysql_relay_domains_maps.cf
-rw-r----- 1 root postfix 137 Apr 29 15:24 /etc/postfix/mysql_virtual_alias_maps.cf
-rw-r----- 1 root postfix 264 Apr 29 15:27 /etc/postfix/mysql_virtual_domains_maps.cf
-rw-r----- 1 root postfix 126 Apr 29 15:31 /etc/postfix/mysql_virtual_mailbox_limit_maps.cf
-rw-r----- 1 root postfix 143 Apr 29 15:29 /etc/postfix/mysql_virtual_mailbox_maps.cf

-Colocamos las ip de los servers que harán relay a traves de nuestro server. Los usuarios que tengan cuenta en el server no necesitan tener su ip aqui, ya que ellos se logearan por SMTP-AUTH, por default colocamos localhost para darle permiso a los scripts locales en el server

echo '# Localhost' > /etc/postfix/mynetworks
echo '127.0.0.0/8' >>/etc/postfix/mynetworks
echo '' >>/etc/postfix/mynetworks

-Existen 2 formatos de guardar sus mails, Mbox que es un fichero donde se almacenan todos los mails, uno detrás del otro y Maildir que almacena los mails cada uno en un directorio especial. Para este documento usaremos Maildir

-Configuramos Courier-authlib para manejar Courier-IMAP y Courier-POP3

vi /etc/authlib/authdaemonrc
authmodulelist="authmysql"
authdaemonvar=/var/spool/authdaemon

vi /etc/authlib/authmysqlrc
MYSQL_SERVER 192.168.0.22
MYSQL_USERNAME postfix
#password de la cuenta postfix de mysql
MYSQL_PASSWORD 12345
MYSQL_PORT 0
MYSQL_OPT 0
MYSQL_DATABASE postfix
MYSQL_USER_TABLE mailbox
MYSQL_CRYPT_PWFIELD password
MYSQL_CLEAR_PWFIELD password
MYSQL_UID_FIELD '1001'
MYSQL_GID_FIELD '1001'
MYSQL_LOGIN_FIELD username
MYSQL_HOME_FIELD '/opt/mail'
MYSQL_NAME_FIELD name
MYSQL_MAILDIR_FIELD CONCAT("/opt/mail/",maildir)
MYSQL_QUOTA_FIELD concat(quota,'S')

 -Protegemos el fichero

chmod 400 /etc/authlib/authmysqlrc

-Comenzamos a configurar Maildrop con Maildir+softquota

vi /etc/quotawarnmsg
X-Comment: Rename/Copy this file to quotawarnmsg, and make appropriate changes
X-Comment: See deliverquota man page for more information
From: Mail Delivery System
Reply-To: postmaster@calcom.com.mx
To: Valued Customer:;
Subject: Mail quota warning
Mime-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 7bit
Your mailbox on the server is now more than 90% full. So that you can continue to receive mail you need to remove some messages from your mailbox.


vi /etc/postfix/master.cf
maildrop unix - n n - - pipe
flags=DRhu user=vmail argv=/usr/bin/maildrop -w 90 -d ${recipient}
#-w N dara un alerta por mail al usuario cuando su quota de disco este al N porciento lleno
#repitiendose esta alerta todos los dias hasta que libere espacio. El mensaje se toma de
#/etc/quotawarnmsg con los campos "Date:" y "Message-Id:" actualizados


-Salvamos y salimos. Reiniciamos el servicio postfix

chkconfig sendmail off
service sendmail stop
chkconfig postfix on
service postfix restart

vi /etc/maildroprc
logfile "/var/log/maildroprc.log"

-Configuramos Courier-IMAP Courier-POP3

vi /usr/lib/courier-imap/etc/imapd
MAXPERIP=20
IMAP_CAPABILITY="IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA AUTH=CRAM-MD5 AUTH=CRAM-SHA1 AUTH=PLAIN AUTH=LOGIN IDLE"
IMAP_ACL=0
IMAP_CAPABILITY_TLS="$IMAP_CAPABILITY"
IMAP_ENHANCEDIDLE=1
#IMAP_TRASHFOLDERNAME=Trash
IMAPDSTART=YES
#IMAP_EMPTYTRASH=Trash:7

vi /usr/lib/courier-imap/etc/imapd-ssl
IMAPDSSLSTART=YES
IMAPDSTARTTLS=YES
#certificado creado anteriormente
TLS_CERTFILE=/usr/local/ssl/mail.yourdomain.com.pem
TLS_PROTOCOL=SSL3
TLS_STARTTLS_PROTOCOL=TLS1

vi /usr/lib/courier-imap/etc/pop3d
MAXDAEMONS=40
POP3AUTH="CRAM-MD5 CRAM-SHA1 PLAIN LOGIN"
POP3AUTH_ORIG="PLAIN LOGIN CRAM-MD5 CRAM-SHA1 CRAM-SHA256"
POP3AUTH_TLS="$POP3AUTH"
POP3DSTART=YES
MAXPERIP=20

vi /usr/lib/courier-imap/etc/pop3d-ssl
POP3DSSLSTART=YES
POP3_STARTTLS=YES
TLS_CERTFILE=/usr/local/ssl/mail.yourdomain.com.pem
TLS_PROTOCOL=SSL3

-Ejecutamos y verificamos que los daemons necesarios estan ok

service saslauthd start
service courier-authlib start
service courier-imap start
service postfix restart
chkconfig saslauthd on
chkconfig courier-authlib on
chkconfig courier-imap on

-Modificaciones a postfixadmin
-Normalmente para crear los maildir para las cuentas de email necesitaremos algunos comandos, aunque modificaremos el postfixadmin para que haga el trabajo sucio por nosotros.
-Este es un ejemplo de como hacerlo manualmente

-Creación del home maildir de una cuenta email:
maildirmake /opt/mail/user1@yourdomain.com

-Le creamos una quota de disco, si no esta presente, no hay restricción de espacio, en este caso son 10MB y fijense en la S que colocamos al final del numero:
maildirmake -q 10971520S /opt/mail/user1@yourdomain.com

-Protegemos el directorio
chmod g-r,o-r /opt/mail/user1\@yourdomain.com/
chown -R vmail.vmail /opt/mail/user1\@yourdomain.com/

-Damos permiso a los scripts para crear usuarios y dominios y borrarlos desde postfixadmin

visudo
#comentamos requiretty
#Defaults requiretty
..
..

vmail   ALL=(ALL)       NOPASSWD: ALL
apache  ALL=(ALL)      NOPASSWD: ALL
apache mail.yourdomain.com=NOPASSWD:   /usr/local/bin/postfixadmin-mailbox-postcreation.sh
apache mail.yourdomain.com=NOPASSWD:   /usr/local/bin/postfixadmin-mailbox-postdeletion.sh
apache mail.yourdomain.com=NOPASSWD:   /usr/local/bin/postfixadmin-domain-postdeletion.sh


service postfix restart

-Manejo de la cola de emails en postfix por linea de comandos

postqueue -p

-Poner un mensaje en HOLD. MESSAGEID es un identificador unico dado por postfix al colocar el mail en cola, para marcar todos los mails escribimos ALL

postsuper -h MESSAGEID

-Eliminar un mail de la cola

postsuper -d MESSAGEID

-Eliminar todos los mails en la cola

postsuper -d ALL

-Verificamos permisos de los files del postfix

postfix check

-Verificamos otros errores

egrep '(reject|warning|error|fatal|panic):' /var/log/maillog

-Verificamos los valores de Courier-authlib. Mostramos las cuentas creadas

vi /etc/authlib/authdaemonrc

DEBUG_LOGIN=2

-Reiniciamos el daemon

service courier-authlib restart

-Listamos las cuentas

/usr/sbin/authenumerate
user2@yourdomain.com 1001 1001 /opt/mail /opt/mail/user2@yourdomain.com/

-Verificamos por linea de comandos una cuenta

/usr/sbin/authtest someuser@yourdomain.com somepassword
Authentication succeeded.

Authenticated: someuser@yourdomain.com (uid 1001, gid 1001)
Home Directory: /opt/mail
Maildir: /opt/mail/someuser@yourdomain.com/
Quota: 10240000S
Encrypted Password: $1$9625a822$9wBt3mVsXm9oMbbO49HVX/
Cleartext Password: somepassword
Options: wbnochangepass=1,wbusexsender=1,disableshared=1

-Cuando estemos seguro de que Courier-authlib este funcionando ok, desabilitamos el modo debug o podemos llenar nuestro disco con mensajes de log

vi /etc/authlib/authdaemonrc
DEBUG_LOGIN=0

service courier-authlib restart

-Verificamos el servicio POP3

telnet localhost pop3
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
+OK Hello there.
user user2@yourdomain.com
+OK Password required.
pass 12345
+OK logged in.
stat
+OK 0 0
quit
+OK Bye-bye.
Connection closed by foreign host.

-Verificamos IMAP

telnet localhost imap
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA AUTH=CRAM-MD5 AUTH=CRAM-SHA1 AUTH=PLAIN AUTH=LOGIN IDLE STARTTLS] Courier-IMAP ready. Copyright 1998-2008 Double Precision, Inc.  See COPYING for distribution information.
a login user2@yourdomain.com 12345
a OK LOGIN Ok.
a examine inbox
* FLAGS (\Draft \Answered \Flagged \Deleted \Seen \Recent)
* OK [PERMANENTFLAGS ()] No permanent flags permitted
* 0 EXISTS
* 0 RECENT
* OK [UIDVALIDITY 1221862032] Ok
* OK [MYRIGHTS "cdilrsw"] ACL
a OK [READ-ONLY] Ok
a logout
* BYE Courier-IMAP server shutting down
a OK LOGOUT completed
Connection closed by foreign host.

-Verificamos Maildrop. Salimos con Control C

maildrop -V9 -d user2@yourdomain.com
maildrop: authlib: groupid=1001
maildrop: authlib: userid=1001
maildrop: authlib: logname=user2@yourdomain.com, home=/opt/mail, mail=/opt/mail/user2@yourdomain.com/
maildrop: Changing to /opt/mail

-Ya con postfix funcionando ok, pasaremos a instalar y configurar MailScanner. MailScanner es un software opensource que integra soporte antispam con spamassassin y antivirus con clamav entre otros antivirus.

-Antes de comenzar paramos el servicio postfix

service postfix stop
service saslauthd stop

mkdir /var/spool/postfix/usr
mkdir /var/spool/postfix/usr/var
mkdir /var/spool/postfix/var/
mkdir /var/spool/postfix/var/spool
mv /var/spool/authdaemon/ /var/spool/postfix/var/spool/authdaemon
ln -s /var/spool/postfix/var/spool/authdaemon/ /var/spool/authdaemon

-Reiniciamos postfix y saslauthd

service postfix start
service saslauthd start

-Cambiamos la configuración del postfix para que trabaje en modo split MTA
vi /etc/postfix/main.cf

header_checks = regexp:/etc/postfix/header_checks

vi /etc/postfix/header_checks

/^Received:/ HOLD

-Descargamos MailScanner

cd /home/vmail/downloads/

wget -c http://mailscanner.info/files/4/rpm/MailScanner-4.80.4-1.rpm.tar.gz
gunzip -d MailScanner-4.80.4-1.rpm.tar.gz
tar xvf MailScanner-4.80.4-1.rpm.tar
cd MailScanner-4.80.4-1

-Ejecutamos el script de install, OJO, colocamos un . punto antes del /

./install.sh

-Prestamos atencion que se instalen bien HTML-Parser y MIME-tools. Es normal que veamos algunos errores. Pero estos 2 modulos si deben quedar instalados. Ctrl-S para temporalmente la ejecucion para darnos tiempo a anotar algun error o modulo faltante para despues instalarlo y Ctrl-Q continua. Si algun modulo perl da error por falta de otro modulo, tomamos nota y lo instalamos despues al terminar el install.sh y volvemos a ejecutarlo.

-Modificamos los siguientes parametros en MailScanner.conf

cd /etc/MailScanner
vi MailScanner.conf

Run As User = postfix
Run As Group = postfix
Incoming Queue Dir = /var/spool/postfix/hold
Outgoing Queue Dir = /var/spool/postfix/incoming
MTA = postfix
SpamAssassin User State Dir = /var/spool/MailScanner/spamassassin

-Preparamos el directorio bayes

mkdir /etc/MailScanner/bayes
chmod g+rws /etc/MailScanner/bayes

-Descargamos e instalamos spamassassin y clamav (antispam-antivirus)

cd /home/vmail/downloads/

-Creamos una cuenta para clamav pero sin home y sin que se pueda logear

adduser -Ms /sbin/nologin clamav

wget -c http://mailscanner.info/files/4/install-Clam-SA-latest.tar.gz
tar xzvf install-Clam-SA-latest.tar.gz
cd install-Clam-0.96-SA-3.3.0
./install.sh

-Respondemos y en:
Do you want me to install ClamAV for you [y or n, default is y] ? y

-Habilitamos algunos pluggins de spamassassin


vi /etc/mail/spamassassin/init.pre
loadplugin Mail::SpamAssassin::Plugin::RelayCountry
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL
loadplugin Mail::SpamAssassin::Plugin::Hashcash
loadplugin Mail::SpamAssassin::Plugin::SPF
loadplugin Mail::SpamAssassin::Plugin::Razor2
loadplugin Mail::SpamAssassin::Plugin::DKIM

vi /etc/mail/spamassassin/v310.pre
loadplugin Mail::SpamAssassin::Plugin::DCC
loadplugin Mail::SpamAssassin::Plugin::Pyzor
loadplugin Mail::SpamAssassin::Plugin::Razor2
loadplugin Mail::SpamAssassin::Plugin::SpamCop
loadplugin Mail::SpamAssassin::Plugin::AWL
loadplugin Mail::SpamAssassin::Plugin::AutoLearnThreshold
loadplugin Mail::SpamAssassin::Plugin::TextCat
loadplugin Mail::SpamAssassin::Plugin::WhiteListSubject
loadplugin Mail::SpamAssassin::Plugin::MIMEHeader
loadplugin Mail::SpamAssassin::Plugin::ReplaceTags
loadplugin Mail::SpamAssassin::Plugin::RelayCountry
loadplugin Mail::SpamAssassin::Plugin::SPF
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL
loadplugin Mail::SpamAssassin::Plugin::DKIM

vi /etc/mail/spamassassin/v312.pre
loadplugin Mail::SpamAssassin::Plugin::DKIM

vi /etc/mail/spamassassin/v320.pre
loadplugin Mail::SpamAssassin::Plugin::Check
loadplugin Mail::SpamAssassin::Plugin::HTTPSMismatch
loadplugin Mail::SpamAssassin::Plugin::URIDetail
loadplugin Mail::SpamAssassin::Plugin::Shortcircuit
loadplugin Mail::SpamAssassin::Plugin::Bayes
loadplugin Mail::SpamAssassin::Plugin::BodyEval
loadplugin Mail::SpamAssassin::Plugin::DNSEval
loadplugin Mail::SpamAssassin::Plugin::HTMLEval
loadplugin Mail::SpamAssassin::Plugin::HeaderEval
loadplugin Mail::SpamAssassin::Plugin::MIMEEval
loadplugin Mail::SpamAssassin::Plugin::RelayEval
loadplugin Mail::SpamAssassin::Plugin::URIEval
loadplugin Mail::SpamAssassin::Plugin::WLBLEval
loadplugin Mail::SpamAssassin::Plugin::VBounce
loadplugin Mail::SpamAssassin::Plugin::ImageInfo
loadplugin Mail::SpamAssassin::Plugin::RelayCountry
loadplugin Mail::SpamAssassin::Plugin::SPF
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL
loadplugin Mail::SpamAssassin::Plugin::Razor2
loadplugin Mail::SpamAssassin::Plugin::DKIM

vi /etc/mail/spamassassin/v330.pre
loadplugin Mail::SpamAssassin::Plugin::FreeMail
loadplugin Mail::SpamAssassin::Plugin::RelayCountry
loadplugin Mail::SpamAssassin::Plugin::SPF
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL
loadplugin Mail::SpamAssassin::Plugin::Razor2
loadplugin Mail::SpamAssassin::Plugin::DKIM

-Activamos el spamassassin y clamav en MailScanner.conf

vi /etc/MailScanner/MailScanner.conf
Use SpamAssassin = yes
Incoming Work User = clamav
Incoming Work Group = clamav
Clamd Socket = /tmp/clamd.socket
Incoming Work Permissions = 0660
Quarantine User = root
Quarantine Group = apache
Quarantine Permissions = 0660
Quarantine Whole Message = yes
Spam Actions = store
Always Looked Up Last = MailWatchLogging
Is Definitely Not Spam = &SQLWhitelist
Is Definitely Spam = &SQLBlacklist

-Creamos el script de inicio para spamassassin

vi /etc/init.d/spamassassin
#!/bin/sh
#
# spamassassin This script starts and stops the spamd daemon
#
# chkconfig: - 78 30
# processname: spamd
# description: spamd is a daemon process which uses SpamAssassin to check \
#              email messages for SPAM.  It is normally called by spamc \
#              from a MDA.

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

prog="spamd"

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# Set default spamd configuration.
SPAMDOPTIONS="-d -c -m5 -H"
SPAMD_PID=/var/run/spamd.pid

# Source spamd configuration.
if [ -f /etc/sysconfig/spamassassin ] ; then
        . /etc/sysconfig/spamassassin
fi

[ -f /usr/bin/spamd -o -f /usr/local/bin/spamd ] || exit 0
PATH=$PATH:/usr/bin:/usr/local/bin

# By default it's all good
RETVAL=0
# See how we were called.
case "$1" in
  start)
        # Start daemon.
        echo -n $"Starting $prog: "
        daemon $NICELEVEL spamd $SPAMDOPTIONS -r $SPAMD_PID
        RETVAL=$?
        echo
        if [ $RETVAL = 0 ]; then
                touch /var/lock/subsys/spamassassin
        fi
        ;;
  stop)
        # Stop daemons.
        echo -n $"Stopping $prog: "
        killproc spamd
        RETVAL=$?
        echo
        if [ $RETVAL = 0 ]; then
                rm -f /var/lock/subsys/spamassassin
                rm -f $SPAMD_PID
        fi
        ;;
  restart)
        $0 stop
        sleep 3
        $0 start
        ;;
  condrestart)
       [ -e /var/lock/subsys/spamassassin ] && $0 restart
       ;;
  status)
         status spamd
        RETVAL=$?
        ;;
  *)
        echo "Usage: $0 {start|stop|restart|status|condrestart}"
        RETVAL=1
        ;;
esac

exit $RETVAL

-Salimos salvando, pasamos a activarlo

chkconfig spamassassin on
service spamassassin start

-Configuramos clamav y freshclam

vi /usr/local/etc/clamd.conf
LogSyslog yes
LogFacility LOG_MAIL
DatabaseDirectory /usr/local/share/clamav
LocalSocket /tmp/clamd.socket
SelfCheck 600
AlgorithmicDetection yes
ScanPE yes
ScanELF yes
ScanOLE2 yes
ScanPDF yes
ScanMail yes
PhishingSignatures yes
ScanHTML yes
ScanArchive yes
MaxScanSize 15M

vi /usr/local/etc/freshclam.conf
DatabaseDirectory  /usr/local/share/clamav
UpdateLogFile /var/log/freshclam.log
LogFileMaxSize 2M
LogSyslog yes
LogFacility LOG_MAIL
PidFile disabled
DatabaseOwner clamav
DNSDatabaseInfo current.cvd.clamav.net
DatabaseMirror db.US.clamav.net
DatabaseMirror database.clamav.net
ScriptedUpdates yes
NotifyClamd /usr/local/etc/clamd.conf

-Creamos un script para iniciar clamd y lo activamos

vi /etc/init.d/clamd
#! /bin/bash
#
# crond   Start/Stop the clam antivirus daemon.
#
# chkconfig: 2345 70 41
# description: clamd is a standard Linux/UNIX program that scans for Viruses.
# processname: clamd
# config: /usr/local/etc/clamd.conf
# pidfile: /var/lock/subsys/clamd

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

RETVAL=0

# See how we were called.

prog="clamd"
progdir="/usr/local/sbin"

# Source configuration
if [ -f /etc/sysconfig/$prog ] ; then
        . /etc/sysconfig/$prog
fi

start() {
        echo -n $"Starting $prog: "
        LANG= daemon $progdir/$prog
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch /var/lock/subsys/clamd
        return $RETVAL
}

stop() {
echo -n $"Stopping $prog: "
        # Would be better to send QUIT first, then killproc if that fails
        killproc $prog
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/clamd
        return $RETVAL
}

rhstatus() {
        status clamd
}

restart() {
        stop
        start
}

reload() {
        echo -n $"Reloading clam daemon configuration: "
        killproc clamd -HUP
        retval=$?
        echo
        return $RETVAL
}

case "$1" in
  start)
        start
        ;;
  stop)
stop
        ;;
  restart)
        restart
        ;;
  reload)
        reload
        ;;
  status)
        rhstatus
        ;;
  condrestart)
        [ -f /var/lock/subsys/clamd ] && restart || :
        ;;
  *)
        echo $"Usage: $0 {start|stop|status|reload|restart|condrestart}"
        exit 1
esac

exit $?

-Salimos salvando y ahora lo activamos

chkconfig clamd
service clamd start

vi /etc/MailScanner/spam.assassin.prefs.conf
ok_locales              en es pt
use_bayes 1
bayes_path /etc/MailScanner/bayes/bayes
bayes_file_mode 0660
bayes_auto_learn 1
ifplugin Mail::SpamAssassin::Plugin::Pyzor
pyzor_path /usr/bin/pyzor
endif
rbl_timeout 11
razor_timeout 10
pyzor_timeout 4

-Instalamos y configuramos razor, dcc y pyzor

cd /home/vmail/downloads/
wget -c http://internap.dl.sourceforge.net/sourceforge/razor/razor-agents-sdk-2.07.tar.bz2
wget
bunzip2 razor-agents-sdk-2.07.tar.bz2
bunzip2 razor-agents-2.84.tar.bz2
tar xvf razor-agents-sdk-2.07.tar
tar xvf razor-agents-2.84.tar

-Verificamos tengamos los siguientes modulos perl instalados:

Time::HiRes
Digest::SHA1
MIME::Base64
Test::Simple
Test::Harness
Getopt::Long
Business::ISBN
GD::Barcode::EAN13
URI::Escape

-Compilamos e instalamos razor

cd razor-agents-sdk-2.07
perl Makefile.PL
make
make test
make install

cd ..
cd razor-agents-2.84
perl Makefile.PL
make
make test
make install

-Creamos el usuario razor para sus reportes, como postfix no puede logearse, primero lo creamos en root y despues lo pasamos al home de postfix

cd /root
razor-admin -create
razor-admin -register
cp -rf .razor/ /var/spool/postfix/
chown -R postfix.postfix /var/spool/postfix/.razor/

-Descargamos e instalamos DCC

cd /home/vmail/downloads/
wget -c http://www.rhyolite.com/dcc/source/dcc.tar.Z
uncompress -d dcc.tar.Z
tar xvf dcc.tar
cd dcc-1.3.126/
./configure
make install

-Descargamos e instalamos Pyzor

cd ..
wget -c http://downloads.sourceforge.net/project/pyzor/pyzor/0.5.0/pyzor-0.5.0.tar.gz
tar xzvf pyzor-0.5.0.tar.gz
cd pyzor-0.5.0

-Para instalar pyzor necesitamos el modulo gdbm de python, verificamos si lo tenemos instalado

python -c 'import gdbm' && echo 'gdbm found'
gdbm found

python setup.py build
python setup.py install

-Le cambiamos los permisos

chmod -R a+rX /usr/share/doc/pyzor /usr/lib/python2.4/site-packages/pyzor /usr/bin/pyzor /usr/bin/pyzord

cd /root
pyzor discover
cp -rf .pyzor/ /var/spool/postfix/
chown -R postfix.postfix /var/spool/postfix/.pyzor/

chkconfig postfix off
service postfix stop
chkconfig MailScanner on
service MailScanner restart

-Descargamos MailWatch

cd /home/vmail/downloads
wget -c http://internap.dl.sourceforge.net/sourceforge/mailwatch/mailwatch-1.0.5.tar.gz
tar xzvf mailwatch-1.0.5.tar.gz
cd mailwatch-1.0.5

-Copiamos el file de creacion de la db al SQL

scp create.sql root@192.168.0.22:/root

-En el server SQL, creamos la db para MailWatch y damos permisos para su acceso

mysql -p < create.sql
mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 154
Server version: 5.1.41-ndb-7.0.13-cluster-gpl MySQL Cluster Server (GPL)

mysql> CREATE USER 'mailwatch'@'localhost' IDENTIFIED BY 'choose_a_password';
Query OK, 0 rows affected (0.07 sec)

mysql> GRANT ALL PRIVILEGES ON `mailscanner` . * TO 'mailwatch'@'localhost';
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE USER 'mailwatch'@'192.168.0.18' IDENTIFIED BY 'choose_a_password';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT ALL PRIVILEGES ON `mailscanner` . * TO 'mailwatch'@'192.168.0.18';
Query OK, 0 rows affected (0.00 sec)

mysql>FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye

-Volvemos al server de email para editar la configuracion de MailWatch.

vi MailWatch.pm
my($db_host) = '192.168.0.22';
my($db_user) = 'mailwatch';
my($db_pass) = 'choose_a_password';
#Comentamos la linea 93
#$dbh->commit;

-Salimos salvando.

mv MailWatch.pm /usr/lib/MailScanner/MailScanner/CustomFunctions/
mv -f mailscanner/ /var/www/html/
chown -R apache:apache /var/www/html/mailscanner/
chmod ug+rwx /var/www/html/mailscanner/images/ /var/www/html/mailscanner/images/cache/
chmod ug+rw /var/www/html/mailscanner/temp/

vi /var/www/html/mailscanner/conf.php.example
define('DB_USER', 'mailwatch');
define('DB_PASS', 'choose_a_password');
define('DB_HOST', '192.168.0.22');
define('QUARANTINE_USE_FLAG', true);

mv /var/www/html/mailscanner/conf.php.example /var/www/html/mailscanner/conf.php
vi SQLBlackWhiteList.pm
my($db_host) = '192.168.0.22';
my($db_user) = 'mailwatch';
my($db_pass) = 'choose_a_password';

mv SQLBlackWhiteList.pm /usr/lib/MailScanner/MailScanner/CustomFunctions/

-Creamos el usuario admin para acceder a mailwatch. Regresamos al server SQL

mysql mailscanner -u mailwatch -p

INSERT INTO users VALUES ('%web_user_username%',md5('%web_user_password%'),'%web_user_name%','A','0','0','0','0','0');
quit;

-Volvemos al server de email y modificamos php.ini.

vi /etc/php.ini
short_open_tag ="On"
safe_mode ="Off"
register_globals ="Off"
magic_quotes_gpc ="On"
magic_quotes_runtime ="Off"
auto_start ="0"
allow_url_fopen ="On"
upload_max_filesize ="15M"
post_max_size = 15M

-Verificamos haya quedado bien configurado spamassassin. Verificamos si falta algun modulo perl para instalarselo

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

-Modificamos la cuarentena de MailScanner


vi /etc/cron.daily/clean.quarantine
$days_to_keep   = 15;

-Modificamos la cuarentena de MailWatch

cd /home/vmail/downloads/mailwatch-1.0.5
vi tools/db_clean.php
#!/usr/bin/php -q

cp tools/quarantine_maint.php /usr/local/bin/
cp tools/db_clean.php /usr/local/bin/
chmod +x /usr/local/bin/quarantine_maint.php /usr/local/bin/db_clean.php

-En una sola linea ejecutamos lo siguiente

echo "/usr/local/bin/quarantine_maint.php --clean" > /etc/cron.daily/mailwatch_quarantine_maint.sh

echo "/usr/local/bin/db_clean.php" > /etc/cron.daily/mailwatch_db_clean.sh
chmod +x /etc/cron.daily/mailwatch*

 -Cola de mensajes

cp mailq.php /usr/local/bin/
crontab -e
0-59 * * * * /usr/local/bin/mailq.php

-Liberar un mail de cuarentena y que no sea chequeado nuevamente con los filtros antispam y antivirus. Debemos agregar un registro a la db mailscanner en la tabla whitelist. Los valores serian:

to_address = defaultto_domain = defaultfrom_address = 127.0.0.1

-Modificamos algunos ficheros de MailScanner, OJO, los campos son separados por TAB dentro de estos ficheros

cd /etc/MailScanner/

-En una sola linea ejecutamos el siguiente comando

touch filename.rules filetype.rules filename.rules.allowall.conf filetype.rules.allowall.conf rules/content.scanning.rules

vi filename.rules
From: 127.0.0.1 /etc/MailScanner/filename.rules.allowall.conf
FromOrTo: default /etc/MailScanner/filename.rules.conf

vi filetype.rules
From: 127.0.0.1 /etc/MailScanner/filetype.rules.allowall.conf
FromOrTo: default /etc/MailScanner/filetype.rules.conf

vi filename.rules.allowall.conf
allow .* - -

vi filetype.rules.allowall.conf
allow .* - -

vi rules/content.scanning.rules
From: 127.0.0.1 no
FromOrTo: default yes

-Modificamos los permisos para el directorio de cuarentena

chmod g+rws /var/spool/MailScanner/quarantine/

-Instalamos unrar
cd /home/vmail/downloads/
wget -c http://dag.wieers.com/rpm/packages/unrar/unrar-3.7.4-1.el5.rf.i386.rpm
rpm -vi unrar-3.7.4-1.el5.rf.i386.rpm

-Entrada a MailWatch. Nos logeamos con el usuario administrativo que creamos, en el URL http://192.168.0.18/mailscanner

-Personalizamos MailWatch. Actualizamos las definiciones de spamassassin y GeoIP en Tools/Links y con eso nos queda listo nuestro server. En la medida que nuestro server maneje una buena cantidad de mails, mas de 1000, entre spam y ham (mails buenos) este mejorara su porcentaje de efectividad.

Share/Bookmark

Email server con postfix, mailscanner, mailwatch, spamassassin, clamav en Centos 5.2

Esta vez instalaremos y configuraremos un servidor Centos 5.2 para que funcione como servidor de email con antispam/antivirus y una base de usuarios virtuales en una db mysql con las siguientes herramientas:

MTA postfix
PostfixAdmin
MailScanner 4.72.2
MailWatch 1.0.4
Antivirus clamav 0.94
spamassassin
MySQL 5.0

Esta configuración me funciona en varios servidores y asi la he configurado, en Linux una operación se puede hacer de varias formas, así que si alguien tiene una mejor forma, favor decirme y aprendemos todos, jejeje. :-)

email server: 192.168.1.197

-Instalamos webmin

wget -c http://internap.dl.sourceforge.net/sourceforge/webadmin/webmin-1.430-1.noarch.rpm
rpm -vi webmin-1.430-1.noarch.rpm

-Instalamos herramientas para modificar y actualizar su zona horaria y fecha

yum install system-config-date mingetty ethtool

-Verificamos que el firewall este desabilitado por el momento

iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

-Desabilitamos SELinux.

vi /etc/selinux/config

-Modificamos la linea SELINUX
SELINUX=disabled

-Salvamos los cambios y salimos
-Instalamos software que nos hará falta mas tarde

yum install fetchmail wget bzip2 unzip zip nmap openssl lynx fileutils ncftp gcc gcc-c++ bind-utils

-Instalamos y configuramos MySQL
yum install mysql mysql-devel mysql-server
chkconfig --levels 235 mysqld on
service mysqld start

-Verificamos que el mysql este ejecutándose y esperando conexiones

netstat -tap | grep mysql
tcp 0 0 *:mysql *:* LISTEN 2091/mysqld

-En caso de que no este activo, editamos my.cnf y agregamos la siguiente linea en la sección [mysqld] y damos restart al servicio

vi /etc/my.cnf
#skip-networking

service mysqld restart

-Le colocamos password al usuario root de MySQL. OJO, usar una verdadera contraseña y su dominio internet real

mysqladmin -u root password 12345
mysqladmin -h m2.prueba.com -u root password 12345

-Mas software necesitado

yum install rpm-build pcre-devel

-Instalamos Cyrus para la encriptacion en la autenticacion

yum install cyrus-sasl-sql cyrus-sasl-devel

-Eliminamos un paquete de Cyrus que no necesitaremos

yum remove cyrus-sasl-gssapi

-Agregamos el repositorio dag para contar con paquetes que no están en los de centos. Desabilitado para que no se actualice algo que no queremos

vi /etc/yum.repos.d/dag.repo

[dag]
name=Dag RPM Repository for Red Hat Enterprise Linux
baseurl=http://apt.sw.be/redhat/el$releasever/en/$basearch/dag
gpgcheck=1
enabled=0
-Descargamos postfix con soporte para mysql. Podemos buscar la ultima version en http://rpm.pbone.net/ y descargar la versión dependiendo de nuestra version de centos

wget -c ftp://mirror.switch.ch/pool/3/mirror/centos/5.2/centosplus/i386/RPMS/postfix-2.3.3-2.el5.centos.mysql_pgsql.i386.rpm

-Instalamos postgresql debido a dependencia con el rpm de postfix

yum install postgresql
rpm -vi postfix-2.3.3-2.el5.centos.mysql_pgsql.i386.rpm

-Instalamos libtool por dependencia con courier

yum install libtool-ltdl-devel

-Creamos un usuario y grupo bajo el cual ejecutara Courier

groupadd vmail -g 1001
useradd vmail -u 1001 -g 1001

-Agregamos este usuario al file sudoers. Entre columnas damos un TAB

visudo
vmail ALL=(ALL) ALL

-Le colocamos password a la cuenta vmail

passwd vmail

-Cambiamos a esta cuenta para instalar unos paquetes desde ella. El password que nos pide es el de la cuenta vmail, al tratar de instalar con el sudo

su vmail
sudo yum install libtool postgresql-devel gdbm-devel pam-devel expect openldap-devel
sudo yum install gamin-devel openldap-servers

-Creamos un árbol de directorios para compilar algunos rpm que necesitaremos

mkdir $HOME/rpm
mkdir $HOME/rpm/SOURCES
mkdir $HOME/rpm/SPECS
mkdir $HOME/rpm/BUILD
mkdir $HOME/rpm/SRPMS
mkdir $HOME/rpm/RPMS
mkdir $HOME/rpm/RPMS/i386
echo "%_topdir $HOME/rpm" >> $HOME/.rpmmacros

-Creamos un directorio para las descargas

mkdir $HOME/downloads; cd $HOME/downloads

-Descargamos los paquetes de Courier

wget http://surfnet.dl.sourceforge.net/sourceforge/courier/courier-authlib-0.58.tar.bz2
wget http://surfnet.dl.sourceforge.net/sourceforge/courier/courier-imap-4.1.1.tar.bz2
wget http://surfnet.dl.sourceforge.net/sourceforge/courier/maildrop-2.0.2.tar.bz2

-Courier nos permite validar conexiones por postgresql, mysql, LDAP, etc antes que solo /etc/passwd. Pasamos a compilarlo

sudo rpmbuild -ta courier-authlib-0.58.tar.bz2

-Instalamos los siguientes rpm generados

cd $HOME/rpm/RPMS/i386/
sudo rpm --install courier-authlib-0.58-1.i386.rpm
sudo rpm --install courier-authlib-devel-0.58-1.i386.rpm
sudo rpm --install courier-authlib-mysql-0.58-1.i386.rpm

-Colocamos acceso total a los directorios bajo rpm para compilar courier-imap server

sudo chmod -R 777 $HOME/rpm/RPMS/
cd $HOME/downloads
rpmbuild -ta courier-imap-4.1.1.tar.bz2
cd $HOME/vmail/rpm/RPMS/i386/
sudo rpm --install courier-imap-4.1.1-1.4.i386.rpm

-Compilamos maildrop que nos permitirá filtrar mails entrantes y salientes a los directorios correctos

cd $HOME/downloads
sudo rpmbuild -ta maildrop-2.0.2.tar.bz2
cd $HOME/rpm/RPMS/i386
sudo rpm --install maildrop-2.0.2.i386.rpm

-Salimos de la cuenta vmail a root y verificamos que seamos root

exit
whoami
root

-Creamos el file para logs de maildrop

touch /var/log/maildroprc.log
chmod 777 /var/log/maildroprc.log

-Generamos los certificados usados por Postfix (para SMTPS y TLS), Courier (para IMAPS y POP3S) y Apache (para HTTPS)

mkdir /usr/local/ssl; cd /usr/local/ssl

-La llave sera sin password evitando que cuando iniciemos postfix, courier o apache pida el password

openssl genrsa -out mail.yourdomain.com.key 1024
Generating RSA private key, 1024 bit long modulus
.....................++++++
.......................++++++
e is 65537 (0x10001)

chmod 600 mail.yourdomain.com.key

-Generamos la solicitud de certificado

openssl req -new -key mail.yourdomain.com.key -out mail.yourdomain.com.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [GB]:CO
State or Province Name (full name) [Berkshire]:Cundinamarca
Locality Name (eg, city) [Newbury]:Bogota
Organization Name (eg, company) [My Company Ltd]:Cabrera ltda
Organizational Unit Name (eg, section) []:Soporte Sistemas
Common Name (eg, your name or your server's hostname) []:mail.yourdomain.com
Email Address []:postmaster@yourdomain.com


Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:password
An optional company name []:

-El fichero generado es el necesario para que nos creen un certificado real las Certificate Authority como Verisign o Thawte, en nuestro caso, lo firmaremos nosotros mismos

openssl genrsa -des3 -out ca.key 1024
Generating RSA private key, 1024 bit long modulus
........................................................++++++
...............++++++
e is 65537 (0x10001)
Enter pass phrase for ca.key:
Verifying - Enter pass phrase for ca.key:

-Restringimos sus permisos

chmod 600 ca.key

-Generamos un certificado auto firmado

openssl req -new -x509 -days 365 -key ca.key -out ca.crt
Enter pass phrase for ca.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [GB]:CO
State or Province Name (full name) [Berkshire]:Cundinamarca
Locality Name (eg, city) [Newbury]:Bogota
Organization Name (eg, company) [My Company Ltd]:Cabrera ltda
Organizational Unit Name (eg, section) []:Sistemas Soporte
Common Name (eg, your name or your server's hostname) []:mail.yourdomain.com
Email Address []:postmaster@yourdomain.com

-Usamos este CA certificado para firmar nuestro certificado

openssl x509 -req -days 365 -CA ca.crt -CAkey ca.key -set_serial 01 -in mail.yourdomain.com.csr -out mail.yourdomain.com.crt

Signature ok
subject=/C=CO/ST=Bogota/L=Cundinamarca/O=Cabrera ltda/OU=Sistemas Soporte/CN=mail.yourdomain.com/emailAddress=postmaster@yourdomain.com
Getting CA Private Key
Enter pass phrase for ca.key:

-Combinamos el server key y el certificado en un unico fichero. Postfix y Apache pueden manejar 2 ficheros pero Courier necesita solo uno. Asi que crearemos un fichero unico para todo. Crearemos el pem en el formato esperado por Courier (key y cert en un unico fichero)

cat mail.yourdomain.com.key mail.yourdomain.com.crt > mail.yourdomain.com.pem
chmod 600 mail.yourdomain.com.pem

-Si todo va bien, debe tener algo parecido

ls -la
total 32
drwxr-xr-x 2 root root 4096 sep 8 17:38 .
drwxr-xr-x 12 root root 4096 sep 8 17:00 ..
-rw-r--r-- 1 root root 1375 sep 8 17:24 ca.crt
-rw------- 1 root root 951 sep 8 17:20 ca.key
-rw-r--r-- 1 root root 993 sep 8 17:30 mail.yourdomain.com.crt
-rw-r--r-- 1 root root 761 sep 8 17:09 mail.yourdomain.com.csr
-rw------- 1 root root 887 sep 8 17:02 mail.yourdomain.com.key
-rw------- 1 root root 1880 sep 8 17:38 mail.yourdomain.com.pem

-Instalamos y configuramos postfixadmin

cd /var/www/html
yum install subversion
svn co https://postfixadmin.svn.sourceforge.net/svnroot/postfixadmin/trunk postfixadmin
cd postfixadmin
chmod 640 *.php
cd admin
chmod 640 *.php
cd ../images/
chmod 640 *.png
cd ../languages/
chmod 640 *.lang
cd ../templates/
chmod 640 *.php
cd ../users/
chmod 640 *.php

-Creamos la db en el server MySQL segun el INSTALL.TXT

mysql -u root -p
CREATE DATABASE postfix;
CREATE USER 'postfix'@'localhost' IDENTIFIED BY 'choose_a_password';
GRANT ALL PRIVILEGES ON `postfix` . * TO 'postfix'@'localhost';
exit

-Configuramos postfixadmin
cd /var/www/html/postfixadmin
yum install php-cli php-ldap php-mysql php-gd php php-pear php-pdo php-common php-devel php5-mbstring php5-imap php-mbstring.i386
yum install php-imap php-odbc php-xml php-xmlrpc curl curl-devel perl-libwww-perl ImageMagick libxml2 libxml2-devel
vi config.inc.php

if (ereg ("config.inc.php", $_SERVER['PHP_SELF']))
{
header ("Location: login.php");
exit;
}
$CONF['configured'] = true;
$CONF['postfix_admin_url'] = 'http://192.168.1.197/postfixadmin';
$CONF['postfix_admin_path'] = dirname(__FILE__);
$CONF['default_language'] = 'en';
$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = '192.168.1.198';
$CONF['database_user'] = 'postfix';
$CONF['database_password'] = 'poiuytha';
$CONF['database_name'] = 'postfix';
$CONF['database_prefix'] = '';
$CONF['database_prefix'] = '';
$CONF['database_tables'] = array (
'admin' => 'admin',
'alias' => 'alias',
'alias_domain' => 'alias_domain',
'config' => 'config',
'domain' => 'domain',
'domain_admins' => 'domain_admins',
'fetchmail' => 'fetchmail',
'log' => 'log',
'mailbox' => 'mailbox',
'vacation' => 'vacation',
'vacation_notification' => 'vacation_notification',
);
$CONF['admin_email'] = 'postmaster@yourdomain.com';
$CONF['smtp_server'] = 'localhost';
$CONF['smtp_port'] = '25';
$CONF['encrypt'] = 'md5crypt';
$CONF['min_password_length'] = 8;
$CONF['generate_password'] = 'YES';
$CONF['show_password'] = 'YES';
$CONF['page_size'] = '200';
$CONF['default_aliases'] = array (
'abuse' => 'abuse@yourdomain.com',
'hostmaster' => 'hostmaster@yourdomain.com',
'postmaster' => 'postmaster@yourdomain.com',
'webmaster' => 'webmaster@yourdomain.com'
);
$CONF['domain_path'] = 'NO';
$CONF['domain_in_mailbox'] = 'YES';
$CONF['aliases'] = '10';
$CONF['mailboxes'] = '10';
$CONF['maxquota'] = '100';
$CONF['quota'] = 'YES';
$CONF['quota_multiplier'] = '1024000';
$CONF['transport'] = 'NO';
$CONF['transport_options'] = array (
'virtual', // for virtual accounts
'local', // for system accounts
'relay' // for backup mx
);
$CONF['transport_default'] = 'virtual';
$CONF['vacation'] = 'YES';
$CONF['vacation_domain'] = 'autoreply.yourdomain.com';
$CONF['vacation_control'] ='YES';
$CONF['vacation_control_admin'] = 'YES';
$CONF['alias_control'] = 'YES';
$CONF['alias_control_admin'] = 'NO';
$CONF['special_alias_control'] = 'NO';
$CONF['alias_goto_limit'] = '0';
$CONF['alias_domain'] = 'YES';
$CONF['backup'] = 'YES';
$CONF['sendmail'] = 'YES';
$CONF['logging'] = 'YES';
$CONF['fetchmail'] = 'YES';
$CONF['fetchmail_extra_options'] = 'NO';
$CONF['show_header_text'] = 'NO';
$CONF['header_text'] = ':: Postfix Admin ::';
$CONF['user_footer_link'] = "http://www.yourdomain.com/";
$CONF['show_footer_text'] = 'YES';
$CONF['footer_text'] = 'Return to www.yourdomain.com';
$CONF['footer_link'] = 'http://www.yourdomain.com/';
$CONF['welcome_text'] = <<
Hi,

Welcome to your new account.
EOM;
$CONF['emailcheck_resolve_domain']='YES';
$CONF['show_status']='YES';
$CONF['show_status_key']='YES';
$CONF['show_status_text']=' ';
$CONF['show_undeliverable']='NO';
$CONF['show_undeliverable_color']='tomato';
$CONF['show_undeliverable_exceptions']=array("unixmail.domain.ext","exchangeserver.domain.ext","gmail.com");
$CONF['show_popimap']='YES';
$CONF['show_popimap_color']='darkgrey';
$CONF['show_custom_count']=2;
$CONF['show_custom_domains']=array("subdomain.domain.ext","domain2.ext");
$CONF['show_custom_colors']=array("lightgreen","lightblue");
$CONF['mailbox_postcreation_script']='sudo /usr/local/bin/postfixadmin-mailbox-postcreation.sh';
$CONF['mailbox_postdeletion_script']='sudo /usr/local/bin/postfixadmin-mailbox-postdeletion.sh';
$CONF['domain_postdeletion_script']='sudo /usr/local/bin/postfixadmin-domain-postdeletion.sh';
$CONF['create_mailbox_subdirs_prefix']='INBOX.';
$CONF['theme_logo'] = 'images/logo-default.png';
$CONF['theme_css'] = 'css/default.css';
if (file_exists(dirname(__FILE__) . '/config.local.php')) { # for /
include(dirname(__FILE__) . '/config.local.php');
}

-Habilitamos permisos para apache

chown -R apache.apache /var/www/html/postfixadmin

mv setup.php setup.php-disabled
cp /var/www/html/postfixadmin/ADDITIONS/postfixadmin* /usr/local/bin
cd /usr/local/bin
chown root.root
postfixadmin*
chmod 744 postfixadmin*

-Modificamos o agregamos las siguientes lineas en estos 3 scripts

vi postfixadmin-mailbox-postcreation.sh

basedir=/opt/mail
..
..
maildirmake "$maildir"
chown -R vmail:vmail $maildir

Salvamos y salimos

vi postfixadmin-mailbox-postdeletion.sh

basedir=/opt/mail
trashbase=/opt/deleted
..
..
maildir="${basedir}/${1}"
..
..
mv $maildir $trashdir
chown -R vmail:vmail $trashdir

Salvamos y salimos

vi postfixadmin-domain-postdeletion.sh

basedir=/opt/mail
trashbase=/opt/deleted

Salvamos y salimos

-Accedemos a la interfaz administrativa de postfixadmin. Pero aun no creamos dominios y cuentas:

http://192.168.1.197/postfixadmin/




-Configuramos SASL para SMTP-AUTH

vi /usr/lib/sasl2/smtpd.conf

# smtpd.conf
pwcheck_method: authdaemond
log_level: 3
mech_list: PLAIN LOGIN
authdaemond_path:/var/spool/authdaemon/socket

Salvamos y salimos

chown root.vmail /usr/lib/sasl2/smtpd.conf
chmod 640 /usr/lib/sasl2/smtpd.conf
chmod 755 /var/spool/authdaemon/

-Comenzamos a configurar postfix

cd /etc/postfix

-Modificamos master.cf

vi master.cf

#descomentamos smtps para tener smtp sobre SSL
smtps inet n - n - - smtpd
-o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes

#habilitamos otro puerto para el smtp para los casos cuando los ISP bloquean el puerto 25 SMTP
567 inet n - n - - smtpd

#Modificamos la linea del maildrop
maildrop unix - n n - - pipe
flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#agregamos al final el modulo de vacation
#
# VIRTUAL VACATION
#
vacation unix - n n - - pipe
flags=DRhu user=vacation argv=/var/spool/vacation/vacation.pl -f ${sender} -- ${recipient}

-Salvamos y salimos

-Agregamos el usuario para ejecutar el script de vacation. Por motivos de seguridad, no necesitamos que tenga shell asignado, nadie se logeara por esta cuenta

adduser -d /var/spool/vacation -s /sbin/nologin vacation

-Editamos /etc/passwd y le colocamos un * al campo password del usuario vacation, asi evitamos que alguien coloque un password a esta cuenta para despues usarla.

vi /etc/passwd
vacation:*:1002:1002::/var/spool/vacation:/sbin/nologin
-Copiamos el script y le cambiamos sus privilegios

cp /var/www/html/postfixadmin/VIRTUAL_VACATION/vacation.pl /var/spool/vacation/vacation.pl
chown vacation.vacation /var/spool/vacation/vacation.pl
chmod 700 /var/spool/vacation/vacation.pl

vi /var/spool/vacation/vacation.pl

my $db_type = 'mysql';
my $db_host = '192.168.1.198';
my $db_username = 'postfixadmin';
my $db_password = 'postfixadmin';
my $db_name = 'postfix';
my $vacation_domain = 'autoreply.example.org';
my $smtp_server = 'localhost';
my $syslog = 0;
my $logfile='/var/spool/vacation/vacation.log';
my $log_level = 2;
my $interval = 0;

vi /etc/postfix/transport
autoreply.yourdomain.com vacation

postmap /etc/postfix/transport

-Instalamos por dependencias con perl

yum install links ncftp

-Entramos a webmin para agregar unos modulos perl que necesitamos para vacation

https://192.168.1.197:10000/

-Vamos a Others - Perl. Modulos a instalar (ademas de los que se instalan por default en Centos):

CPAN::Bundle
DBD::mysql
Mail::Sendmail
Email::Valid
MIME::Charset
Log::Log4perl
Log::Dispatch
MIME::EncWords
GetOpt::Std
Net::Server
IO::Multiplex

-Modificamos main.cf

cd /etc/postfix
vi main.cf
myhostname = mail.yourdomain.com
mydomain = yourdomain.com
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost
local_recipient_maps = proxy:unix:passwd.byname $alias_maps
mynetworks = $config_directory/mynetworks
relay_domains = mysql:/etc/postfix/mysql_relay_domains_maps.cf
alias_database = hash:/etc/aliases

-Agregamos al final del fichero

#
# Virtual Mail Mysql settings
#
virtual_alias_maps = hash:/etc/aliases mysql:/etc/postfix/mysql_virtual_alias_maps.cf hash:/etc/aliases
virtual_uid_maps = static:1001
virtual_gid_maps = static:1001
virtual_mailbox_base = /opt/mail
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 = 1001

# Who handles the mail delivery?
# POSTFIX = virtual
# MAILDROP = maildrop
#
#virtual_transport = virtual
virtual_transport = maildrop
maildrop_destination_recipient_limit = 1
# Transport map
transport_maps = hash:/etc/postfix/transport
vacation_destination_recipient_limit = 1
# Additional for quota support
virtual_create_maildirsize = yes
virtual_mailbox_extended = yes
virtual_mailbox_limit_maps = mysql:/etc/postfix/mysql_virtual_mailbox_limit_maps.cf
virtual_mailbox_limit_override = yes
virtual_maildir_limit_message = Sorry, the user's maildir has overdrawn his diskspace quota, please try again later.

###################################################################################
### ENABLE SASL SUPPORT ( SMTP-AUTH )
# smtpd_sasl_auth_enable = yes
# Enable SASL support in postfix
# smtpd_sasl_security_options = noanonymous
# Anonymous logins will not be permitted
# broken_sasl_auth_clients = yes
# Allow RFC-broken mail clients like Outlook Express4 to use SMTP AUTH
# smtpd_sasl_path = smptd
# Tells SASL to get the config from /usr/lib64/sasl2/smptd.conf
# smtpd_sasl_local_domain =
# If the user fails to nominate a domain, don't auto append one
# smtpd_sasl_authenticated_header = yes
# Include the authenticated username in the message headers.
# Having this on will make it easier if a spammer cracks one of your user's weak passwords,
# and starts using SMTP-AUTH to relay spam through your server
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_sasl_path = smptd
smtpd_sasl_local_domain =
smtpd_sasl_authenticated_header = yes
smtpd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_non_fqdn_hostname,reject_non_fqdn_sender,reject_non_fqdn_recipient,reject_unauth_destination,reject_unauth_pipelining,reject_invalid_hostname,reject_rbl_client list.dsbl.org,reject_rbl_client bl.spamcop.net,reject_rbl_client sbl-xbl.spamhaus.org
###################################################################################
### ENABLE TLS SUPPORT ( "STARTTLS" ... enables SSL to be negotiated during a SMTP connection )
# smtp_use_tls = no
# dont enable TLS for outbound SMTP connections
# smtpd_use_tls = yes
# announce TLS availability for incoming SMTP connections
# smtpd_tls_auth_only = no :
# TLS is optional, not enforced
# smtpd_tls_key_file :
# specify the private key ( must not be encrypted - ie no password)
# smtpd_tls_cert_file :
# specify the certificate
# smtpd_tls_session_cache_database :
# nominate a server-side TLS session cache. Improves performance.
# smtpd_tls_loglevel = 1 :
# log basic TLS handshake and cert info
# smtpd_tls_received_header = yes
# record some protocol/cipher etc info in the Received header smtp_use_tls = no
smtp_use_tls = no
smtpd_use_tls = yes
smtpd_tls_auth_only = no
smtpd_tls_key_file = /usr/local/ssl/mail.yourdomain.com.key
smtpd_tls_cert_file = /usr/local/ssl/mail.yourdomain.com.crt
smtpd_tls_session_cache_database = btree:/etc/postfix/tls_smtpd_scache
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_client_restrictions = check_client_access hash:/etc/postfix/access
smtpd_client_connection_count_limit = 60

-Creamos los ficheros mysql-virtual

vi /etc/postfix/mysql_virtual_alias_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
query = SELECT goto FROM alias WHERE address='%s' AND active = 1

vi /etc/postfix/mysql_virtual_domains_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s'
#optional query to use when relaying for backup MX
#query = SELECT domain FROM domain WHERE domain='%s' and backupmx = '0' and active = '1'

vi /etc/postfix/mysql_virtual_mailbox_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = 1

vi /etc/postfix/mysql_virtual_mailbox_limit_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
query = SELECT quota FROM mailbox WHERE username='%s'

vi /etc/postfix/mysql_relay_domains_maps.cf
user = postfix
password = postfix
hosts = localhost
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s' and backupmx = '1'

-Como estos files contienen datos de conexion a nuestra db, limitamos su acceso por seguridad

chown root.postfix /etc/postfix/mysql_*.cf
chmod 640 /etc/postfix/mysql_*.cf
ls -la /etc/postfix/mysql*
-rw-r----- 1 root postfix 140 sep 15 15:54 /etc/postfix/mysql_relay_domains_maps.cf
-rw-r----- 1 root postfix 134 sep 15 15:48 /etc/postfix/mysql_virtual_alias_maps.cf
-rw-r----- 1 root postfix 261 sep 15 15:51 /etc/postfix/mysql_virtual_domains_maps.cf
-rw-r----- 1 root postfix 123 sep 15 15:53 /etc/postfix/mysql_virtual_mailbox_limit_maps.cf
-rw-r----- 1 root postfix 140 sep 15 15:52 /etc/postfix/mysql_virtual_mailbox_maps.cf

-Colocamos las ip de los servers que haran relay a traves de nuestro server. Los usuarios que tengan cuenta en el server no necesitan tener su ip aqui, ya que ellos se logearan por SMTP-AUTH, por default colocamos localhost para darle permiso a los scripts locales en el server

echo '# Localhost' > /etc/postfix/mynetworks
echo '127.0.0.0/8' >>/etc/postfix/mynetworks
echo '' >>/etc/postfix/mynetworks

-Creacion del directorio de mail para los usuarios. Existen 2 formatos de guardar sus mails, Mbox que es un fichero donde se almacenan todos los mails, uno detras del otro y Maildir que almacena los mails cada uno en un directorio especial. Para este documento usaremos Maildir

mkdir /opt/mail
chown vmail:vmail /opt/mail
chmod 700 /opt/mail
mkdir /opt/deleted
chown vmail:vmail /opt/deleted/
chmod 700 /opt/deleted/

-Configuramos Courier-authlib para manejar Courier-IMAP y Courier-POP3

vi /etc/authlib/authdaemonrc
authmodulelist="authmysql"
authdaemonvar=/usr/var/spool/authdaemon
DEFAULTOPTIONS="wbnochangepass=1,wbusexsender=1,disableshared=1"

vi /etc/authlib/authmysqlrc
MYSQL_SERVER 192.168.1.198
MYSQL_USERNAME root
#password de la cuenta root de mysql
MYSQL_PASSWORD 12345
MYSQL_SOCKET /var/lib/mysql/mysql.sock
MYSQL_PORT 0
MYSQL_OPT 0
MYSQL_DATABASE postfix
MYSQL_USER_TABLE mailbox
MYSQL_CRYPT_PWFIELD password
MYSQL_CLEAR_PWFIELD password
MYSQL_UID_FIELD '1001'
MYSQL_GID_FIELD '1001'
MYSQL_LOGIN_FIELD username
MYSQL_HOME_FIELD '/opt/mail'
MYSQL_NAME_FIELD name
MYSQL_MAILDIR_FIELD CONCAT("/opt/mail/",maildir)
MYSQL_QUOTA_FIELD concat(quota,'S')

-Protegemos el fichero

chmod 400 /etc/authlib/authmysqlrc

-Comenzamos a configurar Maildrop con Maildir+softquota

vi /etc/quotawarnmsg
X-Comment: Rename/Copy this file to quotawarnmsg, and make appropriate changes
X-Comment: See deliverquota man page for more information
From: Mail Delivery System
Reply-To: postmaster@calcom.com.mx
To: Valued Customer:;
Subject: Mail quota warning
Mime-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 7bit
Your mailbox on the server is now more than 90% full. So that you can continue to receive mail you need to remove some messages from your mailbox.

vi /etc/postfix/master.cf
maildrop unix - n n - - pipe
flags=DRhu user=vmail argv=/usr/bin/maildrop -w 90 -d ${recipient}
#-w N dara un alerta por mail al usuario cuando su quota de disco este al N porciento lleno
#repitiendose esta alerta todos los dias hasta que libere espacio. El mensaje se toma de
#/etc/quotawarnmsg con los campos "Date:" y "Message-Id:" actualizados

-Salvamos y salimos. Reiniciamos el servicio postfix

chkconfig sendmail off
service sendmail stop
chkconfig postfix on
service postfix restart

vi /etc/maildroprc
logfile "/var/log/maildroprc.log"

-Configuramos Courier-IMAP Courier-POP3

vi /usr/lib/courier-imap/etc/imapd
MAXPERIP=20
IMAP_CAPABILITY="IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA AUTH=CRAM-MD5 AUTH=CRAM-SHA1 AUTH=PLAIN AUTH=LOGIN IDLE"
IMAP_ACL=0
IMAP_CAPABILITY_TLS="$IMAP_CAPABILITY"
IMAP_ENHANCEDIDLE=1
IMAPDSTART=YES

vi /usr/lib/courier-imap/etc/imapd-ssl
IMAPDSSLSTART=YES
IMAPDSTARTTLS=YES
#certificado creado anteriormente
TLS_CERTFILE=/usr/local/ssl/mail.yourdomain.com.pem

vi /usr/lib/courier-imap/etc/pop3d
MAXDAEMONS=40
POP3AUTH="CRAM-MD5 CRAM-SHA1 PLAIN LOGIN"
POP3AUTH_TLS="$POP3AUTH"
POP3DSTART=YES

vi /usr/lib/courier-imap/etc/pop3d-ssl
POP3DSSLSTART=YES
POP3_STARTTLS=YES
TLS_CERTFILE=/usr/local/ssl/mail.yourdomain.com.pem

-Ejecutamos y verificamos que los daemons necesarios estan ok

service mysqld start
service saslauthd start
service saslauthd start
service courier-authlib start
service courier-imap start
service postfix restart

-Modificaciones a postfixadmin
Normalmente para crear los maildir para las cuentas de email necesitaremos algunos comandos, aunque modificarmos el postfixadmin para que haga el trabajo sucio por nosotros.
Este es un ejemplo de como hacerlo manualmente

Creacion del home maildir de una cuenta email:
maildirmake /opt/mail/user1@yourdomain.com

Le creamos una quota de disco, si no esta presente, no hay restriccion de espacio, en este caso son 10MB y fijese en la S que colocamos al final del numero:
maildirmake -q 10971520S /opt/mail/user1@yourdomain.com

Protegemos el directorio
chmod g-r,o-r /opt/mail/user1\@yourdomain.com/
chown -R vmail.vmail /opt/mail/user1\@yourdomain.com/

-Damos permiso a los scripts para crear usuarios y dominios y borrarlos desde postfixadmin

visudo
#comentamos requiretty
#Defaults requiretty
..
..
vmail ALL=(ALL) ALL
apache mail.yourdomain.com=NOPASSWD: /usr/local/bin/postfixadmin-mailbox-postcreation.sh
apache mail.yourdomain.com=NOPASSWD: /usr/local/bin/postfixadmin-mailbox-postdeletion.sh
apache mail.yourdomain.com=NOPASSWD: /usr/local/bin/postfixadmin-domain-postdeletion.sh

service postfix restart

-Manejo de la cola de emails en postfix por linea de comandos

postqueue -p

-Poner un mensaje en HOLD. MESSAGEID es un identificador unico dado por postfix al colocar el mail en cola, para marcar todos los mails escribimos ALL

postsuper -h MESSAGEID

-Eliminar un mail de la cola

postsuper -d MESSAGEID

-Eliminar todos los mails en la cola

postsuper -d ALL

-Verificamos permisos de los files del postfix

postfix check

-Verificamos otros errores

egrep '(reject|warning|error|fatal|panic):' /var/log/maillog

-Verificamos los valores de Courier-authlib. Mostramos las cuentas creadas

vi /etc/authlib/authdaemonrc
DEBUG_LOGIN=2

-Reiniciamos el daemon

service courier-authlib restart

-Listamos las cuentas
/usr/sbin/authenumerate
user2@yourdomain.com 1001 1001 /opt/mail /opt/mail/user2@yourdomain.com/

-Verificamos por linea de comandos una cuenta

/usr/sbin/authtest someuser@yourdomain.com somepassword
Authentication succeeded.

Authenticated: someuser@yourdomain.com (uid 1001, gid 1001)
Home Directory: /opt/mail
Maildir: /opt/mail/someuser@yourdomain.com/
Quota: 10240000S
Encrypted Password: $1$9625a822$9wBt3mVsXm9oMbbO49HVX/
Cleartext Password: somepassword
Options: wbnochangepass=1,wbusexsender=1,disableshared=1

-Cuando estemos seguro de que Courier-authlib este funcionando ok, desabilitamos el modo debug o podemos llenar nuestro disco con mensajes de log

vi /etc/authlib/authdaemonrc
DEBUG_LOGIN=0

service courier-authlib restart

-Verificamos el servicio POP3

telnet localhost pop3
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
+OK Hello there.
user user2@yourdomain.com
+OK Password required.
pass 12345
+OK logged in.
stat
+OK 0 0
quit
+OK Bye-bye.
Connection closed by foreign host.

-Verificamos IMAP

telnet localhost imap
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA IDLE ACL ACL2=UNION STARTTLS] Courier-IMAP ready. Copyright 1998-2005 Double Precision, Inc. See COPYING for distribution information.
a login user2@yourdomain.com 12345
a OK LOGIN Ok.
a examine inbox
* FLAGS (\Draft \Answered \Flagged \Deleted \Seen \Recent)
* OK [PERMANENTFLAGS ()] No permanent flags permitted
* 0 EXISTS
* 0 RECENT
* OK [UIDVALIDITY 1221862032] Ok
* OK [MYRIGHTS "cdilrsw"] ACL
a OK [READ-ONLY] Ok
a logout
* BYE Courier-IMAP server shutting down
a OK LOGOUT completed
Connection closed by foreign host.

-Verificamos Maildrop

maildrop -V9 -d user2@yourdomain.com
maildrop: authlib: groupid=1001
maildrop: authlib: userid=1001
maildrop: authlib: logname=user2@yourdomain.com, home=/opt/mail, mail=/opt/mail/user2@yourdomain.com/
maildrop: Changing to /opt/mail

Ya con postfix funcionando ok, pasaremos a instalar y configurar MailScanner. MailScanner es un software opensource que integra soporte antispam con spamassassin y antivirus con clamav entre otros antivirus.

-Antes de comenzar paramos el servicio postfix

service postfix stop
service saslauthd stop

mkdir /var/spool/postfix/usr
mkdir /var/spool/postfix/usr/var
mkdir /var/spool/postfix/var/
mkdir /var/spool/postfix/var/spool
mv /var/spool/authdaemon/ /var/spool/postfix/var/spool/authdaemon
ln -s /var/spool/postfix/var/spool/authdaemon/ /var/spool/authdaemon

-Reiniciamos postfix y saslauthd

service postfix start
service saslauthd start

-Cambiamos la configuracion del postfix para que trabaje en modo split MTA

vi /etc/postfix/main.cf

header_checks = regexp:/etc/postfix/header_checks

vi /etc/postfix/header_check

/^Received:/ HOLD

-Descargamos MailScanner

cd /home/vmail/downloads/
wget -c http://www.mailscanner.info/files/4/rpm/MailScanner-4.72.2-1.rpm.tar.gz
gunzip -d MailScanner-4.72.2-1.rpm.tar.gz
tar xvf MailScanner-4.72.2-1.rpm.tar
cd MailScanner-4.72.2-1

-Ejecutamos el script de install, OJO, colocamos un . punto antes del /
./install.sh

-Prestamos atencion que se instalen bien HTML-Parser y MIME-tools. Es normal que veamos algunos errores. Pero estos 2 modulos si deben quedar instalados. Ctrl-S para temporalmente la ejecucion para darnos tiempo a anotar algun error o modulo faltante para despues instalarlo y Ctrl-Q continua. Si algun modulo perl da error por falta de otro modulo, tomamos nota y lo instalamos despues al terminar el install.sh y volvemos a ejecutarlo.

-Modificamos los siguientes parametros en MailScanner.conf

cd /etc/MailScanner
vi MailScanner.conf

Run As User = postfix
Run As Group = postfix
Incoming Queue Dir = /var/spool/postfix/hold
Outgoing Queue Dir = /var/spool/postfix/incoming
MTA = postfix
SpamAssassin User State Dir = /var/spool/MailScanner/spamassassin

-Preparamos el directorio bayes
mkdir /etc/MailScanner/bayes
chmod g+rws /etc/MailScanner/bayes
chown root.apache /etc/MailScanner/bayes

-Descargamos e instalamos spamassassin y clamav (antispam-antivirus)

cd /home/vmail/downloads/

-Creamos una cuenta para clamav pero sin home y sin que se pueda logear
adduser -Ms /sbin/nologin clamav

wget -c http://www.mailscanner.info/files/4/install-Clam-SA-latest.tar.gz
gunzip -d install-Clam-SA-latest.tar.gz
tar xvf install-Clam-SA-latest.tar
cd install-Clam-0.94-SA-3.2.5/
./install.sh

-Respondemos y en:
Do you want me to install ClamAV for you [y or n, default is y] ? y

-Habilitamos algunos pluggins de spamassassin
vi /etc/mail/spamassassin/v320.pre

loadplugin Mail::SpamAssassin::Plugin::Check
loadplugin Mail::SpamAssassin::Plugin::HTTPSMismatch
loadplugin Mail::SpamAssassin::Plugin::URIDetail
loadplugin Mail::SpamAssassin::Plugin::Shortcircuit
loadplugin Mail::SpamAssassin::Plugin::Bayes
loadplugin Mail::SpamAssassin::Plugin::BodyEval
loadplugin Mail::SpamAssassin::Plugin::DNSEval
loadplugin Mail::SpamAssassin::Plugin::HTMLEval
loadplugin Mail::SpamAssassin::Plugin::HeaderEval
loadplugin Mail::SpamAssassin::Plugin::MIMEEval
loadplugin Mail::SpamAssassin::Plugin::RelayEval
loadplugin Mail::SpamAssassin::Plugin::URIEval
loadplugin Mail::SpamAssassin::Plugin::WLBLEval
loadplugin Mail::SpamAssassin::Plugin::VBounce
loadplugin Mail::SpamAssassin::Plugin::ImageInfo
loadplugin Mail::SpamAssassin::Plugin::RelayCountry
loadplugin Mail::SpamAssassin::Plugin::SPF
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL
loadplugin Mail::SpamAssassin::Plugin::Razor2

vi /etc/mail/spamassassin/v310.pre
loadplugin Mail::SpamAssassin::Plugin::DCC
loadplugin Mail::SpamAssassin::Plugin::Pyzor
loadplugin Mail::SpamAssassin::Plugin::Razor2
loadplugin Mail::SpamAssassin::Plugin::SpamCop
loadplugin Mail::SpamAssassin::Plugin::AWL
loadplugin Mail::SpamAssassin::Plugin::AutoLearnThreshold
loadplugin Mail::SpamAssassin::Plugin::TextCat
loadplugin Mail::SpamAssassin::Plugin::WhiteListSubject
loadplugin Mail::SpamAssassin::Plugin::DomainKeys
loadplugin Mail::SpamAssassin::Plugin::MIMEHeader
loadplugin Mail::SpamAssassin::Plugin::ReplaceTags
loadplugin Mail::SpamAssassin::Plugin::RelayCountry
loadplugin Mail::SpamAssassin::Plugin::SPF
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL

vi /etc/mail/spamassassin/init.pre
loadplugin Mail::SpamAssassin::Plugin::RelayCountry
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL
loadplugin Mail::SpamAssassin::Plugin::Hashcash
loadplugin Mail::SpamAssassin::Plugin::SPF
loadplugin Mail::SpamAssassin::Plugin::Razor2

-Activamos el spamassassin y clamav en MailScanner.conf

vi /etc/MailScanner/MailScanner.conf
Use SpamAssassin = yes
Incoming Work User = clamav
Incoming Work Group = clamav
Clamd Socket = /tmp/clamd.socket
Incoming Work Permissions = 0660
Quarantine User = root
Quarantine Group = apache
Quarantine Permissions = 0660
Quarantine Whole Message = yes
Spam Actions = store
Always Looked Up Last = MailWatchLogging
Is Definitely Not Spam = SQLWhitelist
Is Definitely Spam = SQLBlacklist

vi /etc/MailScanner/spam.assassin.prefs.conf
bayes_path /etc/MailScanner/bayes/bayes
bayes_file_mode 0660

-Instalamos y configuramos razor, dcc y pyzor

cd /home/vmail/downloads/
wget -c http://internap.dl.sourceforge.net/sourceforge/razor/razor-agents-sdk-2.07.tar.bz2
wget -c http://internap.dl.sourceforge.net/sourceforge/razor/razor-agents-2.84.tar.bz2
bunzip2 razor-agents-sdk-2.07.tar.bz2
bunzip2 razor-agents-2.84.tar.bz2
tar xvf razor-agents-sdk-2.07.tar
tar xvf razor-agents-2.84.tar

-Verificamos tengamos los siguientes modulos perl instalados:

Time::HiRes
Digest::SHA1
MIME::Base64
Test::Simple
Test::Harness
Getopt::Long
Business::ISBN
GD::Barcode::EAN13
URI::Escape

-Compilamos e instalamos razor

cd razor-agents-sdk-2.07
perl Makefile.PL
make
make test
make install

cd ..
cd razor-agents-2.84
perl Makefile.PL
make
make test
make install

-Creamos el usuario razor para sus reportes, como postfix no puede logearse, primero lo creamos en root y despues lo pasamos al home de postfix

cd /root
razor-admin -create
razor-admin -register
cp -rf .razor/ /var/spool/postfix/
chown -R postfix.postfix /var/spool/postfix/.razor/

cd /home/vmail/downloads/
wget -c http://www.rhyolite.com/dcc/source/dcc.tar.Z
uncompress -d dcc.tar.Z
tar xvf dcc.tar
cd dcc-1.3.97/
./configure
make install

cd ..
wget -c http://internap.dl.sourceforge.net/sourceforge/pyzor/pyzor-0.4.0.tar.bz2
bunzip2 -d pyzor-0.4.0.tar.bz2
tar xvf pyzor-0.4.0.tar
cd pyzor-0.4.0
-Para instalar pyzor necesitamos el modulo gdbm de python, verificamos si lo tenemos instalado
python -c 'import gdbm' && echo 'gdbm found'
gdbm found

python setup.py build
python setup.py install
-Le cambiamos los permisos
chmod -R a+rX /usr/share/doc/pyzor /usr/lib/python2.4/site-packages/pyzor /usr/bin/pyzor /usr/bin/pyzord

pyzor discover
cp -rf .pyzor/ /var/spool/postfix/
chown -R postfix.postfix /var/spool/postfix/.pyzor/

chkconfig postfix off
service postfix stop
chkconfig MailScanner on
service MailScanner start

-Descargamos MailWatch

cd /home/vmail/downloads
wget -c http://internap.dl.sourceforge.net/sourceforge/mailwatch/mailwatch-1.0.4.tar.gz
tar xzvf mailwatch-1.0.4.tar.gz
cd mailwatch-1.0.4
mysql -p < create.sql

vi MailWatch.pm
my($db_user) = 'mailwatch';
my($db_pass) = '%sql_user_password%';
#Comentamos la linea 93
#$dbh->commit;

mv MailWatch.pm /usr/lib/MailScanner/MailScanner/CustomFunctions/

mv -rf mailscanner/ /var/www/html/
mkdir /var/www/html/mailscanner/temp/
chown -R apache:apache /var/www/html/mailscanner/
chmod ug+rwx /var/www/html/mailscanner/images/ /var/www/html/mailscanner/images/cache/
chmod ug+rw /var/www/html/mailscanner/temp/

vi /var/www/html/mailscanner/conf.php.example
define(DB_USER, 'mailwatch');
define(DB_PASS, '%sql_user_password%');
define(QUARANTINE_USE_FLAG, true);

mv /var/www/html/mailscanner/conf.php.example /var/www/html/mailscanner/conf.php
vi SQLBlackWhiteList.pm
my($db_user) = 'mailwatch';
my($db_pass) = '%sql_user_password%';

mv SQLBlackWhiteList.pm /usr/lib/MailScanner/MailScanner/CustomFunctions/

-Creamos el usuario admin para acceder a mailwatch

mysql mailscanner -u mailwatch -p
INSERT INTO users VALUES ('%web_user_username%',md5('%web_user_password%'),'%web_user_name%','A','0','0','0','0','0');
quit;

-Modificamos php.ini

vi /etc/php.ini
short_open_tag ="On"
safe_mode ="Off"
register_globals ="Off"
magic_quotes_gpc ="On"
magic_quotes_runtime ="Off"
auto_start ="0"
allow_url_fopen ="On"
upload_max_filesize ="15M"

-Verificamos haya quedado bien configurado spamassassin. Verificamos si falta algun modulo perl para instalarselo

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

-Modificamos GeoIP para corregir un bug

vi /var/www/html/mailscanner/geoip_update.php

//Cambiamos
dbquery("LOAD DATA INFILE '".$base.'/'.$file2."' INTO TABLE geoip_country FIELDS TERMINATED BY ',' ENCLOSED BY '\"'");

//por
dbquery("LOAD DATA LOCAL INFILE '".$base.'/'.$file2."' INTO TABLE geoip_country FIELDS TERMINATED BY ',' ENCLOSED BY '\"'");

-Modificamos la cuarentena de MailScanner

vi /etc/cron.daily/clean.quarantine
$days_to_keep = 15;

-Modificamos la cuarentena de MailWatch

cd /home/vmail/downloads/mailwatch-1.0.4
vi tools/db_clean.php
#!/usr/bin/php -q

cp tools/quarantine_maint.php /usr/local/bin/
cp tools/db_clean.php /usr/local/bin/
chmod +x /usr/local/bin/quarantine_maint.php /usr/local/bin/db_clean.php

-En una sola linea ejecutamos lo siguiente
echo "/usr/local/bin/quarantine_maint.php --clean" > /etc/cron.daily/mailwatch_quarantine_maint.sh

echo "/usr/local/bin/db_clean.php" > /etc/cron.daily/mailwatch_db_clean.sh
chmod +x /etc/cron.daily/mailwatch*

-Cola de mensajes

cp mailq.php /usr/local/bin/
crontab -e
0-59 * * * * /usr/local/bin/mailq.php

-Liberar un mail de cuarentena y que no sea chequeado nuevamente con los filtros antispam y antivirus. Debemos agregar un registro a la db mailscanner en la tabla whitelist. Los valores serian:

to_address = default
to_domain = default
from_address = 127.0.0.1

-Modificamos algunos ficheros de MailScanner, OJO, los campos son separados por TAB dentro de estos ficheros

cd /etc/MailScanner/
-En una sola linea ejecutamos el siguiente comando
touch filename.rules filetype.rules filename.rules.allowall.conf filetype.rules.allowall.conf rules/content.scanning.rules

vi filename.rules
From: 127.0.0.1 /etc/MailScanner/filename.rules.allowall.conf
FromOrTo: default /etc/MailScanner/filename.rules.conf

vi filetype.rules
From: 127.0.0.1 /etc/MailScanner/filetype.rules.allowall.conf
FromOrTo: default /etc/MailScanner/filetype.rules.conf

vi filename.rules.allowall.conf
allow .* - -

vi filetype.rules.allowall.conf
allow .* - -

vi rules/content.scanning.rules
From: 127.0.0.1 no
FromOrTo: default yes

-Modificamos los permisos para el directorio de cuarentena
chmod g+rws /var/spool/MailScanner/quarantine/

-Instalamos unrar
cd /home/vmail/downloads/
wget -c http://dag.wieers.com/rpm/packages/unrar/unrar-3.7.4-1.el5.rf.i386.rpm
rpm -vi unrar-3.7.4-1.el5.rf.i386.rpm

-Entrada a MailWatch. Nos logeamos con el usuario administrativo que creamos, en el URL http://192.168.1.197/mailscanner

-Personalizamos MailWatch. Actualizamos las definiciones de spamassassin y GeoIP en Tools/Links y con eso nos queda listo nuestro server. En la medida que nuestro server maneje una buena cantidad de mails, mas de 1000, entre spam y ham (mails buenos) este mejorara su porcentaje de efectividad. Share/Bookmark