Postfix Pantaneiro
De gutocarvalho.net
Postfix à moda pantaneira
Autor: Guto Carvalho (guto@gutocarvalho.net)
Co-Autor: Patrick Ximenes (hexaclamys@gmail.com)
Revisão/Colaboração: Rafael Bedendo, Fernando R.Durso
Revisão/Colaboração para Debian Lenny Clenio W. e Silva (cleniogyn@gmail.com)
Campo Grande, Mato Grosso do Sul, Brasil.
Ambiente: Ubuntu Feisty 7.04 Server, Debian Lenny
Procure tirar dúvidas deste tutorial no fórum apropriado: http://gutocarvalho.net/phpBB3
informações
Este artigo aborda a configuração de um servidor de e-mail completo, com as seguintes características.....
Cenário
distro
- ubuntu feisty 7.04 server / Debian Lenny
ferramentas
- postfix
- postfix mysql support
- postfix tls support
- courier authlib
- courier mysql support
- courier imap
- courier imap-ssl
- courier pop
- courier pop-ssl
- sasl2 (autenticacao)
- clamav-filter
- clamav
- spamassassin
- razor
- pyzor
- dcc-client
- postgrey
- postfix-policyd-spf-perl
- mailman
- mailgraph
- queuegraph
- couriergraph
- pfqueue
- pflogsum (relatórios)
- squirrelmail
- squirrelmail-locale
- roundcube-webmail
definindo senha do administrador do mysql, habilitando logs
vamos setar uma senha para o banco de dados mysql
root@voyager:~# mysqladmin -u root password 'suasenha'
ajustando my.cnf
root@voyager:~# vi /etc/mysql/my.cnf
# # The MySQL database server configuration file. # # You can copy this to one of: # - "/etc/mysql/my.cnf" to set global options, # - "~/.my.cnf" to set user-specific options. # # One can use all long options that the program supports. # Run program with --help to get a list of available options and with # --print-defaults to see which it would actually understand and use. # # For explanations see # http://dev.mysql.com/doc/mysql/en/server-system-variables.html # This will be passed to all mysql clients # It has been reported that passwords should be enclosed with ticks/quotes # escpecially if they contain "#" chars... # Remember to edit /etc/mysql/debian.cnf when changing the socket location. [client] port = 3306 socket = /var/run/mysqld/mysqld.sock # Here is entries for some specific programs # The following values assume you have at least 32M ram # This was formally known as [safe_mysqld]. Both versions are currently parsed. [mysqld_safe] socket = /var/run/mysqld/mysqld.sock nice = 0 [mysqld] user = mysql pid-file = /var/run/mysqld/mysqld.pid socket = /var/run/mysqld/mysqld.sock port = 3306 basedir = /usr datadir = /var/lib/mysql tmpdir = /tmp language = /usr/share/mysql/english skip-external-locking # # Instead of skip-networking the default is now to listen only on # localhost which is more compatible and is not less secure. bind-address = 127.0.0.1 # # * Fine Tuning # key_buffer = 16M max_allowed_packet = 16M thread_stack = 128K thread_cache_size = 8 #max_connections = 100 #table_cache = 64 #thread_concurrency = 10 # # * Query Cache Configuration # query_cache_limit = 1M query_cache_size = 16M # # * Logging and Replication # # Both location gets rotated by the cronjob. # Be aware that this log type is a performance killer. log = /var/log/mysql.log # # Error logging goes to syslog. This is a Debian improvement :) # # Here you can see queries with especially long duration #log_slow_queries = /var/log/mysql/mysql-slow.log #long_query_time = 2 #log-queries-not-using-indexes # The following can be used as easy to replay backup logs or for replication. #server-id = 1 log_bin = /var/log/mysql/mysql-bin.log # WARNING: Using expire_logs_days without bin_log crashes the server! See README.Debian! expire_logs_days = 10 max_binlog_size = 100M #binlog_do_db = include_database_name #binlog_ignore_db = include_database_name # # * BerkeleyDB # # Using BerkeleyDB is now discouraged as its support will cease in 5.1.12. skip-bdb # # * InnoDB # # InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/. # Read the manual for more InnoDB related options. There are many! # You might want to disable InnoDB to shrink the mysqld process by circa 100MB. #skip-innodb # # * Security Features # # Read the manual, too, if you want chroot! # chroot = /var/lib/mysql/ # # For generating SSL certificates I recommend the OpenSSL GUI "tinyca". # # ssl-ca=/etc/mysql/cacert.pem # ssl-cert=/etc/mysql/server-cert.pem # ssl-key=/etc/mysql/server-key.pem [mysqldump] quick quote-names max_allowed_packet = 16M [mysql] #no-auto-rehash # faster start of mysql but no tab completition [isamchk] key_buffer = 16M # # * NDB Cluster # # See /usr/share/doc/mysql-server-*/README.Debian for more information. # # The following configuration is read by the NDB Data Nodes (ndbd processes) # not from the NDB Management Nodes (ndb_mgmd processes). # # [MYSQL_CLUSTER] # ndb-connectstring=127.0.0.1 # # * IMPORTANT: Additional settings that can override those from this file! # !includedir /etc/mysql/conf.d/
instalando o postfix
instalando o programa
root@voyager:~# apt-get install postfix postfix-doc postfix-mysql
instalando
instalando postfixadmin, populando banco
entre no diretório tmp
root@voyager:~# cd /tmp
agora vamos fazer o download do programa
root@voyager:/tmp# wget http://ufpr.dl.sourceforge.net/sourceforge/postfixadmin/postfixadmin-2.1.0.tgz
vamos descompactar
root@voyager:/tmp# tar zxvf postfixadmin-2.1.0.tgz
entre no diretório
root@voyager:/tmp# cd postfixadmin-2.1.0
agora vamos editar o dump do banco do postfixadmin e vamos alterar a senha do usuário, procure o campo password e ajuste a senha.
root@voyager:/tmp# vi DATABASE_MYSQL.TXT
# # Postfix Admin # by Mischa Peters <mischa at high5 dot net> # Copyright (c) 2002 - 2005 High5! # License Info: http://www.postfixadmin.com/?file=LICENSE.TXT # # This is the complete MySQL database structure for Postfix Admin. # If you are installing from scratch you can use this file otherwise you # need to use the TABLE_CHANGES.TXT or TABLE_BACKUP_MX.TXT that comes with Postfix Admin. # # There are 2 entries for a database user in the file. # One you can use for Postfix and one for Postfix Admin. # # If you run this file twice (2x) you will get an error on the user creation in MySQL. # To go around this you can either comment the lines below "USE MySQL" until "USE postfix". # Or you can remove the users from the database and run it again. # # You can create the database from the shell with: # # mysql -u root [-p] < DATABASE_MYSQL.TXT # # Postfix / MySQL # USE mysql; # Postfix user & password INSERT INTO user (Host, User, Password) VALUES ('localhost','postfix',password('suasenha')); INSERT INTO db (Host, Db, User, Select_priv) VALUES ('localhost','postfix','postfix','Y'); # Postfix Admin user & password INSERT INTO user (Host, User, Password) VALUES ('localhost','postfixadmin',password('suasenha')); INSERT INTO db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv) VALUES ('localhost', 'postfix', 'postfixadmin', 'Y', 'Y', 'Y', 'Y'); FLUSH PRIVILEGES; GRANT USAGE ON postfix.* TO postfix@localhost; GRANT SELECT, INSERT, DELETE, UPDATE ON postfix.* TO postfix@localhost; GRANT USAGE ON postfix.* TO postfixadmin@localhost; GRANT SELECT, INSERT, DELETE, UPDATE ON postfix.* TO postfixadmin@localhost; CREATE DATABASE postfix; USE postfix; # # Table structure for table admin # CREATE TABLE admin ( username varchar(255) NOT NULL default , password varchar(255) NOT NULL default , created datetime NOT NULL default '0000-00-00 00:00:00', modified datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', PRIMARY KEY (username), KEY username (username) ) TYPE=MyISAM COMMENT='Postfix Admin - Virtual Admins'; # # Table structure for table alias # CREATE TABLE alias ( address varchar(255) NOT NULL default , goto text NOT NULL, domain varchar(255) NOT NULL default , created datetime NOT NULL default '0000-00-00 00:00:00', modified datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', PRIMARY KEY (address), KEY address (address) ) TYPE=MyISAM COMMENT='Postfix Admin - Virtual Aliases'; # # Table structure for table domain # CREATE TABLE domain ( domain varchar(255) NOT NULL default , description varchar(255) NOT NULL default , aliases int(10) NOT NULL default '0', mailboxes int(10) NOT NULL default '0', maxquota int(10) NOT NULL default '0', transport varchar(255) default NULL, backupmx tinyint(1) NOT NULL default '0', created datetime NOT NULL default '0000-00-00 00:00:00', modified datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', PRIMARY KEY (domain), KEY domain (domain) ) TYPE=MyISAM COMMENT='Postfix Admin - Virtual Domains'; # # Table structure for table domain_admins # CREATE TABLE domain_admins ( username varchar(255) NOT NULL default , domain varchar(255) NOT NULL default , created datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', KEY username (username) ) TYPE=MyISAM COMMENT='Postfix Admin - Domain Admins'; # # Table structure for table log # CREATE TABLE log ( timestamp datetime NOT NULL default '0000-00-00 00:00:00', username varchar(255) NOT NULL default , domain varchar(255) NOT NULL default , action varchar(255) NOT NULL default , data varchar(255) NOT NULL default , KEY timestamp (timestamp) ) TYPE=MyISAM COMMENT='Postfix Admin - Log'; # # Table structure for table mailbox # CREATE TABLE mailbox ( username varchar(255) NOT NULL default , password varchar(255) NOT NULL default , name varchar(255) NOT NULL default , maildir varchar(255) NOT NULL default , quota int(10) NOT NULL default '0', domain varchar(255) NOT NULL default , created datetime NOT NULL default '0000-00-00 00:00:00', modified datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', PRIMARY KEY (username), KEY username (username) ) TYPE=MyISAM COMMENT='Postfix Admin - Virtual Mailboxes'; # # Table structure for table vacation # CREATE TABLE vacation ( email varchar(255) NOT NULL default , subject varchar(255) NOT NULL default , body text NOT NULL, cache text NOT NULL, domain varchar(255) NOT NULL default , created datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', PRIMARY KEY (email), KEY email (email) ) TYPE=MyISAM COMMENT='Postfix Admin - Virtual Vacation';
depois de ajustar a senha, vamos criar o banco.
root@voyager:/tmp# mysql -u root -p < DATABASE_MYSQL.TXT
criando o usuário vmail
Your system can hold mailboxes for thousands of users. You probably do not want to assign a unique UID (user ID) to every user. So I recommend you create a pseudo-user who will become the owner of all mailboxes.
O seu sistema pode ter milhares de caixas postais de usuários. Provavelmente você não quer que cada usuário tenha um ID, desta forma utilizaremos o vmail que é um pseudo-usuário para que ele se torne dono das caixas postais.
root@voyager:~# groupadd -g 5000 vmail
root@voyager:~# useradd -g vmail -u 5000 vmail -d /home/vmail -m
dentro do diretorio do vmail ficaram as contas dos dominios virtuais
root@voyager:~# cd /home/vmail/dominio.com.br/jose
root@voyager:~# ls -lah /home/vmail
configurando autenticação SASL/MYSQL
O SASL permite que um usuário consiga enviar email pelo servidor smtp (relay) sem que o seu IP esteja na lista de IP's liberados para relay, no postfix é configurado na linha "mynetworks" no arquivo main.cf.
O requisito para enviar email é que o usuário exista no sistema. Isso é um ótimo recurso, pois o usuário onde estiver pode enviar email pelo seu servidor, sem que você precise liberar o "Relay" para todo mundo.
root@voyager:~# apt-get install libsasl2 libsasl2-modules libsasl2-modules-sql
root@voyager:~# mkdir /etc/postfix/sasl/
root@voyager:~# vi /etc/postfix/sasl/smtpd.conf
pwcheck_method: auxprop auxprop_plugin: sql mech_list: plain login cram-md5 digest-md5 sql_engine: mysql sql_hostnames: 127.0.0.1 sql_user: postfix sql_passwd: suasenha sql_database: postfix sql_select: SELECT password FROM mailbox WHERE username = '%u@%r' sql_verbose: yes log_level: 10
root@voyager:~# ln -s /etc/postfix/sasl/smtpd.conf /usr/lib/sasl2/
A senha deve estar plain text no banco, senão não autentica.
root@voyager:~# chown root:postfix /etc/postfix/sasl/smtpd.conf
root@voyager:~# chmod u=rw,g=r,o= /etc/postfix/sasl/smtpd.conf
configurando conexoes TLS pelo smtpd
vamos entrar no diretório do postfix
root@voyager:~# cd /etc/postfix
root@voyager:/etc/postfix# mkdir tls
root@voyager:/etc/postfix# cd tls
vamos gerar o certificado para conexoes seguras no MTA.
root@voyager:/etc/postfix/tls# openssl req -new -outform PEM -out postfix.cert -newkey rsa:2048 -nodes -keyout postfix.key -keyform PEM -days 999 -x509
procure preencher como o exemplo abaixo:
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
insira as seguintes linhas no arquivo /etc/postfix/main.cf, pode ser no final do arquivo
root@voyager:~# vim /etc/postfix/main.cf
smtpd_use_tls = yes smtpd_tls_cert_file = /etc/postfix/tls/postfix.cert smtpd_tls_key_file = /etc/postfix/tls/postfix.key smtpd_data_restrictions = reject_unauth_pipelining
insira as linhas abaixo no master.cf
root@voyager:~# vim /etc/posfix/master.cf
tlsmgr unix - - n 300 1 tlsmgr smtps inet n - n - - smtpd -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes 587 inet n - n - - smtpd -o smtpd_enforce_tls=yes -o smtpd_sasl_auth_enable=yes
instalando e configurando pop3, imap4, pop3-ssl e imap4-ssl
instalando os programas
root@voyager:~# apt-get install courier-authdaemon courier-authlib-mysql courier-pop courier-pop-ssl courier-imap courier-imap-ssl
Bom nós instalamos o courier-imap-ssl e couirer-pop-ssl, o pacote do ubuntu cria o certificado pra gente, mas vamos criar o nosso personalizado como fizemos acima.
root@voyager:~# cd /etc/courier
criando o certificado para conexões imap seguras (IMAP-SSL)
root@voyager:~# openssl req -x509 -newkey rsa:1024 -keyout imapd.pem -out imapd.pem -nodes -days 999
preencha conforme o exemplo
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
certifique-se que o arquivo /etc/courier/imapd-ssl esta com a linha abaixo
TLS_CERTFILE=/etc/courier/imapd.pem
criando o certificado para conexões pop3 seguras (POP3-SSL)
root@voyager:~# openssl req -x509 -newkey rsa:1024 -keyout pop3d.pem -out pop3d.pem -nodes -days 999
preencha conforme o exemplo
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
certifique-se que o arquivo /etc/courier/pop3d-ssl esta com a linha abaixo
TLS_CERTFILE=/etc/courier/pop3d.pem
instalando e configurando postgrey
instalando o programa
root@voyager:~# apt-get install postgrey
edite o /etc/default/postgrey
root@voyager:~# vim /etc/default/postgrey
e ajuste a linha existente, deixando como abaixo
POSTGREY_OPTS="--inet=127.0.0.1:60000 --delay=60"
isto ajusta o tempo de tentativas do servidor.
Devemos ajustar a configuração do smtpd_recipient_restrictions no arquivo main.cf
root@voyager:~# vim /etc/postfix/main.cf
smtpd_recipient_restrictions =
reject_unauth_pipelining,
permit_mynetworks,
reject_non_fqdn_recipient,
reject_unknown_recipient_domain,
reject_unauth_destination,
check_policy_service inet:127.0.0.1:60000, permit
Essa ultima linha é referente ao postgrey.
o postgrey tem os seguintes arquivos a configurar:
/etc/postgrey/whitelist_clients /etc/postgrey/whitelist_recipients
o conteúdo é auto-explicativo, são listas brancas ou seja o que estiver ali é liberado.
instalando e configurando o postfix-policyd-spf-perl
este programa vai fazer checagens SPF nas mensagens tratadas pelo servudor
instalando o programa
root@voyager:~# apt-get install postfix-policyd-spf-perl
ajustando o main.cf vamos alterar a configuração do smtpd_recipient_restrictions inserindo a seguinte linha antes da checagem do postgrey
check_policy_service unix:private/policy
ficaria assim:
smtpd_recipient_restrictions =
reject_unauth_pipelining,
permit_mynetworks,
permit_sasl_authenticated,
reject_non_fqdn_recipient,
reject_unauth_destination,
check_policy_service unix:private/policy
check_policy_service inet:127.0.0.1:60000
permit
ajustando o master.cf
insira esta linha antes das configurações TLS e do clamav-filter.
policy unix - n n - - spawn
user=nobody argv=/usr/bin/perl /usr/sbin/postfix-policyd-spf-perl
instalando e configurando o spamassassin
instalando o programa
root@voyager:~# apt-get install spamassassin razor pyzor libnet-dns-perl libmail-spf-query-perl dcc-client
Obs.: No caso do debian lenny, retire o pacote dcc-client da instalação
vamos editar e configurar o arquivo /etc/default/spamassassin
root@voyager:~# vim /etc/default/spamassassin
seu conteúdo deve ficar assim
# /etc/default/spamassassin # Duncan Findlay # WARNING: please read README.spamd before using. # There may be security risks. # Change to one to enable spamd ENABLED=1 # Options # See man spamd for possible options. The -d option is automatically added. # NOTE: version 3.0.x has switched to a "preforking" model, so you # need to make sure --max-children is not set to anything higher than # 5, unless you know what you're doing. OPTIONS="--create-prefs --max-children 5 --helper-home-dir" # Pid file # Where should spamd write its PID to file? If you use the -u or # --username option above, this needs to be writable by that user. # Otherwise, the init script will not be able to shut spamd down. PIDFILE="/var/run/spamd.pid" # Set nice level of spamd #NICE="--nicelevel 15"
agora vamos editar o arquivo /etc/spamassassin/local.cf
root@voyager:~# vim /etc/spamassassin/local.cf
o conteúdo do arquivo deve ficar assim
### checagens na rede ############## # faz checagens RBL (0=nao, 1=sim) skip_rbl_checks 0 # dcc (0=nao, 1=sim) use_dcc 1 dcc_path /usr/bin/dccproc dcc_add_header 1 dcc_dccifd_path /usr/sbin/dccifd #pyzor (0=nao, 1=sim) use_pyzor 1 pyzor_path /usr/bin/pyzor pyzor_add_header 1 #razor (0=nao, 1=sim) use_razor2 1 razor_config /etc/razor/razor-agent.conf ### encapsular spam em anexo (0=nao, 1=ok, 2=safe) ### report_safe 0 ### nivel de sensibilidade do spamassassin ####### required_score 4.0 ### idiomas ###### ok_languages all ok_locales all ### sobrescreve o subject ######## rewrite_header Subject [***** SPAM _SCORE_ *****] ### sistema bayes ########## use_bayes 1 use_bayes_rules 1 bayes_auto_learn 1 ### lista liberada ############ whitelist_from *@dominio.com.br #unwhitelist_from proibido@dominio.com.br ### lista negada ########################## blacklist_from *@microsoft.com *@sco.com #unblacklist_from liberado@microsoft.com #### redes confiaveis ############ trusted_networks 127.0.0.0/8 192.168.1.0/24 200.xx.xx.xx/29 201.xx.xx.xx/29 ### adicionando headers na mensagens ######## clear_headers add_header spam FLAG _YESNOCAPS add_header all Status _YESNO_, hits=_HITS_ required=_REQD_ tests=_TESTS_ version=_VERSION_ add_header all Level _STARS(*)_ add_header all Checker-Version SpamAssassin _VERSION (_SUBVERSION_) on _HOSTNAME_ fold_headers 1
configurando clamav-filter
instalando programas essenciais
root@voyager:~# apt-get install clamav clamav-daemon clamav-freshclam
instalando programas que auxiliam e são utilizados nas varreduras
root@voyager:~# apt-get install file arc gzip bzip2 cabextract zip unzip unrar-free cpio tar zoo arj lzop nomarch pax unzoo
Obs.: Para Debian Lenny, você pode retirar o pacote unzoo da instalação.
root@voyager:~# wget http://www.unitednerds.org/projects/mail/clamav-filter.sh.gz
root@voyager:~# gzip -d clamav-filter.sh.bz2
root@voyager:~# chmod 0755 clamav-filter.sh
root@voyager:~# mkdir -p /var/spool/filter
root@voyager:~# chown clamav:clamav /var/spool/filter
root@voyager:~# mv clamav-filter.sh /usr/lib/postfix
insira no final do master.cf
smtp inet n - n - - smtpd
-o content_filter=clamav:clamav
clamav unix - n n - - pipe
flags=Rq user=clamav argv=/usr/lib/postfix/clamav-filter.sh -f ${sender} -- ${recipient}
se você quiser descartar mensagensque além de taggear a msg como SPAM altere antes da linha viruscan no clamav-filter.sh adicione o código abaixo
# # SpamAssassin # spamc -c < $nome_arquivo >/dev/null ; RETVAL=$? if [ $RETVAL -ne 0 ]; then # Se quiser redireciona-la para outro lugar... sed -e "s/^Subject: /Subject: --- SPAM (SpamAssassin): $from -> $@ --- /i" $nome_arquivo | $SENDMAIL -f postmaster@$MYHOSTNAME -- postmaster@$MYHOSTNAME rm -f $nome_arquivo exit 0 fi viruscan
integrando spamassassin ao clamav-filter
precisamos instalar o spamc que é um cliente do spamd
root@voyager:~# apt-get install spamc
para integrar o spamassassin ao clamav-filter altere a linha abaixo dentro do script em /usr/lib/postfix/clamav-filter.sh
root@voyager:~# vim /usr/lib/posffix/clamav-filter.sh
SENDMAIL="/usr/sbin/sendmail -i "
Para:
SENDMAIL="/usr/bin/spamc -f -e /usr/sbin/sendmail -i "
clamav-filter modificado
fizemos algumas otimizações no clamav filter original, caso deseje usar segue o script abaixo:
lembre-se de ajustar as variáveis MYHOSTNAME e REPORTHOST
#!/bin/sh
# ClamAV script; set a opcao ScanMail no clamav.conf
# by Deives Michellis "thefallen" - dmichellis@yahoo.com | thefallen@unitednerds.org
# alteracoes e otimizacoes por:
# guto carvalho (guto@gutocarvalho.net)
# patrick ximenes (hexaclamys@gmail.com)
export PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/usr/games
#
# configuracoes/variaveis
#
INSPECT_DIR=/var/spool/filter
# apenas checando virus
#SENDMAIL="/usr/sbin/sendmail -i "
# checando virus e spam
SENDMAIL="/usr/bin/spamc -s 5000000 -f -e /usr/sbin/sendmail -i "
MYHOSTNAME="gutocarvalho.net"
REPORTHOST="gutocarvalho.net"
#MYHOSTNAME=`postconf -h myhostname`
#REPORTHOST=`postconf -h myhostname`
#
# exit codes <sysexits.h>
#
EX_TEMPFAIL=75
EX_UNAVAILABLE=69
EX_DENIED=77
#
# definicoes dos nomes temporarios
#
nome_arquivo=`date +%Y%m%d%H%M%S`
nome_arquivo=in.$$.$nome_arquivo
AVCMD="/usr/bin/clamdscan --disable-summary --stdout "
NOTIFY_VIRUS=yes
NOTIFY_POSTMASTER=yes
#
# funcao viruscan
#
viruscan() {
VIRUS=`$AVCMD $nome_arquivo`
SAIDA=$?
VIRUS=`echo $VIRUS | cut -d" " -f2-`
if [ $SAIDA -eq 1 ]; then
postlog -t postfix/clamav-virus-filter message-id=$msgid reject: VIRUS from=\<$from\> to=\<$rcpts\> 2>/dev/null
# notificando sender
if [ "$NOTIFY_VIRUS" = "yes" ]; then
echo "From: Virus Scanner <mailer-daemon@$MYHOSTNAME>
Subject: AVISO: Email rejeitado: VIRUS Detectado
To: $from
Seu email para ($rcpts) com assunto ($subj) foi rejeitado por conter virus.
Virus encontrados: $VIRUS
" | $SENDMAIL -f MAILER-DAEMON -- $from
fi
# notificando postmaster
if [ "$NOTIFY_POSTMASTER" = "yes" ]; then
echo "From: Virus Scanner <mailer-daemon@$MYHOSTNAME>
Subject: Postmaster Copy: VIRUS Detectado
To: postmaster@$MYHOSTNAME
Um email de $from para ($rcpts) com assunto ($subj) foi rejeitado por conter virus.
Virus encontrados: $VIRUS
" | $SENDMAIL -f MAILER-DAEMON -- postmaster@$MYHOSTNAME
fi
exit 0
fi
}
#
# clean up when done or when aborting.
#
trap "rm -rf $nome_arquivo*" 0 1 2 3 15
#
# start processing.
#
cd $INSPECT_DIR || { echo $INSPECT_DIR does not exist; exit $EX_TEMPFAIL; }
cat >$nome_arquivo || { echo Cannot save mail to file; exit $EX_TEMPFAIL; }
from=$2
if [ "$from" != "--" ]; then
shift
else
$from=""
fi
shift ; shift
dominio=`echo $from | cut -d"@" -f2`
email=`echo $from | cut -d"@" -f1`
subj=`head -n 200 $nome_arquivo | grep -i "^Subject:" | cut -d":" -f2- | head -n 1`
msgid=`head -n 200 $nome_arquivo | grep -i "^message-id" | cut -d: -f 2- | sed 's/^ *//' | head -n 1`
saida="-f $from -- $@"
rcpts=$@
spamc -s 5000000 -c < $nome_arquivo >/dev/null ; RETVAL=$?
postlog -t postfix/clamav-spam-filter message-id=$msgid reject: SPAM from=\<$from\> to=\<$rcpts\> 2>/dev/null
if [ $RETVAL -ne 0 ]; then
#Se quiser redireciona-la para outro lugar...
#sed -e "s/^Subject: /Subject: --- SPAM (SpamAssassin): $from -> $@ --- /i" $nome_arquivo | $SENDMAIL -f postmaster@$MYHOSTNAME -- postmaster@$MYHOSTNAME
cp $nome_arquivo /root/spamtest
rm -f $nome_arquivo
exit 0
fi
viruscan
$SENDMAIL $saida <$nome_arquivo
exit 0
configurações do courier
Configurar o courier para autenticar no MySQL:
As configurações default dos arquivos imapd e pop3d, ao meu ver, já são boas. Altere caso você sinta necessidade.
Edite o /etc/courier/authmysqlrc. Esse arquivo é responsável pelas configurações do Courier para que ele conecte no MySQL e autentique os usuários. Edite-o conforme as suas configurações.
root@voyager:~# cd /etc/courier
root@voyager:/etc/courier# vim /etc/courier/authmysqlrc
MYSQL_SERVER 127.0.0.1 MYSQL_USERNAME postfix MYSQL_PASSWORD suasenha MYSQL_PORT 0 MYSQL_OPT 0 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_NAME_FIELD name MYSQL_MAILDIR_FIELD maildir MYSQL_QUOTA_FIELD quota
agora vamos editar o arquivo authdaemonrc
root@voyager:/etc/courier# vim /etc/courier/authdaemonrc
procure a linha authmodulelist e ajuste conforme abaixo:
authmodulelist="authmysql"
agora vamos ajustar os avisos de quota do courier
copiar o arquivo de exemplo warning de cota:
root@voyager:/etc/courier# cp /usr/share/doc/courier-base/examples/quotawarnmsg.example quotawarnmsg
root@voyager:/etc/courier# vi /etc/courier/quotawarnmsg
Ajuste o arquivo quotawarnmsg de acordo com suas necessidades.
ele deve ficar parecido com o abaixo:
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 <guto@gutocarvalho.net> Reply-To: guto@gutocarvalho.net 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. Sua caixa-postal no servidor esta com mais de 90% do espaço utilizado. Para continuar recebendo e-mails por favor remova algumas mensagens de sua caixa. Obrigado.
reiciando daemods...
root@voyager:/etc/courier# /etc/init.d/courier-authdaemon restart
root@voyager:/etc/courier# /etc/init.d/courier-pop restart
root@voyager:/etc/courier# /etc/init.d/courier-pop-ssl restart
root@voyager:/etc/courier# /etc/init.d/courier-imap restart
root@voyager:/etc/courier# /etc/init.d/courier-imap-ssl restart
agora vamos testar...
primeiro o imap
root@voyager:/etc/courier# /etc/courier# telnet localhost 143
Trying 0.0.0.0... Connected to 0. 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. 0 logout * BYE Courier-IMAP server shutting down 0 OK LOGOUT completed Connection closed by foreign host.
agora o pop
root@voyager:/etc/courier# telnet localhost 110
Trying 0.0.0.0... Connected to 0. Escape character is '^]'. +OK Hello there. quit +OK Better luck next time. Connection closed by foreign host.
Ok, os serviços POP e IMAP estão ativos, vamos ao restante das configurações
checando postfix
veja se o postfix esta com suporte ao mysql habilitado
root@voyager:/etc/courier# postconf -m
- btree
- cidr
- environ
- hash
- mysql
- nis
- proxy
- regexp
- sdbm
- static
- tcp
- unix
configurando postfix, conexao mysql
crie os arquivos abaixo e ajuste a senha
root@gutocarvalho:/etc/postfix/# mkdir mysql
root@gutocarvalho:/etc/postfix/# cd mysql
root@gutocarvalho:/etc/postfix/mysql# vim mysql_relay_domains_maps.cf
user = postfix password = suasenha hosts = localhost dbname = postfix table = domain select_field = domain where_field = domain
root@gutocarvalho:/etc/postfix/mysql# vim mysql_virtual_alias_maps.cf
user = postfix password = suasenha hosts = 127.0.0.1 dbname = postfix table = alias select_field = goto where_field = address
root@gutocarvalho:/etc/postfix/mysql# vim mysql_virtual_domains_maps.cf
user = postfix password = suasenha hosts = 127.0.0.1 dbname = postfix table = domain select_field = domain where_field = domain
root@gutocarvalho:/etc/postfix/mysql# vim mysql_virtual_mailbox_limit_maps.cf
user = postfix password = suasenha hosts = localhost dbname = postfix table = mailbox select_field = quota where_field = username
root@gutocarvalho:/etc/postfix/mysql# vim mysql_virtual_mailbox_maps.cf
user = postfix password = suasenha hosts = 127.0.0.1 dbname = postfix table = mailbox select_field = maildir where_field = username
arquivos criados agora vamos fazer ajustes finais no master.cf e main.cf
vou passar aqui os 2 arquivos já devidamente otimizados.
editando master.cf
root@voyager:~# vim /etc/posfix/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").
#
# ==========================================================================
# service type private unpriv chroot wakeup maxproc command + args
# (yes) (yes) (yes) (never) (100)
# ==========================================================================
smtp inet n - - - - smtpd
#submission inet n - - - - smtpd
# -o smtpd_enforce_tls=yes
# -o smtpd_sasl_auth_enable=yes
# -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#smtps inet n - - - - smtpd
# -o smtpd_tls_wrappermode=yes
# -o smtpd_sasl_auth_enable=yes
# -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#628 inet n - - - - qmqpd
pickup fifo n - - 60 1 pickup
cleanup unix n - - - 0 cleanup
qmgr fifo n - n 300 1 qmgr
#qmgr fifo n - - 300 1 oqmgr
tlsmgr unix - - - 1000? 1 tlsmgr
rewrite unix - - - - - trivial-rewrite
bounce unix - - - - 0 bounce
defer unix - - - - 0 bounce
trace unix - - - - 0 bounce
verify unix - - - - 1 verify
flush unix n - - 1000? 0 flush
proxymap unix - - n - - proxymap
smtp unix - - - - - smtp
# When relaying mail as backup MX, disable fallback_relay to avoid MX loops
relay unix - - - - - smtp
-o fallback_relay=
# -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq unix n - - - - showq
error unix - - - - - error
discard unix - - - - - discard
local unix - n n - - local
virtual unix - n n - - virtual
lmtp unix - - - - - lmtp
anvil unix - - - - 1 anvil
scache unix - - - - 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=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# 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.
#
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=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix - n n - 2 pipe
flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
#mailman unix - n n - - pipe
# flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
# ${nexthop} ${user}
# spf check
policy unix - n n - - spawn
user=nobody argv=/usr/bin/perl /usr/sbin/postfix-policyd-spf-perl
# configuracoes tls
tlsmgr unix - - n 300 1 tlsmgr
smtps inet n - n - - smtpd -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes
587 inet n - n - - smtpd -o smtpd_enforce_tls=yes -o smtpd_sasl_auth_enable=yes
# clamav-filter
smtp inet n - n - - smtpd
-o content_filter=clamav:clamav
clamav unix - n n - - pipe
flags=Rq user=clamav argv=/usr/lib/postfix/clamav-filter.sh -f ${sender} -- ${recipient}
editando arquivo main.cf
root@voyager:~# vim /etc/posfix/main.cf
### configuracoes globais #######################################
não se esqueça de ajustar as diretivas MYNETWORKS, MYHOSTNAME, MYDESTINATION
smtpd_banner = $myhostname ESMTP $mail_name (ubuntu)
biff = no
# appending .domain is the MUA's job.
append_dot_mydomain = no
myhostname = mail.seudominio.net
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
#alias_maps = hash:/var/lib/mailman/data/aliases, hash:/etc/aliases
#alias_database = hash:/var/lib/mailman/data/aliases, hash:/etc/aliases
myorigin = /etc/mailname
mydestination = mail.seudominio.net, localhost.localdomain, localhost
relayhost =
mynetworks = 127.0.0.0/8 192.168.1.0/24 201.41.xx.xx/29
recipient_delimiter = +
inet_interfaces = all
# tamanho maximo de caixa postal
mailbox_size_limit = 50000000
# tamanho maximo de mensagem
message_size_limit = 10240000
### otimizando #########
# how long if undelivered before sending warning update to sender
delay_warning_time = 4h
# will it be a permanent error or temporary
unknown_local_recipient_reject_code = 450
# how long to keep message on queue before return as failed.
# some have 3 days, I have 16 days as I am backup server for some people
# whom go on holiday with their server switched off.
maximal_queue_lifetime = 7d
# max and min time in seconds between retries if connection failed
minimal_backoff_time = 1000s
maximal_backoff_time = 8000s
# how long to wait when servers connect before receiving rest of data
smtp_helo_timeout = 60s
# how many address can be used in one message.
# effective stopper to mass spammers, accidental copy in whole address list # but may restrict intentional mail shots.
smtpd_recipient_limit = 16
# how many error before back off.
smtpd_soft_error_limit = 3
# how many max errors before blocking it.
smtpd_hard_error_limit = 12
### configuracoes dos dominios virtuais #############
virtual_alias_maps = mysql:/etc/postfix/mysql/mysql_virtual_alias_maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/mysql/mysql_virtual_domains_maps.cf
virtual_mailbox_base = /home/vmail/
### armazenamento de mensagens dos dominios virtuais #####################
virtual_mailbox_maps = mysql:/etc/postfix/mysql/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/mysql_virtual_mailbox_limit_maps.cf
virtual_mailbox_limit_override = yes
virtual_maildir_limit_message = Sorry, the your maildir has overdrawn your diskspace quota, please free up some of spaces of your mailbox try again.
virtual_overquota_bounce = yes
### configuracoes tls e sasl ##################################
smtpd_use_tls = yes
smtpd_tls_cert_file = /etc/postfix/tls/postfix.cert
smtpd_tls_key_file = /etc/postfix/tls/postfix.key
smtpd_data_restrictions = reject_unauth_pipelining
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_path = smtpd
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain =
### configuracoes de restricoes ##########################
smtpd_helo_required = yes
disable_vrfy_command = yes
smtpd_delay_reject = yes
strict_rfc821_envelopes = yes
### necessario pra clamav-filter ####
# quanto tempo um comando externo pode rodar antes de dar timeout
command_time_limit = 1h
### restricao durante o HELO/EHLO
smtpd_helo_restrictions =
permit_mynetworks,
warn_if_reject,
reject_non_fqdn_hostname,
reject_invalid_hostname,
permit
### detalhes necessarios para o sender
smtpd_sender_restrictions =
permit_sasl_authenticated,
permit_mynetworks,
reject_non_fqdn_sender,
reject_unknown_sender_domain,
reject_unauth_pipelining,
permit
### restricao para servidores que estao conectando (apos helo/ehlo)
smtpd_client_restrictions =
#reject_rbl_client sbl.spamhaus.org,
#reject_rbl_client bl.spamcop.net,
permit
### restricao aplicada aos recipientes
smtpd_recipient_restrictions =
reject_unauth_pipelining,
permit_mynetworks,
permit_sasl_authenticated,
reject_non_fqdn_hostname,
reject_non_fqdn_sender,
reject_non_fqdn_recipient,
reject_unauth_destination,
reject_invalid_hostname,
reject_rbl_client sbl.spamhaus.org,
reject_rbl_client bl.spamcop.net,
check_policy_service unix:private/policy
check_policy_service inet:127.0.0.1:60000
permit
policy_time_limit = 3600
inet_protocols = ipv4
arquivos configurados, vamos ajustar o postfix admin e criar contas para fazermos alguns testes:
reiniciando daemons
porém antes vamos reiniciar os daemons
parando tudo
root@voyager:~# /etc/init.d/courier-imap-ssl stop root@voyager:~# /etc/init.d/courier-imap stop root@voyager:~# /etc/init.d/courier-pop-ssl stop root@voyager:~# /etc/init.d/courier-pop stop root@voyager:~# /etc/init.d/courier-authdaemon stop root@voyager:~# /etc/init.d/postfix stop root@voyager:~# /etc/init.d/spamassassin stop root@voyager:~# /etc/init.d/clamav-daemon stop root@voyager:~# /etc/init.d/clamav-freshclam stop root@voyager:~# /etc/init.d/postgrey stop
iniciando tudo
root@voyager:~# /etc/init.d/courier-authlib start root@voyager:~# /etc/init.d/courier-imap start root@voyager:~# /etc/init.d/courier-imap-ssl start root@voyager:~# /etc/init.d/courier-pop start root@voyager:~# /etc/init.d/courier-pop-ssl start root@voyager:~# /etc/init.d/spamassassin start root@voyager:~# /etc/init.d/clamav-daemon start root@voyager:~# /etc/init.d/clamav-freshclam start root@voyager:~# /etc/init.d/postgrey start root@voyager:~# /etc/init.d/postfix start
configurando postfixadmin
vamos entrar no diretorio tmp
root@voyager:~# cd /tmp
agora vamos mover o diretorio que ja foi extraido para seu destino
root@voyager:/tmp# mv postfix-2.1.0 /var/www/postfixadmin
configurando postfixadmin
Obs.: Caso ocorra erro ao copiar o conteúdo do tutorial e colar no arquivo que será criado abaixo com o nome config.inc.php na hora dos testes do postfixadmin, a sugestão é: Copiar o arquivo de exemplo que vem dentro do diretório: cp config.inc.php.sample config.inc.php e alterar as variáveis que estão em negrito abaixo.
root@voyager:~# vim /var/www/postfixadmin/config.inc.php
<?php // // Postfix Admin // by Mischa Peters <mischa at high5 dot net> // Copyright (c) 2002 - 2005 High5! // License Info: http://www.postfixadmin.com/?file=LICENSE.TXT // // File: config.inc.php // if (ereg ("config.inc.php", $_SERVER['PHP_SELF'])) { header ("Location: login.php"); exit; } // Postfix Admin Path // Set the location to your Postfix Admin installation here. $CONF['postfix_admin_url'] = ; $CONF['postfix_admin_path'] = ; // Language config // Language files are located in './languages'. $CONF['default_language'] = 'en'; // Database Config // mysql = MySQL 3.23 and 4.0 // mysqli = MySQL 4.1 // pgsql = PostgreSQL $CONF['database_type'] = 'mysql'; $CONF['database_host'] = 'localhost'; $CONF['database_user'] = 'postfixadmin'; $CONF['database_password'] = 'suasenha'; $CONF['database_name'] = 'postfix'; $CONF['database_prefix'] = ; // Site Admin // Define the Site Admins email address below. // This will be used to send emails from to create mailboxes. $CONF['admin_email'] = 'postmaster@seudominio.com.br'; // Mail Server // Hostname (FQDN) of your mail server. // This is used to send email to Postfix in order to create mailboxes. $CONF['smtp_server'] = 'localhost'; $CONF['smtp_port'] = '25'; // Encrypt // In what way do you want the passwords to be crypted? // md5crypt = internal postfix admin md5 // system = whatever you have set as your PHP system default // cleartext = clear text passwords (ouch!) $CONF['encrypt'] = 'cleartext'; // Generate Password // Generate a random password for a mailbox and display it. // If you want to automagically generate paswords set this to 'YES'. $CONF['generate_password'] = 'NO'; // Page Size // Set the number of entries that you would like to see // in one page. $CONF['page_size'] = '10'; // Default Aliases // The default aliases that need to be created for all domains. $CONF['default_aliases'] = array ( 'abuse' => 'abuse@seudominio.com.br', 'hostmaster' => 'hostmaster@seudominio.com.br', 'postmaster' => 'postmaster@seudominio.com.br', 'webmaster' => 'webmaster@seudominio.com.br' ); // Mailboxes // If you want to store the mailboxes per domain set this to 'YES'. // Example: /usr/local/virtual/domain.tld/username@domain.tld $CONF['domain_path'] = 'YES'; // If you don't want to have the domain in your mailbox set this to 'NO'. // Example: /usr/local/virtual/domain.tld/username $CONF['domain_in_mailbox'] = 'NO'; // Default Domain Values // Specify your default values below. Quota in MB. $CONF['aliases'] = '10'; $CONF['mailboxes'] = '10'; $CONF['maxquota'] = '10'; // Quota // When you want to enforce quota for your mailbox users set this to 'YES'. $CONF['quota'] = 'NO'; // You can either use '1024000' or '1048576' $CONF['quota_multiplier'] = '1024000'; // Transport // If you want to define additional transport options for a domain set this to 'YES'. // Read the transport file of the Postfix documentation. $CONF['transport'] = 'NO'; // Virtual Vacation // If you want to use virtual vacation for you mailbox users set this to 'YES'. // NOTE: Make sure that you install the vacation module. http://high5.net/postfixadmin/ $CONF['vacation'] = 'NO'; // This is the autoreply domain that you will need to set in your Postfix // transport maps to handle virtual vacations. It does not need to be a // real domain (i.e. you don't need to setup DNS for it). $CONF['vacation_domain'] = 'autoreply.dominio.com.br'; // Alias Control // Postfix Admin inserts an alias in the alias table for every mailbox it creates. // The reason for this is that when you want catch-all and normal mailboxes // to work you need to have the mailbox replicated in the alias table. // If you want to take control of these aliases as well set this to 'YES'. $CONF['alias_control'] = 'NO'; // Special Alias Control // Set to 'NO' if you don't want your domain admins to change the default aliases. $CONF['special_alias_control'] = 'YES'; // Logging // If you don't want logging set this to 'NO'; $CONF['logging'] = 'YES'; // Header $CONF['show_header_text'] = 'NO'; $CONF['header_text'] = ':: Postfix Admin ::'; // Footer // Below information will be on all pages. // If you don't want the footer information to appear set this to 'NO'. $CONF['show_footer_text'] = 'YES'; $CONF['footer_text'] = 'Return to seudominio.com.br'; $CONF['footer_link'] = 'http://seudominio.com.br'; // Welcome Message // This message is send to every newly created mailbox. // Change the text between EOM. $CONF['welcome_text'] = <<<EOM Hi, Welcome to your new account. EOM; // // END OF CONFIG FILE // ?>
Acesse via web e entre na administração principal.
Aliás antes de acessar ajuste o .htaccess do diretório admin.
primeiro vamos criar um aquivo
root@voyager:~# htpasswd -c /etc/apache2/passwd admin
agora vamos ajustar o arquivo
root@voyager:~# vim /var/www/posfixadmin-2.1.0/admin/.htaccess
ele deve estar assim:
AuthUserFile /etc/apache2/passwd #AuthGroupFile /dev/null AuthName "Postfix Admin" AuthType Basic <limit GET POST> require valid-user </limit>
pronto agora podes usá-lo.
como funciona esse front-end?
http://ip-do-servidor/postfixadmin/admin/ Aqui você cria os domínios e especifica quem vai administrá-los.
http://ip-do-servidor/postfixadmin/ Este é o endereço para os usuários criados administrarem seus domínios
http://ip-do-servidor/postfixadmin/users/ Este é o endereço para usuário de um domínio trocar seus dados e senha.
Sempre que criar uma conta de e-mail, envie um e-mail de um conta externa para essa nova conta para que ela seja ativada e seu diretório MAILDIR seja criado, habilitando as checagens via POP/WEBMAIL/IMAP.
Teoricamente o postfixadmin deveria enviar a mensagem de boas vindas, mas por algum motivo nesta versão não está enviando.
testando autenticação via pop e imap
Beleza agora que está configurado e funcionando vamos criar um dominio e um usuário para fazermos testes.
Estou supondo que tu já tenha feito a criação e tudo deu certo, vamos aos testes!
Testando autenticação no courier-imap.
root@voyager:~# telnet 0 143
Trying 0.0.0.0... Connected to 0. 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. 0 login usuario@dominio.com.br minhasenha 0 OK LOGIN Ok. 0 select inbox * FLAGS (Draft Answered Flagged Deleted Seen Recent) * OK [PERMANENTFLAGS (* Draft Answered Flagged Deleted Seen)] Limited * 1 EXISTS * 1 RECENT * OK [UIDVALIDITY 1154248579] Ok * OK [MYRIGHTS "acdilrsw"] ACL 0 OK [READ-WRITE] Ok 0 logout * BYE Courier-IMAP server shutting down 0 OK LOGOUT completed Connection closed by foreign host.
Tudo ok com a autenticação no courier-imap, agora vamos testar agora a autenticação do courier-pop3.
root@voyager:~# telnet 0 110
Trying 0.0.0.0... Connected to 0. Escape character is '^]'. +OK Hello there. user usuario@dominio.com.br +OK Password required. pass minhasenha +OK logged in. list +OK POP3 clients that break here, they violate STD53. 1 4259 . quit +OK Bye-bye. Connection closed by foreign host.
Até agora tudo funcionou corretamente, caso tenha problemas, verifique no log do MySQL, veja como a query está sendo feita, isso pode te poupar muito tempo de dor de cabeça.
testando clamav-filter
Vamos agora fazer um teste, para saber se nosso servidor realmente está evitando vírus, vamos utilizar para isto o arquivo de teste do EICAR, com o seguinte comando:
instalando programas necessários para o teste
root@voyager:~# apt-get install mailx nail
- Teste 1, arquivo anexado.
baixe o arquivo de teste para antivirus do site https://www.eicar.org
root@voyager:~# wget https://secure.eicar.org/eicar_com.zip
estou supondo que você tem um MTA local em sua workstation.
root@sua-workstation-de-teste:~# nail -s "teste" -a eicar_com.zip usuario@dominio.com.br
agora vamos ver se o servidor pegou verifique o log do servidor de e-mail....
root@voyager:~# tail -f /var/log/mail.log
==> /var/log/mail.log <== Jul 30 10:34:27 voyager postfix/cleanup[5983]: 48E3C77521: message-id=<1185806063.6017.6.camel@defiant> Jul 30 10:34:27 voyager postfix/qmgr[5782]: 48E3C77521: from=<guto@gutocarvalho.net>, size=1111, nrcpt=1 (queue active) Jul 30 10:34:27 voyager postfix/virus-filter: message-id=<1185806063.6017.6.camel@defiant> reject: VIRUS from=<guto@gutocarvalho.net> to=<listas@gutocarvalho.net> Jul 30 10:34:27 voyager spamd[4350]: spamd: connection from localhost [127.0.0.1] at port 51287 Jul 30 10:34:27 voyager spamd[4350]: spamd: setuid to clamav succeeded Jul 30 10:34:27 voyager spamd[4350]: spamd: processing message (unknown) for clamav:110 ==> /var/log/clamav/clamav.log <== Mon Jul 30 10:34:27 2007 -> /var/spool/filter/in.6255.20070730103427: Eicar-Test-Signature FOUND
- Teste 2, codigo malicioso na mensagem
root@sua-workstation-de-teste:~# mail -s "teste" usuario@dominio.com.br
X5O!P%@AP[4PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H* . CC:
agora vamos verificar o log novamente.
==> /var/log/mail.info <== Jul 30 10:45:59 voyager postfix/cleanup[6422]: 2876E77521: message-id=<1185806754.6017.10.camel@defiant> Jul 30 10:45:59 voyager postfix/qmgr[5782]: 2876E77521: from=<guto@gutocarvalho.net>, size=641, nrcpt=1 (queue active) Jul 30 10:45:59 voyager postfix/virus-filter: message-id=<1185806754.6017.10.camel@defiant> reject: VIRUS from=<guto@gutocarvalho.net> to=<listas@gutocarvalho.net> Jul 30 10:45:59 voyager postfix/virus-filter: message-id=<1185806754.6017.10.camel@defiant> reject: VIRUS from=<guto@gutocarvalho.net> to=<listas@gutocarvalho.net>
Veja se funcionar como descrito o usuário que mandou o vírus vai receber uma mensagem do MTA com a seguinte MSG.
Return-Path: <> X-Original-To: guto@gutocarvalho.net Delivered-To: guto@gutocarvalho.net Received: by mail.gutocarvalho.net (Postfix, from userid 110) id 98BB877525; Mon, 30 Jul 2007 10:34:37 -0400 (AMT) X-Spam-Checker-Version: SpamAssassin _VERSION (2006-10-05) on voyager X-Spam-Level: X-Spam-Status: No, hits=-0.0 required=4.0 tests=NO_RECEIVED,NO_RELAYS version=3.1.7-deb De: Virus Scanner <mailer-daemon@mail.gutocarvalho.net> Assunto: AVISO: Email rejeitado: VIRUS Detectado Para: guto@gutocarvalho.net Message-Id: <20070730143437.98BB877525@mail.gutocarvalho.net> Data: Mon, 30 Jul 2007 10:34:37 -0400 (AMT) X-Evolution-Source: pop://guto%40gutocarvalho.net@pop.gutocarvalho.net/ Mime-Version: 1.0 Seu email para (listas@gutocarvalho.net) com assunto ( sera que pega?) foi rejeitado por conter virus. Virus encontrados: Eicar-Test-Signature FOUND
esta msg pode ser configurada no script do clamav-filter, que está em /usr/lib/postfix/clamav-filter
checando spamassassin
se ver mensagens como abaixo a integração do spamassassin com clamav-filter estará perfeita.
root@voyager:~# tail -f /var/log/mail.log
Jul 30 10:55:38 voyager spamd[4350]: spamd: identified spam (18.3/4.0) for clamav:110 in 13.8 seconds, 4086 bytes. Jul 30 10:55:38 voyager spamd[4350]: spamd: result: Y 18 - HTML_MESSAGE,HTML_OBFUSCATE_10_20,RAZOR2_CF_RANGE_51_100,RAZOR2_CF_RANGE_E8_51_100,RAZOR2_CHECK,URIBL_AB_SURBL,URIBL_JP_SURBL,URIBL_OB_SURBL,URIBL_SC_SURBL,URIBL_WS_SURBL scantime=13.8,size=4086,user=clamav,uid=110,required_score=4.0,rhost=localhost,raddr=127.0.0.1,rport=36072,mid=<656380318.24930185074963@bigape.com>,autolearn=no
testando postgrey
postgrey funcionando corretamente.
root@voyager:~# tail -f /var/log/mail.log
Jul 30 10:54:15 voyager postfix/smtpd[6544]: NOQUEUE: reject: RCPT from ip-85-144.wnet.cz[62.77.85.144]: 450 4.7.1 <deffente@rcon.com.br>: Recipient address rejected: Greylisted, see http://isg.ee.ethz.ch/tools/postgrey/help/rcon.com.br.html; from=<zesupport@zacks.com> to=<deffente@rcon.com.br> proto=SMTP helo=<ip-85-144.wnet.cz>
checando postfix-spf
postfix/spf checando corretamente
root@voyager:~# tail -f /var/log/mail.log|grep spf
Dec 27 15:14:30 gutocarvalho postfix/policy-spf[21470]: handler sender_policy_framework: is decisive. Dec 27 15:14:30 gutocarvalho postfix/policy-spf[21470]: : Policy action=PREPEND Received-SPF: none (bonnenkrant.com: No applicable sender policy available) receiver=gutocarvalho.net; identity=mfrom; envelope-from="ilcs@bonnenkrant.com"; helo=corporat190-025204002.sta.etb.net.co; client-ip=190.25.204.2
instalando ferramenta de relatorios
instalando o programa
root@voyager:~# apt-get install pflogsumm
vamos copiar um exemplo de script para relatórios diários
root@voyager:~# cp /usr/share/doc/pflogsumm/examples/example.cron.daily /etc/cron.daily/pflogsumm
agora vamos ajustá-lo.
root@voyager:~# vim /etc/cron.daily/pflogsumm
#!/bin/sh
#
# Debian pflogsumm daily cron script
#
# This script analyses the logfile for statistics and problems.
#
DATA=`date --date=yesterday +%Y%m%d`
if [ -x /usr/sbin/pflogsumm.pl ]; then
/usr/sbin/pflogsumm.pl -d yesterday --problems_first /var/log/mail.log > /var/www/relatorios/pflogsumm/relatorio-posfix-pflogsumm-$DATA.txt
fi
não se esqueça de ajustar as permissões do script e criar o diretório dos relatórios
root@voyager:~# chmod 700 /etc/cron.daily/pflogsumm
root@voyager:~# mkdir -p /var/www/relatorios/pflogsumm
instalando mailgraph
instalando o programa
root@voyager:~# apt-get install mailgraph
para acessá-lo vá até http://ip-do-servidor/cgi-bin/mailgraph.cgi
instalando o pfqueue
excelente ferramenta para ver a fila de mensagens no console
root@voyager:~# apt-get install pfqueue
instalando queuegraph
instalando o programa para gerar gráficos da fila de mensagens
root@voyager:~# apt-get install queuegraph
para acessá-lo vá até http://ip-do-servidor/cgi-bin/queuegraph.cgi
instalando couriergraph
instalando o programa para gerar gráficos de uso do courier imap e pop
root@voyager:~# apt-get install couriergraph
para acessá-lo vá até http://ip-do-servidor/cgi-bin/couriergraph.cgi
arquivo de controle dos daemons
criando o arquivo
root@voyager:~# vim /usr/sbin/pfctl
ele deve ter este conteúdo
#!/bin/bash
up="clamav-daemon spamassassin postgrey postfix courier-authdaemon courier-imap courier-imap-ssl courier-pop courier-pop-ssl"
down="postfix postgrey clamav-daemon spamassassin courier-pop-ssl courier-pop courier-imap-ssl courier-imap courier-authdaemon"
start(){
for i in $up;do
/etc/init.d/$i start
done
}
stop(){
for i in $down;do
/etc/init.d/$i stop
done
}
status(){
for i in $daemon;do
/etc/init.d/$i status
done
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart)
stop
start
;;
*)
echo comando invalido.
;;
esac
exit 0
setando permissoes
root@voyager:~# chmod 700 /usr/sbin/pfctl
agora para usar digite apenas no console
root@voyager:~# pfctl stop
root@voyager:~# pfctl start
root@voyager:~# pfctl restart
alias
é legal criar alguns alias para facilitar a observação dos logs.
eu geralmente coloco isto no final do /root/.bashrc
root@voyager:~# vim /root/.bashrc
alias l='ls -lh' alias la='ls -lha' alias rm='rm -i' alias mv='mv -i' alias cp='cp -i' alias tm='tail -f /var/log/messages' alias td='tail -f /var/log/daemon.log' alias ta='tail -f /var/log/auth.log' alias tu='tail -f /var/log/user.log' alias tk='tail -f /var/log/kern.log' alias tp='tail -f /var/log/auth.log /var/log/mail.log /var/log/mail.info /var/log/mail.warn /var/log/mail.err /var/log/clamav/clamav.log'
assim quando quero ver log do serviço de e-mail digito apenas tp.
roundcube webmail
vamos fazer o download do roundcube
root@voyager:~# cd /var/www
root@voyager:/var/www# wget http://ufpr.dl.sourceforge.net/sourceforge/roundcubemail/roundcubemail-0.1-rc2.tar.gz
root@voyager:/var/www# tar zxvf roundcubemail-0.1-rc2.tar.gz
root@voyager:/var/www# cd roundcubemail-0.1-rc2
root@voyager:/var/www# cp config/db.inc.php.dist config/db.inc.php
root@voyager:/var/www# cp config/main.inc.php.dist config/main.inc.php
agora vamos editar o arquivo db.inc.php para e ajustar a linha 68
root@voyager:/var/www# vim config/db.inc.php
$rcmail_config['db_dsnw'] = 'mysql://usuario:senha@127.0.0.1/nomedobanco';
agora vamos criar o banco, entre no mysql
root@voyager:/var/www# mysql -u root -p
mysql> create database nomedobanco;
mysql> grant all privileges on nomedobanco.* to usuario@localhost identified by 'suasenha';
feito isto vamos criar um link simbolico
root@voyager:/var/www# ln -s roundcubemail-0.1-rc2 webmail
Agora vamos importar o sql no banco criado.
root@voyager:/var/www# mysql roundcubemail < SQL/mysql5.initial.sql
agora vamos acessar pelo navegador no endereço: http://seu-endereco-ip/webmail/
mailman
em breve...
sympa
em breve...
referências
- IMAP
- TCP-IP Modelo
- postfix
- clamav-filter
- spamassassin
- Greylist
- SPF
- tutoriais
- http://flurdy.com/docs/postfix/
- http://workaround.org/articles/ispmail-sarge/#postfix-sasl
- http://www.howtoforge.com/perfect_setup_ubuntu704
- https://help.ubuntu.com/community/PostfixCompleteVirtualMailSystemHowto
- http://www.vivaolinux.com.br/artigos/verArtigo.php?codigo=526
- http://www.secforum.com.br/article.php?sid=3402
- http://www.vivaolinux.com.br/artigos/verArtigo.php?codigo=1243
- http://mteixeira.webset.net/artigos/antispam-suse100.html
- http://www.howtoforge.com/postfix_antispam_mailscanner_clamav_ubuntu

