Configurar un servidor de correos en CentOS 6(Postfix, MySQL, Postfixadmin, Dovecot, Amavisd-new y Clamav)

Esta es una guía bien larga pero muy completa y esta diseñada para que solo copies y pegues cada comando y contenido, a mi me funciona a la perfección pero si a ti te falla en algún punto déjame un comentario.

El objetivo es que tengas un servidor robusto con los siguientes servicios

  • Dominios virtuales en Postfix lo que significa que los buzones no dependen de un usuario en Linux y podrás utilizar el mismo nombre de usuario en diferentes dominios sin compartir el mismo buzón.
  • Interface web para administración de dominios y usuarios con Postfixadmin.
  • Acceso a webmail con Roundcube.
  • Permitir SSL/TLS al configurar cuentas en un cliente de correo para proteger las credenciales.
  • Backend en MySQL.
  • Escaneo de emails con ClamAV y Amavis.

Se asume que usaras una instalación fresca de CentOS 6, yo trabaje sobre una plataforma de 64 bits pero seguro te funcionara a la perfección sobre 32 bits.

1. Configurar Repositorios

Edita el archivo /etc/yum.repos.d/CentOS-Base.repo y activa los repositorios centosplus y contrib cambiando la línea enabled=0 a enabled=1

Agrega los repositorios de rpmforge

wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.i686.rpm
rpm -Uhv rpmforge*

Edita el archivo /etc/yum.repos.d/rpmforge.repo y activa el repositorio rpmforge-extras cambiando la línea enabled=0 a enabled=1

Agrega los repositorios de RPEL

rpm -Uhv http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm

Ahora necesitamos excluir algunos RPMs que tienen problemas de versiones con rpmforge. Para eso agregamos la siguiente línea al final de los repositorios base y updates en el archivo /etc/yum.repos.d/CentOS-Base.repo

exclude=spamassassin*,perl-Compress-Raw-Zlib*,perl-Compress-Raw-Bzip2*

Ahora actualiza el sistema operativo

yum -y update

2. Instalar el software

Instala algunas herramientas y utilidades necesarias

yum -y install gcc gcc-c++ wget bison nano make createrepo screen libmcrypt proftpd caching-nameserver

Instala MySQL

yum -y install mysql mysql-server

Instala Apache y PHP

yum -y groupinstall 'Web Server' 'PHP Support'
yum -y install php-gd php-ncurses php-snmp php-mbstring php-mysql php-devel php-imap php-odbc php-pear php-xml php-xmlrpc php-dba php-pear-DB php-process php-pear-DB php-mcrypt perl-Net-SSLeay

Ahora instala el resto de los paquetes y aplicaciones necesarias

yum -y 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

Ya que no existe un RPM para instalar Postfixadmin lo bajamos manualmente

wget http://sourceforge.net/projects/postfixadmin/files/latest/download
tar -xzvf postfixadmin-ultima.version.tar.gz
mv postfixadmin-ultima.version /usr/share/postfixadmin

3. Configurar el servidor

Configura un certificado SSL

genkey --days 3650 mail.tudominio.com

Sigue las instrucciones

Configura el usuario de correo virtual

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

Configura Postfixadmin

Crea el archivo de configuración de apache para postfixadmin

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

Llénalo con el siguiente contenido:

alias /mailadmin /usr/share/postfixadmin
     <Directory "/usr/share/postfixadmin">
       AllowOverride AuthConfig
     </Directory>

Reinicia apache

service httpd restart

Crea una base de datos en MySQL para postfixadmin

mysql -u root -p -e "CREATE DATABASE postfix;"
mysql -u root -p -e "CREATE USER postfix@localhost IDENTIFIED BY 'tupassword';"
mysql -u root -p -e "GRANT ALL PRIVILEGES ON postfix . * TO postfix@localhost;"

remplaza el contenido del archivo /usr/share/postfixadmin/config.local.php con las siguientes líneas

<?php
/** 
 * Contains configuration options that override the default config file
 */
 
/*****************************************************************
 *  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
 * You have to set $CONF['configured'] = true; before the
 * application will run!
 * Doing this implies you have changed this file as required.
 * i.e. configuring database etc; specifying setup.php password etc.
 */
$CONF['configured'] = true;
 
