quinta-feira, 6 de outubro de 2011

Configurando postfix + mysql + courier + SPF + clamav +spamassassin + greylist + TLS

Este tutorial tem como objetivo apresentar uma forma de configurar o postfix MTA com alguns serviços adicionais, para entrega e recebimento de mail com controle de spam, virus e greylist com suporte SSL. Este tutorial é bem pratico e objetivo.


1 - Entre no console do mysql e digite:

CREATE DATABASE postfix;
CREATE USER 'postfix'@'localhost' IDENTIFIED BY 'choose_a_password';
GRANT ALL PRIVILEGES ON `postfix` . * TO 'postfix'@'localhost';

Isso vai criar o banco de dados e dar as devidas permissões.

2 - Baixa a ultima versão do postfixadmin, descompacta dentro do diretorio web, configura o arquivo config.inc.php nas seguinte linhas abaixo:

$CONF['configured'] = false;

Para

$CONF['configured'] = true;

E essas linhas deixa como esta abaixo:

$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'postfix';
$CONF['database_password'] = '123456';
$CONF['database_name'] = 'postfix';

Feito isso é só rodar o postfixadmin que ele já instala automaticamente o banco de dados do postfix no mysql.

3 – PHPMYADMIN

No phpmyadmin edite o seguinte arquivo create-mailbox.php e procure a seguinte linha:

$maildir = $fUsername . "/";

Mudar para

$maildir = $fDomain. "/" . $fName . "/" . maildir . "/";

4 – SASL2, entre no diretorio /etc/sasl2 e crie os segunte arquivo com o conteudo.

Smtpd.conf

Dentro dele:

pwcheck_method: saslauthd
log_level: 3
mech_list: plain login

Crie uma alias para este arquivo na pasta /usr/lib/sasl2/

ln -s /etc/sasl2/smtpd.conf /usr/lib/sasl2/smtpd.conf

Então é só iniciar o sasl2 com o comando abaixo: -a rimap é para ele autenticar via o imap.

/usr/sbin/saslauthd -r -a rimap -O 127.0.0.1

5 – Criando o usuario Vmail:

groupadd -g 5000 vmail
useradd -g vmail -u 5000 vmail -d /home/vmail -m

6 - Confiigurando o main.cf

Vou colocar somente as principais linhas para essa configuração.

recipient_delimiter = +
home_mailbox = Maildir/
mailbox_transport = virtual:unix:/home/vmail/
header_checks = pcre:/etc/postfix/header_checks
body_checks = pcre:/etc/postfix/body_checks
smtpd_banner = Prefeitura Municipal de Muriae Mail Server

masquerade_domains = /etc/postfix/meus_dominios

smtpd_sasl_auth_enable = yes
smtpd_sasl_authenticated_header = yes
broken_sasl_auth_clients = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain =

smtpd_client_restrictions = permit_sasl_authenticated,
check_client_access pcre:/etc/postfix/ip_access.bkp,
# permit_mynetworks,
## check_client_access hash:/etc/postfix/helo_ok,
reject_unknown_reverse_client_hostname,
reject_unknown_sender_domain,
reject_unknown_recipient_domain,
# reject_unknown_client,
reject_non_fqdn_sender,
reject_non_fqdn_recipient,
# reject_unknown_hostname,
reject_non_fqdn_hostname,
reject_unauth_pipelining,
reject_unlisted_sender,
reject_unlisted_recipient,
# reject_unverified_sender,
# reject_unverified_recipient,
reject_rbl_client rbl.brasilrbl.com.br,
reject_rbl_client zen.spamhaus.org,
reject_rbl_client bl.spamcop.net,
reject_rhsbl_client rhsbl.brasilrbl.com.br,
reject_rhsbl_sender rhsbl.brasilrbl.com.br,
## reject_rhsbl_client blackhole.securitysage.com,
## reject_rhsbl_sender blackhole.securitysage.com,
reject_rhsbl_client rhsbl.sorbs.net,
reject_rhsbl_sender rhsbl.sorbs.net,
permit

