Vamos instalar os pacotes necessários.
# aptitude install postfix postfix-mysql postfix-doc postfix-policyd-spf-perl postfix-tls libsasl2-2 libsasl2-modules-sql libsasl2-modules libsasl2-dev sasl2-bin openssl libpam-smbpass courier-imap courier-imap-ssl courier-pop courier-pop-ssl courier-authlib-mysql courier-authdaemon
Confirme as opções com Y.
Ajustando o sistema:
Agora precisamos ajustar o UID e GID da máquina para que as permissões possam ser atribuídas de maneira adequada.
Vamos verificar o gid do postfix:
# cat /etc/passwd | grep postfix
postfix:x:105:108::/var/spool/postfix:/bin/false
O GID do postfix é 108, esse deve ser o valor informado no arquivo de configuração do postfix em /etc/postfix/main.cf nas seguinte linhas:
virtual_minimun_uid = 108
virtual_gid_maps = static:108
virtual_uid_maps = static:108
Em seguida precisamos criar um usuário com UID 108 no sistema para o funcionamento correto do sistema de vmail.
# adduser --system --shell /bin/false --uid 108 --gid 108 vmail
Mudar a permissão do home do usuário:
# chown -R vmail:postdrop /home/vmail
Arquivo de configuração do Postfix:
# vim /etc/postfix/main.cf
##############################
#Autor:Douglas Q. dos Santos
#Data: 27/08/2010
##############################
smtpd_banner = $myhostname ESMTP $mail_name
biff = no
######################
#Definicao do Hostname
######################
myhostname = mail.valefertil.com.br
#####################
#Definicao do Dominio
#####################
mydomain = valefertil.com.br
#######################################
#Lista de dominios aceitos pelo postfix
#######################################
mydestination = $myhostname, localhost.localdomain, mailfertil.$mydomain
#######################################
#Habilita o envio de e-mails para o dominio local
#######################################
append_dot_mydomain = no
###########################################
#Especifica um arquivo que contera os Alias
###########################################
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
###########################################
#Especifica qual o dominio principal que esta usando
###########################################
myorigin = $mydomain
##########################################
#Servidor responsavel pela entrega das mensagens
##########################################
relayhost =
#######################################
#Quais redes serão aceitas pelo postfix
#######################################
mynetworks = 127.0.0.1/32, 192.168.0.0/24, 10.10.10.0/24
#######################################
#Especifica um comando externo opcional
#######################################
mailbox_command = procmail -a "$EXTENSION"
recipient_delimiter = +
#######################################
#Quais interfaces serão usadas para sistema de email
######################################
inet_interfaces = all
##################################################
#Quais os protocolos usados pelo sistema de e-mail
##################################################
inet_protocols = all
###########################
#Tamanho maximo da mensagem
###########################
message_size_limit = 30720000
#############################
#Tamanho maximo do arquivo de armazenamento para
#Tamanho ilimitado deixar como 0
##############################
mailbox_size_limit = 0
header_checks = regexp:/etc/postfix/header_checks
##########################
#Autenticação dos Usuarios
##########################
smtpd_sasl_local_domain =
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = 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 opm.blitzed.org, reject_rbl_client list.dsbl.org,reject_rbl_client bl.spamcop.net, reject_rbl_client sbl-xbl.spamhaus.org, check_policy_service unix:private/policy
smtpd_tls_auth_only = no
##########################################
#Ativação do TLS (Transport Layer Security
##########################################
readme_directory = no
smtp_use_tls = yes
smtpd_use_tls = yes
smtp_tls_note_starttls_offer = yes
smtpd_tls_CAfile = /etc/postfix/ssl/cacert.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
smtpd_tls_cert_file = /etc/postfix/ssl/smtpd.crt
smtpd_tls_key_file = /etc/postfix/ssl/smtpd.key
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
tls_random_source = dev:/dev/urandom
#MySQL
transport_maps = mysql:/etc/postfix/mysql_transport_maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
virtual_transport = virtual
virtual_minimum_uid = 108
virtual_uid_maps = static:108
virtual_gid_maps = static:108
virtual_mailbox_base = /home/vmail
#Quota
virtual_mailbox_limit = 0
virtual_maildir_extended = yes
virtual_mailbox_limit_override = yes
virtual_mailbox_limit_maps = mysql:/etc/postfix/mysql_virtual_mailbox_limit_maps.cf
virtual_overquota_bounce = yes
virtual_maildir_limit_message = Desculpe, o diretorio de correio do usuario estourou sua quota, por favor tente novamente depois.
Agora precisamos criar os arquivos necessários o acesso ao banco de dados. Esses são os arquivos referenciados no /etc/postfix/main.cf.
# vim mysql_transport_maps.cf
# /etc/postfix/mysql_transport_maps.cf
user = mail
password = senha
hosts = localhost
dbname = mail
table = domain
select_field = transport
where_field = domain
# vim mysql_virtual_alias_maps.cf
# /etc/postfix/mysql_virtual_alias_maps.cf
user = mail
password = senha
hosts = localhost
dbname = mail
table = alias
select_field = goto
where_field = address
# vim mysql_virtual_domains_maps.cf
# /etc/postfix/mysql_virtual_domains_maps.cf
user = mail
password = senha
hosts = localhost
dbname = mail
table = domain
select_field = domain
where_field = domain
# vim mysql_virtual_mailbox_limit_maps.cf
# /etc/postfix/mysql_virtual_mailbox_limit_maps.cf
user = mail
password = senha
hosts = localhost
dbname = mail
table = mailbox
select_field = quota
where_field = username
# vim mysql_virtual_mailbox_maps.cf
user = mail
password = senha
hosts = localhost
dbname = mail
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = 1
Mudar as permissões dos arquivos criados para que o postfix possa acessá-los:
# chmod o= /etc/postfix/mysql_*
# chgrp postfix /etc/postfix/mysql_*
# vim /usr/local/etc/postfix/header_checks
# /etc/postfix/header_checks
/^Received:/ HOLD
Configuração do arquivo master.cf.
Agora que terminamos os arquivos de conexão com o banco devemos inserir as seguinte linhas ao final do arquivo
/etc/postfix/master.cf:
# vim /etc/postfix/master.cf
vacation unix - n n - - pipe
flags=Rq user=vacation argv=/var/spool/vacation/vacation.pl -f ${sender} -- ${recipient}
policy unix - n n - - spawn
user=nobody argv=/usr/sbin/postfix-policyd-spf-perl
Gerando as chaves criptografadas para o nosso postfix:
# mkdir /etc/postfix/ssl
# cd /etc/postfix/ssl
# openssl genrsa -des3 -rand /etc/hosts -out smtpd.key 1024
Informe a senha e confirme a senha:
# chmod 600 smtpd.key
# openssl req -new -key smtpd.key -out smtpd.csr
Informe a senha que foi informada no comando anterior e informe os dados que serão pedidos:
# openssl x509 -req -days 365 -in smtpd.csr -signkey smtpd.key -out smtpd.crt
Informe a mesma senha novamente.
# openssl rsa -in smtpd.key -out smtpd.key.unec
Informe a mesma senha novamente.
# mv smtpd.key.unec smtpd.key
# openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 365
Informe a uma senha e confirme.
# chown -R root:postfix /etc/postfix/ssl/
# chmod -R 640 /etc/postfix/ssl/
Aliases:
# vim /etc/aliases
root: ti@dominio.com.br
# newaliases
Os logs dos emails podem ser consultados em /var/log/maillog e /var/log/messages ou /var/log/syslog.
Configurando o SASL
Precisamos habilitar o SASL para ser iniciado e para que trabalhe enjaulado junto com o Postfix, já que o mesmo trabalha em modo chroot por default.
# vim /etc/default/saslauthd
[...]
START=yes
[...]
#OPTIONS="-c -m /var/run/saslauthd"
OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"
Em seguida crie o link a seguir:
# cd /var/run
# mv saslauthd saslauthd.bkp
# ln -s /var/spool/postfix/var/run/saslauthd/
Agora vamos configurar a conexão do SASL com o MySQL:
# vim /etc/postfix/sasl/smtpd.conf
# /etc/postfix/sasl/smtpd.conf
pwcheck_method: saslauthd sql
log_level: 3
mech_list: plain login cram digest
Adicione o usuário postfix ao grupo sasl:
# adduser postfix sasl
Não esqueça de reiniciar o serviço:
# /etc/init.d/saslauthd stop
# /etc/init.d/saslauthd start
Para finalizar, restarte o postfix:
# /etc/init.d/postfix stop
# /etc/init.d/postfix start
Devido ao método chroot do postfix, também precisamos criar um link do mysql para que o acesso possa ser realizado corretamente.
# mkdir -p /var/spool/postfix/var/run/mysqld
# vim /etc/init.d/mysql
[...]
case "${1:-''}" in
'start')
[...]
fi
/bin/ln -f /var/run/mysqld/mysqld.sock /var/spool/postfix/var/run/mysqld/mysqld.sock
;;
[...]
Reinicie o servidor do mysql:
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
Configurando o Courier
Assim como fizemos em todos os outros serviços, também precisamos configurar o Courier para conectar na base MySQL.
# vim /etc/courier/authdaemonrc
authmodulelist="authmysql"
authmodulelistorig="authmysql"
daemons=5
authdaemonvar=/var/run/courier/authdaemon
subsystem=mail
DEFAULTOPTIONS=""
LOGGEROPTS=""
# vim /etc/courier/authmysqlrc
#/etc/courier/authmysqlrc
MYSQL_SERVER localhost
MYSQL_USERNAME mail
MYSQL_PASSWORD senha
MYSQL_SOCKET /var/run/mysqld/mysqld.sock
MYSQL_PORT 3306
MYSQL_OPT 0
MYSQL_DATABASE mail
MYSQL_USER_TABLE mailbox
MYSQL_CRYPT_PWFIELD password
MYSQL_CLEAR_PWFIELD password
MYSQL_UID_FIELD '108'
MYSQL_GID_FIELD '108'
MYSQL_LOGIN_FIELD username
MYSQL_HOME_FIELD '/home/vmail'
MYSQL_NAME_FIELD name
MYSQL_MAILDIR_FIELD CONCAT("/home/vmail/",maildir)
MYSQL_QUOTA_FIELD concat(quota,'S')
Configurando os daemons de transporte:
# vim /etc/courier/imapd
#/etc/courier/imapd
ADDRESS=0
PORT=143
MAXDAEMONS=40
MAXPERIP=20
PIDFILE=/var/run/courier/imapd.pid
TCPDOPTS="-nodnslookup -noidentlookup"
LOGGEROPTS="-name=imapd"
IMAP_CAPABILITY="IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA IDLE"
IMAP_KEYWORDS=1
IMAP_ACL=1
IMAP_CAPABILITY_ORIG="IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA AUTH=CRAM-MD5 AUTH=CRAM-SHA1 AUTH=CRAM-SHA256 IDLE"
IMAP_PROXY=0
IMAP_PROXY_FOREIGN=0
IMAP_IDLE_TIMEOUT=60
IMAP_MAILBOX_SANITY_CHECK=0
IMAP_CAPABILITY_TLS="$IMAP_CAPABILITY AUTH=PLAIN"
IMAP_CAPABILITY_TLS_ORIG="$IMAP_CAPABILITY_ORIG AUTH=PLAIN"
IMAP_DISABLETHREADSORT=0
IMAP_CHECK_ALL_FOLDERS=0
IMAP_OBSOLETE_CLIENT=0
IMAP_UMASK=022
IMAP_ULIMITD=65536
IMAP_USELOCKS=1
IMAP_SHAREDINDEXFILE=/etc/courier/shared/index
IMAP_ENHANCEDIDLE=0
IMAP_TRASHFOLDERNAME=Trash
IMAP_EMPTYTRASH=Trash:7
IMAP_MOVE_EXPUNGE_TO_TRASH=0
SENDMAIL=/usr/sbin/sendmail
HEADERFROM=X-IMAP-Sender
IMAPDSTART=YES
MAILDIRPATH=Maildir
# vim /etc/courier/pop3d
#/etc/courier/pop3d
PIDFILE=/var/run/courier/pop3d.pid
MAXDAEMONS=40
MAXPERIP=4
POP3AUTH=""
POP3AUTH_ORIG="PLAIN LOGIN CRAM-MD5 CRAM-SHA1 CRAM-SHA256"
POP3AUTH_TLS=""
POP3AUTH_TLS_ORIG="LOGIN PLAIN"
POP3_PROXY=0
PORT=110
ADDRESS=0
TCPDOPTS="-nodnslookup -noidentlookup"
LOGGEROPTS="-name=pop3d"
POP3DSTART=YES
MAILDIRPATH=Maildir
# vim /etc/courier/imapd-ssl
#/etc/courier/impad-ssl
SSLPORT=993
SSLADDRESS=0
SSLPIDFILE=/var/run/courier/imapd-ssl.pid
SSLLOGGEROPTS="-name=imapd-ssl"
IMAPDSSLSTART=YES
IMAPDSTARTTLS=YES
IMAP_TLS_REQUIRED=0
COURIERTLS=/usr/bin/couriertls
TLS_KX_LIST=ALL
TLS_COMPRESSION=ALL
TLS_CERTS=X509
TLS_CERTFILE=/etc/courier/imapd.pem
TLS_TRUSTCERTS=/etc/ssl/certs
TLS_VERIFYPEER=NONE
TLS_CACHEFILE=/var/lib/courier/couriersslcache
TLS_CACHESIZE=524288
MAILDIRPATH=Maildir
# vim /etc/courier/pop3d-ssl
#/etc/courier/pop3d-ssl
SSLPORT=995
SSLADDRESS=0
SSLPIDFILE=/var/run/courier/pop3d-ssl.pid
SSLLOGGEROPTS="-name=pop3d-ssl"
POP3DSSLSTART=YES
POP3_STARTTLS=YES
POP3_TLS_REQUIRED=0
COURIERTLS=/usr/bin/couriertls
TLS_STARTTLS_PROTOCOL=TLS1
TLS_KX_LIST=ALL
TLS_COMPRESSION=ALL
TLS_CERTS=X509
TLS_CERTFILE=/etc/courier/pop3d.pem
TLS_TRUSTCERTS=/etc/ssl/certs
TLS_VERIFYPEER=NONE
TLS_CACHEFILE=/var/lib/courier/couriersslcache
TLS_CACHESIZE=524288
MAILDIRPATH=Maildir
Vamos gerar os certificados para autenticação agora via ssl:
# cd /etc/courier
# vim imap.cnf
RANDFILE = /usr/lib/courier/imapd.rand
[ req ]
default_bits = 1024
encrypt_key = yes
distinguished_name = req_dn
x509_extensions = cert_type
prompt = no
[ req_dn ]
C=BR
ST=PR
L=Curitiba
O=Empresa Mail Server
OU=Empresa IMAP SSL key
CN=mail.dominio.com.br
emailAddress=postmaster@dominio.com.br
[ cert_type ]
nsCertType = server
# vim pop3d.cnf
RANDFILE = /usr/lib/courier/pop3d.rand
[ req ]
default_bits = 1024
encrypt_key = yes
distinguished_name = req_dn
x509_extensions = cert_type
prompt = no
[ req_dn ]
C=BR
ST=PR
L=Curitiba
O=Empresa Mail Server
OU=Empresa POP3 SSL key
CN=mail.dominio.com.br
emailAddress=postmaster@dominio.com.br
[ cert_type ]
nsCertType = server
Agora vamos utilizar os comandos para gerar o certificados:
# rm /etc/courier/imapd.pem
# rm /etc/courier/pop3d.pem
# /usr/sbin/mkimapdcert
# /usr/sbin/mkpop3dcert
Reinicie os serviços do Courier:
# /etc/init.d/courier-authdaemon restart
# /etc/init.d/courier-imap restart
# /etc/init.d/courier-pop restart