// In order to setup Postfixadmin, you MUST specify a hashed password here.
// To create the hash, visit setup.php in a browser and type a password into the field,
// on submission it will be echoed out to you as a hashed value.
$CONF['setup_password'] = 'changeme';
$CONF['postfix_admin_url'] = '/mailadmin';
$CONF['postfix_admin_path'] = dirname(__FILE__);
$CONF['default_language'] = 'en';
$CONF['database_type'] = 'mysql';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'postfix';
$CONF['database_password'] = 'changeme';
$CONF['database_name'] = 'postfix';
$CONF['admin_email'] = 'postmaster@tudominio.com';
$CONF['encrypt'] = 'md5crypt';
$CONF['dovecotpw'] = "/usr/sbin/dovecotpw";
$CONF['min_password_length'] = 6;
$CONF['page_size'] = '20';
$CONF['domain_path'] = 'YES';
$CONF['domain_in_mailbox'] = 'NO';
$CONF['aliases'] = '50';
$CONF['mailboxes'] = '50';
$CONF['maxquota'] = '100';
$CONF['quota'] = 'YES';
$CONF['quota_multiplier'] = '1024000';
$CONF['transport'] = 'YES';
$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.tudominio.com';
$CONF['vacation_control'] ='YES';
$CONF['vacation_control_admin'] = 'YES';
$CONF['special_alias_control'] = 'YES';
$CONF['user_footer_link'] = "http://mail.tudominio.com/mailadmin";
$CONF['show_footer_text'] = 'YES';
$CONF['footer_text'] = 'Return to tudominio';
$CONF['footer_link'] = 'http://tudominio.com';
$CONF['create_mailbox_subdirs']=array('Drafts','Spam','Sent','Trash');
$CONF['create_mailbox_subdirs_host']='localhost';
$CONF['create_mailbox_subdirs_prefix']='';
$CONF['used_quotas'] = 'YES';
$CONF['new_quota_table'] = 'YES';
// $CONF['create_mailbox_subdirs_hostoptions']=array('notls');
$CONF['create_mailbox_subdirs_hostoptions']=array('novalidate-cert','norsh');
$CONF['theme_logo'] = 'images/logo-default.png';
$CONF['theme_css'] = 'css/default.css';
 
//
// END OF CONFIG FILE
//

Asegúrate de remplazar las líneas de password y dominio de acuerdo a tu instalación.

Ahora corre el script de configuración desde tu navegador web de la siguiente manera.

http://tudominio.com/mailadmin/setup.php

Si todas las verificaciones se muestran como “OK” entonces sigue las instrucciones para establecer la contraseña de configuración (Setup Password)

Ahora entra a http://tudominio.com/mailadmin/ y sigue las instrucciones.

Configurar Postfix

En esta parte cambiaremos y crearemos muchos archivos de configuración (config files). Para los archivos de configuración existentes asegúrate de remplazar todo el contenido por el que aparece en esta guía y siempre ten en cuenta de remplazar las líneas correspondientes a contraseñas y dominios para que cumplan con tus requisitos.

/etc/postfix/main.cf

# 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
 
# network settings
inet_interfaces = all
mydomain = tudominio.com
myhostname = mail.tudominio.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 
smtpd_tls_security_level = may
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/mail.tudominio.com.key
smtpd_tls_cert_file = /etc/pki/tls/certs/mail.tudominio.com.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
 
# Other            options
# email            size limit ~20Meg
message_size_limit = 204800000

/etc/postfix/master.cf

#
# 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
# -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}

/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

Archivos de configuración para MySQL

/etc/postfix/mysql-virtual_alias_maps.cf

hosts = localhost
user = postfix
password = tupassword
dbname = postfix
query = SELECT goto FROM alias WHERE address='%s' AND active = '1'

/etc/postfix/mysql-virtual_domains_maps.cf

hosts = localhost
user = postfix
password = tupassword
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 = postfix
password = tupassword
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s' and backupmx = '1'

/etc/postfix/mysql-virtual_mailbox_maps.cf

hosts = localhost
user = postfix
password = tupassword
dbname = postfix
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = '1'

/etc/postfix/mysql-virtual_mailbox_limit_maps.cf

hosts = localhost
user = postfix
password = tupassword
dbname = postfix
query = SELECT quota FROM mailbox WHERE username='%s' AND active = '1'

Ahorra corre el siguiente comando.

touch /etc/postfix/virtual_regexp

Para terminar con la configuración de postfix creamos la funcionalidad de respuesta automática o “Vacation email”

Corre la siguiente secuencia de comandos.