##smtpd_helo_restrictions = permit_sasl_authenticated,
# check_helo_access hash:/etc/postfix/helo_ok,
# permit_mynetworks,
# reject_invalid_hostname,
# reject_unknown_hostname,
# reject_non_fqdn_sender,
## reject_unauth_pipelining,
## reject_unknown_helo_hostname

smtpd_sender_restrictions = permit_sasl_authenticated,
# permit_mynetworks,
# check_sender_access hash:/etc/postfix/helo_ok,
reject_non_fqdn_sender,
reject_unknown_sender_domain,
reject_unlisted_sender,
reject_unverified_sender,
reject_unauth_pipelining
# reject_unknown_client,

smtpd_recipient_restrictions = check_sender_access hash:/etc/postfix/sender_proibidos,
permit_sasl_authenticated,
# permit_mynetworks,
# reject_sender_login_mismatch,
# permit_mynetworks,
reject_authenticated_sender_login_mismatch,
reject_unauth_pipelining,
# reject_unknown_client,
reject_unknown_recipient_domain,
reject_unverified_recipient,
reject_unlisted_recipient,
reject_unauth_destination,
check_policy_service inet:127.0.0.1:60000,
# check_policy_service unix:private/greylist,
check_policy_service unix:private/policy,
# check_recipient_access hash:/etc/postfix/whitelist,
permit

smtpd_data_restrictions = reject_unauth_pipelining
smtpd_etrn_restrictions = permit_sasl_authenticated, reject

##smtpd_helo_required = yes
disable_vrfy_command = yes
strict_rfc821_envelopes = yes
invalid_hostname_reject_code = 554
multi_recipient_bounce_reject_code = 554
non_fqdn_reject_code = 554
relay_domains_reject_code = 554
unknown_address_reject_code = 554
unknown_client_reject_code = 554
unknown_hostname_reject_code = 554
unknown_local_recipient_reject_code = 554
unknown_relay_recipient_reject_code = 554
unknown_sender_reject_code = 554
unknown_virtual_alias_reject_code = 554
unknown_virtual_mailbox_reject_code = 554
unverified_recipient_reject_code = 554
unverified_sender_reject_code = 554