useradd -r -d /var/spool/vacation -s /sbin/nologin -c "Virtual vacation" vacation
mkdir /var/spool/vacation 
chmod 770 /var/spool/vacation
cp /usr/share/postfixadmin/VIRTUAL_VACATION/vacation.pl /var/spool/vacation/
echo "autoreply.tudominio.com vacation:" > /etc/postfix/transport 
postmap /etc/postfix/transport
chown -R vacation:vacation /var/spool/vacation
echo "127.0.0.1 autoreply.tudominio.com" >> /etc/hosts 
mkdir /etc/postfixadmin

Para finalizar crea el archivo /etc/postfixadmin/vacation.conf con el siguiente contenido.

# ========== begin configuration ==========
$db_type = 'mysql';
$db_username = 'user';
$db_password = 'tupassword';    
$db_name     = 'postfix';    
$vacation_domain = 'autoreply.tudominio';

Configurar Dovecot

Remplaza el contenido del archivo /etc/dovecot/dovecot.conf con el siguiente contenido.

##
## 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/certs/mail.tudominio.com.crt 
ssl_key = </etc/pki/tls/private/mail.tudominio.com.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@tudominio.com
}  
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
}

Ahora el archivo /etc/dovecot/trash.conf

1 Spam
2 Trash

El siguiente paso es configurar dovecot para que se conecte a MySQL. Para eso crea los siguientes archivos de configuración.

/etc/dovecot/dovecot-mysql.conf

driver = mysql
connect = host=localhost dbname=postfix user=postfix password=tupassword
# 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'
default_pass_scheme = MD5-CRYPT

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

connect = host=localhost dbname=postfix user=postfix password=tupassword
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
}

Ahora crea el archivo de sieve filter para el filtro de spam

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

Ingresa el siguiente contenido

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;
  }

Configuración de Roundcube

Remplaza el archivo de configuración de apache de Roundcube /etc/httpd/conf.d/roundcubemail.conf con el siguiente contenido.

#
# Round Cube Webmail is a browser-based multilingual IMAP client
#
 
# Force https here instead of in Round Cube 
RewriteEngine On
 
# This checks to make sure the connection is not already HTTPS
RewriteCond %{HTTPS} !=on 
 
# These rules will redirect all users who are using any part of /secure/ to the same location but using HTTPS.
# i.e.  http://www.example.com/secure/ to https://www.example.com/secure/
RewriteRule ^/?roundcubemail/(.*) https://%{SERVER_NAME}/roundcubemail/$1 [R,L]
RewriteRule ^/?webmail/(.*) https://%{SERVER_NAME}/webmail/$1 [R,L]
 
Alias /roundcubemail /usr/share/roundcubemail
Alias /webmail /usr/share/roundcubemail
 
<Directory /usr/share/roundcubemail/>
        Order Deny,Allow
        Deny from all
        Allow from all
        php_value suhosin.session.encrypt Off 
</Directory>

Ahora crea la base de datos de MySQL para Roundcube.

mysql -u root -p -e "CREATE DATABASE roundcubemail;"
mysql -u root -p -e "GRANT ALL PRIVILEGES ON roundcubemail.* TO roundcube@localhost IDENTIFIED BY 'tupassword';"

Crea las tablas

mysql -u root -p roundcubemail &lt; /usr/share/doc/roundcubemail-0.8.6/SQL/mysql.initial.sql

En el archivo /etc/roundcubemail/db.inc.php encuentra la siguiente línea y asegúrate de remplazar pass por tu password

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

En el archivo /etc/roundcubemail/main.inc.php cambia las siguientes líneas como se muestra a continuación:

$rcmail_config['default_host'] = 'localhost';
$rcmail_config['smtp_server'] = 'localhost';
$rcmail_config['force_https'] = true;
$rcmail_config['plugins'] = array('managesieve');
$rcmail_config['quota_zero_as_unlimited'] = true;

Ahora configuramos el manage sieve plugin

cd /usr/share/roundcubemail/plugins/managesieve/
cp config.inc.php.dist config.inc.php

Edita el archivo config.inc.php y cambia la siguiente línea de esta forma:

$rcmail_config['managesieve_port'] = 4190;

Edita el archivo /etc/php.d/mcrypt.ini y cambia la linea extension=module.so por extension=mcrypt.so

Reinicia el servicio de apache

service httpd restart

Por ultimo asegúrate de que todos los servicios inicien automáticamente cada vez que el servidor es reiniciado

chkconfig postfix on
chkconfig dovecot on
chkconfig http on
chkconfig mysqld on

Ahora reinicia el servidor y si todo funciona bien cuando inicie entonces realizaste la instalación con éxito.

Configuraciones opcionales

Filtro de Spam y Virus

Remplaza el contenido de /etc/clamd.conf con las siguientes líneas

##
## Cconfig file for the Clam AV daemon
## Please read the clamd.conf(5) manual before editing this file.
##

# Logfile
LogFile /var/log/clamav/clamd.log
LogFileMaxSize 20M
LogTime yes
LogSyslog yes

# Pid
PidFile /var/run/clamav/clamd.pid

# Paths
TemporaryDirectory /var/tmp
DatabaseDirectory /var/lib/clamav
LocalSocket /var/run/clamav/clamd

# Sets the group ownership on the unix socket.
# Default: disabled (the primary group of the user running clamd)
#LocalSocketGroup virusgroup

# Misc
FixStaleSocket yes
TCPSocket 3310
TCPAddr 127.0.0.1
MaxConnectionQueueLength 50
MaxThreads 50
ReadTimeout 240
User clam
AllowSupplementaryGroups yes

# Exe
ScanPE yes
ScanELF yes
DetectBrokenExecutables yes

# Docs
ScanOLE2 yes
ScanPDF yes

# Mail
ScanMail yes
PhishingSignatures yes
PhishingScanURLs yes

# Data Loss Prevention (DLP)

# Enable the DLP module
# Default: No
#StructuredDataDetection yes

# This option sets the lowest number of Credit Card numbers found in a file
# to generate a detect.
# Default: 3
#StructuredMinCreditCardCount 5

# This option sets the lowest number of Social Security Numbers found
# in a file to generate a detect.
# Default: 3
#StructuredMinSSNCount 5

# With this option enabled the DLP module will search for valid
# SSNs formatted as xxx-yy-zzzz
# Default: yes
#StructuredSSNFormatNormal yes

# With this option enabled the DLP module will search for valid
# SSNs formatted as xxxyyzzzz
# Default: no
#StructuredSSNFormatStripped yes

# Archives
ScanArchive yes
ArchiveBlockEncrypted no

Configura Razor

razor-admin -register -user=antispamfilter -pass=tupassword

Actualiza y reinicia Clamav

freshclam
service clamd restart
chkconfig clamd on

Configura Amavisd-new

En el archivo /etc/amavisd/amavisd.conf cambia las siguientes líneas de estar forma:

$mydomain = 'tudominio.com'; 
$log_level = 1; 
$sa_tag_level_deflt = -99; 
$sa_tag2_level_deflt = 5.0; 
$sa_kill_level_deflt = 9; 
$sa_dsn_cutoff_level = 9; 
$sa_quarantine_cutoff_level = 50; 
$myhostname = 'mail.tudominio.com'; 
$notify_method = 'smtp:[127.0.0.1]:10025'; 
$forward_method = 'smtp:[127.0.0.1]:10025'; 
$final_banned_destiny = D_DISCARD;

Busca las siguientes lineas y asegurate de apuntar el socket the clamav al directorio correcto

### 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 ],

Agrega el usuario de clamav al grupo de amavis y cambia los privilegios del directorio /var/spool/amavisd/tmp

usermod -g amavis clam
cd /var/spool/amavisd
chmod -R 750 tmp/

Ahora actualiza spamassassin y reinicia amavisd-new

sa-update
service amavisd start
chkconfig amavisd on

Indícale a postfix que inicie a filtrar spam des comentando las siguientes dos líneas del archivo /etc/postfix/master.cf

-o content_filter=smtp-amavis:127.0.0.1:10024
-o receive_override_options=no_address_mappings

Reinicia postfix y listo

service postfix restart

Usando el plugin Roundcube Password

Utiliza este plugin si quieres que los usuarios puedan cambiar su propio password desde roundcube.

Edita el archivo /etc/roundcubemail/main.inc.php y cambia la siguiente línea de esta forma:

$rcmail_config['plugins'] = array('managesieve','password');

Ahora configuramos el plugin

cd /usr/share/roundcubemail/plugins/password/
cp config.inc.php.dist config.inc.php

Edita el archivo config.inc.php y cambia las siguientes líneas de esta forma:

$rcmail_config['password_db_dsn'] = 'mysql://postfix:tupasswordenpostfixadmin@localhost/postfix';
$rcmail_config['password_query'] = 'UPDATE mailbox SET password=%c WHERE username=%u limit 1;';

Reinicia Apache

service httpd restart

Tu servidor esta listo.

En posts futuros mostrare como agregar Domain Keys en Postfix ademas de una buena estrategia para que puedas hacerle respaldo a tu servidor de correos.

Deja tus comentarios y/o sugerencias.