smtpd_tls_security_level = may
smtpd_tls_cert_file = /etc/postfix/postfix.cert
smtpd_tls_key_file = /etc/postfix/postfix.key
smtpd_tls_session_cache_database = btree:${queue_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${queue_directory}/smtp_scache

### configuracoes dos dominios virtuais #############

virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
virtual_mailbox_base = /home/vmail/

### armazenamento de mensagens dos dominios virtuais #####################

virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
virtual_mailbox_limit = 51200000
virtual_minimum_uid = 5000
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
virtual_transport = virtual

### configuraoes de quota ##############################

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 = Sua caixa de email esta cheia, favor liberar espa..
virtual_overquota_bounce = yes

smtpd_recipient_limit = 21

#Entrega de e-mails para mesmo destino
smtp_destination_concurrency_limit = 50

#Entrega de e-mails para mesmo destino - remoto
default_destination_concurrency_limit = 50

#Entrega de e-mails para mesmo destino - local
default_destination_recipient_limit = 50

#Tempo de reenvio de mensagem em fila
fast_flush_refresh_time = 1h

#Tempo de dele�o de mensagem em fila
fast_flush_purge_time = 1d

#Tempo de mensagem em fila
maximal_queue_lifetime = 240m

bounce_queue_lifetime = 240m

biff = yes
#always_bcc=edsonferreira@dpcnet.com.br
allow_untrusted_routing = no

#content_filter = lmtp-filter:127.0.0.1:10025
#receive_override_options = no_address_mappings

default_process_limit = 500
command_time_limit = 3600

# dk-milter
#smtpd_milters = unix:/var/run/dk-milter/dk.sock
#non_smtpd_milters = unix:/var/run/dk-milter/dk.sock

7 – Configurando o master.cf

#
# Postfix master process configuration file. For details on the format
# of the file, see the master(5) manual page (command: "man 5 master").
#
# The script postfix-chroot.sh can be used to set up a Postfix chroot
# environment on your Mandrivalinux System.
#
# ==========================================================================
# service type private unpriv chroot wakeup maxproc command + args
# (yes) (yes) (yes) (never) (100)
# ==========================================================================
smtp inet n - n - 15 smtpd
-o content_filter=clamav:clamav
submission inet n - n - 15 smtpd
-o smtpd_enforce_tls=yes
-o smtpd_sasl_auth_enable=yes
# -o smtpd_client_restrictions=permit_sasl_authenticated,reject
smtps inet n - n - 15 smtpd
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
# -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#628 inet n - n - - qmqpd
pickup fifo n - n 60 1 pickup
-o content_filter=
-o receive_override_options=
cleanup unix n - n - 0 cleanup
qmgr fifo n - n 300 1 qmgr
#qmgr fifo n - n 300 1 oqmgr
tlsmgr unix - - n 300 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 - 50 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.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent. See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
#maildrop unix - n n - - pipe
# flags=DRhu user=nobody argv=/usr/bin/maildrop -d ${recipient}
#
# Cyrus. Please See the Postfix CYRUS_README file for details
#
# deliver interface (deprecated), to use this also use
# postconf -e cyrus-deliver_destination_recipient_limit=1
#cyrus-deliver unix - n n - - pipe
# user=cyrus argv=/usr/lib/cyrus-imapd/deliver -e -r ${sender} -m ${extension} ${user}
#
# for default cyrus socket placement
#cyrus unix - n n - - lmtp
# -o lmtp_cache_connection=yes
#
# if you configure cyrus socket in the chroot jail
#cyrus-chroot unix - - y - - lmtp
# -o lmtp_cache_connection=yes
#
# for lmtp to cyrus via tcp
#cyrus-inet unix - - y - - lmtp
# -o lmtp_cache_connection=yes
# -o lmtp_sasl_auth_enable=yes
# -o lmtp_sasl_password_maps=hash:/etc/postfix/cyrus_lmtp_sasl_pass
# -o lmtp_sasl_security_options=noanonymous
#
# UUCP. Unix to Unix CoPy
#
# See the Postfix UUCP_README file for configuration details.
#
#uucp unix - n n - - pipe
# flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
# These are not distributed with Mandrivalinux
#
#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

##### START OF CONTENT FILTER CUSTOMIZATIONS #####
# Please see the Postfix FILTER_README for details.
# These sample entries expect your content filter to
# listen on port 10025 and to inject mail back into
# postfix on port 10026.
#
# to enable such content filter run the command
# postconf -e content_filter=smtp-filter:127.0.0.1:10025
# postconf -e smtp-filter_destination_concurrency_limit=2
# or
# postconf -e content_filter=lmtp-filter:127.0.0.1:10025
# postconf -e lmtp-filter_destination_concurrency_limit=2
# and the command
# postconf -e receive_override_options=no_address_mappings
#

127.0.0.1:10026 inet n - n - 20 smtpd
-o content_filter=
-o smtpd_restriction_classes=
-o smtpd_client_restrictions=permit_mynetworks,reject
-o smtpd_helo_restrictions=
-o smtpd_sender_restrictions=
-o smtpd_delay_reject=no
-o smtpd_recipient_restrictions=permit_mynetworks,reject
-o mynetworks=127.0.0.0/8
-o smtpd_authorized_xforward_hosts=127.0.0.0/8
-o strict_rfc821_envelopes=yes
-o smtpd_error_sleep_time=0
-o smtpd_soft_error_limit=1001
-o smtpd_hard_error_limit=1000
-o receive_override_options=no_unknown_recipient_checks,no_header_body_checks

lmtp-filter unix - - n - 20 lmtp
-o lmtp_data_done_timeout=1200
-o lmtp_send_xforward_command=yes
-o lmtp_cache_connection=no
-o max_use=20

smtp-filter unix - - y - - smtp
-o smtp_data_done_timeout=1200
-o smtp_send_xforward_command=yes
-o max_use=20

##### END OF CONTENT FILTER CUSTOMIZATIONS #####

policy unix - n n - - spawn
user=nobody argv=/usr/bin/perl /usr/libexec/postfix/postfix-policyd-spf-perl

clamav unix - n n - 15 pipe
flags=Rq user=clamav argv=/usr/libexec/postfix/clamav-filter.sh -f ${sender} -- ${recipient}

#greylist unix - n n - - spawn
# user=nobody argv=/usr/bin/perl /usr/libexec/postfix/greylist.pl

7.1 - Arquivos para mysql no postfix:

Criar os seguintes arquvos abaixo com seu devido conteúdo:

mysql_virtual_alias_maps.cf:
user = postfix
password = 123456
dbname = postfix
table = alias
select_field = goto
where_field = address
hosts = localhos

mysql_virtual_mailbox_limit_maps.cf
user = postfix
password = 123456
dbname = postfix
table = mailbox
select_field = quota
where_field = username
hosts = localhost

mysql_virtual_domains_maps.cf
user = postfix
password = 123456
hosts = localhost
dbname = postfix
table = domain
select_field = description
where_field = domain
#additional_conditions = and backupmx = '0' and active = '1'

mysql_virtual_mailbox_maps.cf
user = postfix
password = 123456
dbname = postfix
table = mailbox
select_field = maildir
where_field = username
hosts = localhost

8 – Configurando o clamav, greylist, SPF e spamassassin:

/etc/clamd:

LogFile /var/log/clamav/clamd.log
LogFileMaxSize 0
LogTime yes
LogSyslog yes
PidFile /var/run/clamav/clamd.pid
TemporaryDirectory /var/tmp
DatabaseDirectory /var/clamav
LocalSocket /tmp/clamd.socket
FixStaleSocket yes
TCPSocket 3310
TCPAddr 127.0.0.1
MaxConnectionQueueLength 30
MaxThreads 50
ReadTimeout 300
User clamav
AllowSupplementaryGroups yes
ScanPE yes
ScanELF yes
DetectBrokenExecutables yes
ScanOLE2 yes
ScanMail yes
#ScanHTML yes
ScanArchive yes

Baixe o arquivo http://www.unitednerds.org/projects/mail/clamav-filter.sh.gz e coloque dentro de /usr/libexec/postfix/.

gzip -d clamav-filter.sh.bz2
chmod 0755 clamav-filter.sh
mkdir -p /var/spool/filter
chown clamav:clamav /var/spool/filter

Integrando spamassassin ao clamav-filter

Edite o arquivo com vim /usr/libexec/posffix/clamav-filter.sh e altere a seguinte linha:

SENDMAIL="/usr/sbin/sendmail -i "

Para

SENDMAIL="/usr/bin/spamc -f -e /usr/sbin/sendmail -i "

Configurando o spamassassin:

Entre no diretório /etc/mail/spamassassin e edite o arquivo local.cf e deixe como abaixo, lembrando que está em um nível baixo de segurança podendo aumentar.

Obs: pode entrar nesse site: http://www.yrex.com/spam/spamconfig.php e gerar a própria configuração do spamassassin:

# How many hits before a message is considered spam.
required_score 7.0

# Change the subject of suspected spam
rewrite_header subject *****INFO - POSSÃVEL SPAM*****

# Encapsulate spam in an attachment (0=no, 1=yes, 2=safe)
report_safe 1

# Enable the Bayes system
use_bayes 1

# Enable Bayes auto-learning
bayes_auto_learn 1

# Enable or disable network checks
skip_rbl_checks 0
use_razor2 1
#use_dcc 1
use_pyzor 1

# Mail using languages used in these country codes will not be marked
# as being possibly spam in a foreign language.
# - portuguese
#ok_languages pt

# Mail using locales used in these country codes will not be marked
# as being possibly spam in a foreign language.
ok_locales all

Configurando o Greylist:

Instale o postgrey, edite o rc.local e acrecente a seguinte linha para iniciar o serviço: a linha abaixo já se encontra com todas as opções necessárias.

Dentro do main.cf acrescente a seguinte linha: sempre colocar a linha depois do reject_unauth_destination.

smtpd_recipient_restrictions = ...
reject_unauth_destination,
....
check_policy_service inet:127.0.0.1:60000,
....

postgrey --inet=127.0.0.1:60000 --delay=60 --retry-window=1 --auto-whitelist-clients=1 --dbdir=/var/spool/postfix/postgre -d

Configurando o SPF:

dentro do master.cf acrecente a seguinte linha:

policy unix - n n - - spawn
user=nobody argv=/usr/bin/perl /usr/libexec/postfix/postfix-policyd-spf-perl

dentro o main.cf acrecente a seguinte linha: sempre colocar a linha depois do reject_unauth_destination.

smtpd_recipient_restrictions = ...
reject_unauth_destination,
....
check_policy_service unix:private/policy,
....

8.1 - Configurando conexes TLS pelo smtpd

cd /etc/postfix

Criando as chaves: openssl req -new -outform PEM -out postfix.cert -newkey rsa:2048 -nodes -keyout postfix.key -keyform PEM -days 999 -x509

Preencha os campos que vai aparecer:

Country Name (2 letter code) [AU]:BR
State or Province Name (full name) [Some-State]:MS
Locality Name (eg, city) []:CGR
Organization Name (eg, company) [Internet Widgits Pty Ltd]: empresa dominio.com.br
Organizational Unit Name (eg, section) []:nocc, network operation command center
Common Name (eg, YOUR name) []:admin
Email Address []: admin@dominio.com.br
configuração no main.cf:
smtpd_tls_security_level = may
smtpd_tls_cert_file = /etc/postfix/postfix.cert
smtpd_tls_key_file = /etc/postfix/postfix.key
smtpd_tls_session_cache_database = btree:${queue_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${queue_directory}/smtp_scache

Configuração no master.cf:

tlsmgr unix - - n 300 1 tlsmgr

submission inet n - n - 15 smtpd
-o smtpd_enforce_tls=yes
-o smtpd_sasl_auth_enable=yes
# -o smtpd_client_restrictions=permit_sasl_authenticated,reject
smtps inet n - n - 15 smtpd
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
# -o smtpd_client_restrictions=permit_sasl_authenticated,rejects

9 - Configurando o Courier Imap

Pacote instalado desse site:


Entre no diretório /etc/authlib e altere os seguintes arquivos:

authdaemonrc

authmodulelistorig="authuserdb authpam authpgsql authldap authmysql authcustom authpipe"

Para

authmodulelistorig="authmysql"

Neste arquivo é so isso, não precisa de mudar mais nada:

No arquivo authmysqlrc deixe como esta abaixo:

authmysqlrc

MYSQL_SERVER localhost
MYSQL_USERNAME postfix
MYSQL_PASSWORD 123456
MYSQL_SOCKET /var/lib/mysql/mysql.sock
MYSQL_DATABASE postfix
MYSQL_USER_TABLE mailbox
#MYSQL_CLEAR_PWFIELD password
MYSQL_UID_FIELD '5000'
MYSQL_GID_FIELD '5000'
MYSQL_LOGIN_FIELD username
MYSQL_HOME_FIELD '/home/vmail'
MYSQL_MAILDIR_FIELD maildir
MYSQL_QUOTA_FIELD quota
MYSQL_WHERE_CLAUSE active="1"
MYSQL_CRYPT_PWFIELD password

No diretório /usr/lib/courier-imap/etc tem os arquivo imapd-ssl e pop3d-ssl, Edite esse arquivo e altere como abaixo, lembrando que só tive problema no courier 64bits.

# TLS_PROTOCOL sets the protocol version. The possible versions are:
#
# SSL2 - SSLv2
# SSL3 - SSLv3
# SSL23 - either SSLv2 or SSLv3
# TLS1 - TLS1

TLS_PROTOCOL=SSL23

Esse conteúdo está disponibilizado sobre a licença de uso - Tiu enhavo estas disponebla sur uza permesilo LiPE

Nenhum comentário:

Postar um comentário

Postagens populares