Arquivos históricos do BR-Linux.org apresenta:

Configurando o MTA PostFix no CL9

Excelente tutorial muito completo ensinando a configurar o servidor de email Postfix no Conectiva 9.0 com mais uma série de opções ( POSTFIX-2 + COURIER-IMAP + MYSQL + MAILDROP + POSTFIXADMIN + SQUIRRELMAIL + CLAMAV + CLAMAV-FILTER + SPAMASSASSIM ) .

Enviado por Alexandro Batista (alexandrobatista@pop.com.br).

Configurando o MTA PostFix no CL9

( POSTFIX-2 + COURIER-IMAP + MYSQL + MAILDROP + POSTFIXADMIN
+ SQUIRRELMAIL + CLAMAV + CLAMAV-FILTER + SPAMASSASSIM )


Revisado por: Alexandro Batista
Email: alexandrobatista@pop.com.br
Data: 7/06/2004

Autor - TUTORIAL DE INSTALACAO DO POSTFIX + OPÇÕES
Marco A. S. Máximo
Email: marco.maximo@pwo.com.br
Data: 20.01.2004

Autor - TUTORIAL DE INSTALACAO DO CLAMAV
Gleydson Soares
Email: gsoares@securityanalyze.com
Deives Michellis "thefallen"
Email: dmichellis@yahoo.com
Colaboradores
David da Guia Carvalho
Email: dguiarj@globo.com
Data: 19.05.2004


========================================
ANTES DE COMEÇAR
========================================


- O autor do tutorial não pode ser responsabilizado por qualquer dano causado pela utilização do mesmo. Você está utilizando por livre e espontânea vontade.

- Crie o diretório /source , pois esse diretório será usado para compilar os fontes. Isso não influencia em absolutamente NADA na instalação, apenas para nao digitar /usr/local/src.

- Toda instalação será executada como ROOT, apenas a compilação do COURIER-IMAP que será feita por um usuário normal.

- Aonde aparecer os caracteres "xxxxx", troque pela sua senha correspondente.

- Crie o grupo e usuário para o MAILDROP

[root@localhost root]# groupadd -g 108 maildrop
[root@localhost root]# useradd -r -d /var/spool/mail/ -g 108 -u 108 -s /bin/false -M maildrop


========================================
INSTALANDO O MYSQL
========================================


Estou utilizando o MySQL que vem junto com a distribuição.

Execute o comando "mysql_createdb" para cria o bando de dados:

[root@localhost root]# mysql_createdb

This script will create the main mysql database where user passwords and general permissions are stored. It will also ask you to configure the root password o that a blank one does not get asigned. Please, type the root password :"xxxxx"


DICA (Para abilitar o log do MySQL):

Esse recurso é muito útil para identificar alguns erros durante a instalação de aplicativos que fazem acesso ao banco. Para resolver esse problema, edite o arquivo /etc/my.cnf com o seguinte conteúdo:

[root@localhost root]# vi /etc/my.cnf

#=============== INICIO /etc/my.cnf =================
[mysql.server]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

[mysqladmin]
socket=/var/lib/mysql/mysql.sock

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
language=/usr/share/mysql/portuguese/
log=/var/lib/mysql/mysqld.log

[mysql]
socket=/var/lib/mysql/mysql.sock
#=============== FIM do /etc/my.cnf =================

Crie o arquivo de log e mude a permissão:

[root@localhost root]# touch /var/lib/mysql/mysqld.log
[root@localhost root]# chown mysql:mysql /var/lib/mysql/mysqld.log
[root@localhost root]# cds
[root@localhost init.d]# ./mysql start

Iniciando mysql: Starting mysqld daemon with databases from
/var/lib/mysql [ OK ]


Insira no final do arquivo /etc/rc.d/rc.local a seguinte linha para poder
iniciar o servico do mysql se caso tiver que reiniciar a maquina.

/etc/init.d/mysql start

Beleza! Vamos agora criar as tabelas para o POSTFIX.
Crie um arquivo com o nome "postfix_mysq.db" com o seguinte conteúdo:

ATENÇÃO:
- Substitua, no primeiro bloco, o valor "xxxxx" pela senha do usuário do postfix.
- Substitua, caso queira, o diretório aonde ficaram as caixas postais dos usuários, o último bloco no campo home. No meu caso estou usando o diretório "/postfix/"

[root@localhost init.d]# cd /source/db/
OBs.: Me refiro aqui como o postfix_mysq.db ja esteja neste diretorio, nada impede e vc utilizar outro diretorio.

Se quiser visualizar o arquivo execute o comando de visualizacao ou se preferir edita-lo, execute-o com o editor que melhor lhe convem:
# ===================== INICIO DO postfix_mysq.db ======
#
# Postfix / MySQL
#
# Cria o usuário e senha do Postfix e Maildrop para
# acesso ao banco
#
USE mysql;
INSERT INTO user (Host, User, Password) VALUES
('localhost','postfix',password('xxxxx'));
INSERT INTO user (Host, User, Password) VALUES
('localhost','maildrop',password('xxxxx'));
#
INSERT INTO db (Host, Db, User, Select_priv) VALUES
('localhost','postfix','postfix','Y');
INSERT INTO db (Host, Db, User, Select_priv) VALUES
('localhost','postfix','maildrop','Y');
#
FLUSH PRIVILEGES;
#
# Cria o banco postfix
#
CREATE DATABASE postfix;
#
# Cria a estrutura da tabela alias
#
USE postfix;
CREATE TABLE alias (
address varchar(255) NOT NULL default '',
goto text NOT NULL,
domain varchar(255) NOT NULL default '',
create_date datetime NOT NULL default '0000-00-00 00:00:00',
change_date datetime NOT NULL default '0000-00-00 00:00:00',
active tinyint(4) NOT NULL default '1',
PRIMARY KEY (address)
) TYPE=MyISAM COMMENT='Virtual Aliases - mysql_virtual_alias_maps';
#
# Cria a estrutura da tabela domain
#
USE postfix;
CREATE TABLE domain (
domain varchar(255) NOT NULL default '',
description varchar(255) NOT NULL default '',
transport varchar(255) NOT NULL default 'maildrop',
create_date datetime NOT NULL default '0000-00-00 00:00:00',
change_date datetime NOT NULL default '0000-00-00 00:00:00',
active tinyint(4) NOT NULL default '1',
PRIMARY KEY (domain)
) TYPE=MyISAM COMMENT='Virtual Domains - mysql_virtual_domains_maps';
#
# Cria a estrutura da tabela mailbox
#
USE postfix;
CREATE TABLE mailbox (
username varchar(255) NOT NULL default '',
password varchar(255) NOT NULL default '',
name varchar(255) NOT NULL default '',
home char(255) default '/postfix/',
maildir varchar(255) NOT NULL default '',
quota varchar(255) NOT NULL default '100000000S', # 100 MB
domain varchar(255) NOT NULL default '',
create_date datetime NOT NULL default '0000-00-00 00:00:00',
change_date datetime NOT NULL default '0000-00-00 00:00:00',
active tinyint(4) NOT NULL default '1',
passwd_expire enum('N','Y') default 'Y',
uid int(10) unsigned default '108',
gid int(10) unsigned default '108',
PRIMARY KEY (username)
) TYPE=MyISAM COMMENT='Virtual Mailboxes - mysql_virtual_mailbox_maps';
#
#================================================
#
# POSTFIXADMIN / MYSQL
#
# Cria a tabela para o PostfixAdmin
#
# Cria o usuário de administração do PostfixAdmin
#
USE mysql;
INSERT INTO user (Host, User, Password) VALUES
('localhost','postfixadmin',password('xxxxx'));
#
INSERT INTO db (Host, Db, User, Select_priv, Insert_priv, Update_priv,
Delete_priv) VALUES ('localhost', 'postfix', 'postfixadmin', 'Y', 'Y', 'Y',
'Y');
FLUSH PRIVILEGES;
#
# Cria a tabela de administração do PostfixAdmin
#
USE postfix;
CREATE TABLE admin (
username varchar(255) NOT NULL default '',
password varchar(255) NOT NULL default '',
domain varchar(255) NOT NULL default '',
create_date datetime NOT NULL default '0000-00-00 00:00:00',
change_date datetime NOT NULL default '0000-00-00 00:00:00',
active tinyint(4) NOT NULL default '1',
PRIMARY KEY (username)
) TYPE=MyISAM COMMENT='Virtual Admins - Store Virtual Domain Admins';
#
#==============================================
#
# VACATION / MYSQL
#
# Cria a tabela do Vacation
#
USE postfix;
CREATE TABLE vacation (
email varchar(255) NOT NULL default '',
subject varchar(255) NOT NULL default '',
body text NOT NULL,
cache text NOT NULL
) TYPE=MyISAM COMMENT='Virtual Vacation - Vacation Daemon Table';
#
#=================================================
#
# WEBMAIL / MYSQL
#
# Cria as tabelas do Webmail squirrelmail
#
# Cria o usuário "squirreluser" e da permissão de acesso ao banco "webmail"
#
USE mysql;
INSERT INTO user (Host,User,Password) VALUES
('localhost','squirreluser',password('xxxxx'));
INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv)
VALUES ('localhost','webmail','squirreluser','Y','Y','Y','Y');
FLUSH PRIVILEGES;
#
CREATE DATABASE webmail;
USE webmail;
#
# Tabela de preferência dos usuários 'userprefs'
#
CREATE TABLE userprefs (
user varchar(128) NOT NULL default '',
prefkey varchar(64) NOT NULL default '',
prefval blob NOT NULL,
PRIMARY KEY (user,prefkey)
) TYPE=MyISAM;
#
# Tabela do livro de endereço dos usuários 'address'
#
CREATE TABLE address (
owner varchar(128) NOT NULL default '',
nickname varchar(16) NOT NULL default '',
firstname varchar(128) NOT NULL default '',
lastname varchar(128) NOT NULL default '',
email varchar(128) NOT NULL default '',
label varchar(255) default NULL,
PRIMARY KEY (owner,nickname),
KEY firstname (firstname,lastname)
) TYPE=MyISAM;
#
# ===================== FIM DO postfix_mysq.db =======

Depois do arquivo criado, execute o comando:

[root@localhost db]# mysql -u root -p < postfix_mysq.db


O banco e as tabelas, bem como o usuários do postfix serão criados. Vamos testar o acesso do usuário postfix:
[root@localhost /]# mysql postfix -p
mysql> show tables;
Tables_in_postfix
+-------------------+
admin
alias
domain
domain_admins
log
mailbox
vacation
+-------------------+

mysql> exit


========================================
INSTALANDO O COURIER-IMAP
========================================

download courier-imap

Como iremos utilizar o Postfix com suporte a Maildir ao estilo Qmail, então o
Courier-IMAP é o programa que permite o acesso a esse tipo de caixa postal. Ele também vai ser responsável por validar os logins dos usuários e permitir que eles encontrem as suas mensagens por POP3 ou acesso por IMAP. Tudo isso, lendo informações da tabela "mailbox" no MySQL.

Descompacte o arquivo no diretorio /source:

Para compilar o courier você precisa estar como usuário comum, se você descompactou como root, mude as permissões do diretório para seu usuário, no meu caso "alex":

[root@localhost source]# chown -R alex:alex courier-imap-3.0.3/
[root@localhost source]# exit

Conectiva Linux 9
Kernel 2.4.x-x_4cl

localhost login: alex
Password:

[alex@localhost alex]$ cd /source/courier-imap-3.0.3/

[alex@localhost courier-imap-3.0.3]$ ./configure --prefix=/usr/ --sysconfdir=/etc/courier --libexecdir=/usr/lib/courier --with-redhat

[alex@localhost courier-imap-3.0.3]$ make

Caso ocorra algum erro, pode ser a falta dos pacotes gdbm e gdbm-devel, usados ara a autenticação com biblitecas GDBM com o módulo authuserdb. Esse processo demora um pouco e pode dar a impressão que o programa entrou em loop, não se preocupe isso é normal. Após o configure terminar devemos agora compila-lo:

Após a compilação, logue-se como ROOT e instale o courier-imap:

[alex@localhost courier-imap-3.0.3]$ exit


Conectiva Linux 9
Kernel 2.4.x-x_4cl

localhost login: root
Password:

[root@localhost root]# cd /source/courier-imap-3.0.3/

[root@localhost courier-imap-3.0.3]# make install


Configurando
---------------

[root@localhost courier-imap-3.0.3]# cd /etc/courier/
[root@localhost courier]# cp imapd.dist imapd
[root@localhost courier]# cp imapd-ssl.dist imapd-ssl
[root@localhost courier]# cp pop3d.dist pop3d
[root@localhost courier]# cp pop3d-ssl.dist pop3d-ssl
[root@localhost courier]# cp authmysqlrc.dist authmysqlrc
[root@localhost courier]# cp authdaemonrc.dist authdaemonrc
[root@localhost courier]# cp quotawarnmsg.example quotawarnmsg
[root@localhost courier]# mkdir dist
[root@localhost courier]# mv *.dist *.example dist/

Isso criará os seguintes arquivos de configuração do courier ( imapd, pop3d, authmysqlrc, authdaemonrc, imapd-ssl, pop3d-ssl) esses 2 últimos para conexões seguras.

DICA:
Acho interesante manter os arquivos *.dist, isso ira ajudar caso você queira lembrar das configurações default do courier.

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 o Courier para que ele conecte no MySQL e autentique os usuários. Edite-o conforme as suas configurações.

Exemplo:

[root@localhost courier]# vi authmysqlrc
#==================== INICIO AUTHMYSQLRC ============
##VERSION: $Id: authmysqlrc,v 1.16 2004/01/19 19:34:09 mrsam Exp $
#
# Copyright 2000-2004 Double Precision, Inc. See COPYING for
# distribution information.
#
# Do not alter lines that begin with ##, they are used when upgrading
# this configuration.
#
# authmysqlrc created from authmysqlrc.dist by sysconftool
#
# DO NOT INSTALL THIS FILE with world read permissions. This file
# might contain the MySQL admin password!
#
# Each line in this file must follow the following format:
#
# field[spaces|tabs]value
#
# That is, the name of the field, followed by spaces or tabs, followed by
# field value. Trailing spaces are prohibited.


##NAME: LOCATION:0
#
# The server name, userid, and password used to log in.

MYSQL_SERVER localhost
MYSQL_USERNAME postfix
MYSQL_PASSWORD xxxxx # senha do usuario postfix

##NAME: MYSQL_SOCKET:0
#
# MYSQL_SOCKET can be used with MySQL version 3.22 or later, it specifies the
# filesystem pipe used for the connection
#
# MYSQL_SOCKET /var/mysql/mysql.sock
MYSQL_SOCKET /var/lib/mysql/mysql.sock
##NAME: MYSQL_PORT:0
#
# MYSQL_PORT can be used with MySQL version 3.22 or later to specify a port to
# connect to.

MYSQL_PORT 3306

##NAME: MYSQL_OPT:0
#
# Leave MYSQL_OPT as 0, unless you know what you're doing.

MYSQL_OPT 0

##NAME: MYSQL_DATABASE:0
#
# The name of the MySQL database we will open:

MYSQL_DATABASE postfix

##NAME: MYSQL_USER_TABLE:0
#
# The name of the table containing your user data. See README.authmysqlrc
# for the required fields in this table.

MYSQL_USER_TABLE mailbox

##NAME: MYSQL_CRYPT_PWFIELD:0
#
# Either MYSQL_CRYPT_PWFIELD or MYSQL_CLEAR_PWFIELD must be defined. Both
# are OK too. crypted passwords go into MYSQL_CRYPT_PWFIELD, cleartext
# passwords go into MYSQL_CLEAR_PWFIELD. Cleartext passwords allow
# CRAM-MD5 authentication to be implemented.

MYSQL_CRYPT_PWFIELD password

##NAME: MYSQL_CLEAR_PWFIELD:0
#
#
# MYSQL_CLEAR_PWFIELD clear

##NAME: MYSQL_DEFAULT_DOMAIN:0
#
# If DEFAULT_DOMAIN is defined, and someone tries to log in as 'user',
# we will look up 'user@DEFAULT_DOMAIN' instead.
#
#
# DEFAULT_DOMAIN example.com

##NAME: MYSQL_UID_FIELD:0
#
# Other fields in the mysql table:
#
# MYSQL_UID_FIELD - contains the numerical userid of the account
#
MYSQL_UID_FIELD uid

##NAME: MYSQL_GID_FIELD:0
#
# Numerical groupid of the account

MYSQL_GID_FIELD gid

##NAME: MYSQL_LOGIN_FIELD:0
#
# The login id, default is id. Basically the query is:
#
# SELECT MYSQL_UID_FIELD, MYSQL_GID_FIELD, ... WHERE id='loginid'
#

MYSQL_LOGIN_FIELD username

##NAME: MYSQL_HOME_FIELD:0
#

MYSQL_HOME_FIELD home

##NAME: MYSQL_NAME_FIELD:0
#
# The user's name (optional)

MYSQL_NAME_FIELD name

##NAME: MYSQL_MAILDIR_FIELD:0
#
# This is an optional field, and can be used to specify an arbitrary
# location of the maildir for the account, which normally defaults to
# $HOME/Maildir (where $HOME is read from MYSQL_HOME_FIELD).
#
# You still need to provide a MYSQL_HOME_FIELD, even if you uncomment this
# out.
#
# MYSQL_MAILDIR_FIELD maildir
MYSQL_MAILDIR_FIELD maildir
##NAME: MYSQL_DEFAULTDELIVERY:0
#
# Courier mail server only: optional field specifies custom mail delivery
# instructions for this account (if defined) -- essentially overrides
# DEFAULTDELIVERY from ${sysconfdir}/courierd
#
# MYSQL_DEFAULTDELIVERY defaultdelivery

##NAME: MYSQL_QUOTA_FIELD:0
#
# Define MYSQL_QUOTA_FIELD to be the name of the field that can optionally
# specify a maildir quota. See README.maildirquota for more information
#
# MYSQL_QUOTA_FIELD quota
MYSQL_QUOTA_FIELD quota
##NAME: MYSQL_AUXOPTIONS:0
#
# Auxiliary options. The MYSQL_AUXOPTIONS field should be a char field that
# contains a single string consisting of comma-separated "ATTRIBUTE=NAME"
# pairs. These names are additional attributes that define various per-account
# "options", as given in INSTALL's description of the "Account OPTIONS"
# setting.
#
# MYSQL_AUXOPTIONS_FIELD auxoptions
#
# You might want to try something like this, if you'd like to use a bunch
# of individual fields, instead of a single text blob:
#
# MYSQL_AUXOPTIONS_FIELD
CONCAT("allowimap=",allowimap,",allowpop3=",allowpop3,",allowwebmail=",allowwebm
ail,",sharedgroup=",sharedgroup)
#
# This will let you define fields called "allowimap", etc, with the end result
# being something that the OPTIONS parser understands.

##NAME: MYSQL_WHERE_CLAUSE:0
#
# This is optional, MYSQL_WHERE_CLAUSE can be basically set to an arbitrary
# fixed string that is appended to the WHERE clause of our query
#
# MYSQL_WHERE_CLAUSE server='mailhost.example.com'
MYSQL_WHERE_CLAUSE active=1
##NAME: MYSQL_SELECT_CLAUSE:0
#
# (EXPERIMENTAL)
# This is optional, MYSQL_SELECT_CLAUSE can be set when you have a database,
# which is structuraly different from proposed. The fixed string will
# be used to do a SELECT operation on database, which should return fields
# in order specified bellow:
#
# username, cryptpw, clearpw, uid, gid, home, maildir, quota, fullname, options
#
# The username field should include the domain (see example below).
#
# Enabling this option causes ignorance of any other field-related
# options, excluding default domain.
#
# There are two variables, which you can use. Substitution will be made
# for them, so you can put entered username (local part) and domain name
# in the right place of your query. These variables are:
# $(local_part), $(domain), $(service)
#
# If a $(domain) is empty (not given by the remote user) the default domain
# name is used in its place.
#
# $(service) will expand out to the service being authenticated: imap, imaps,
# pop3 or pop3s. Courier mail server only: service will also expand out to
# "courier", when searching for local mail account's location. In this case,
# if the "maildir" field is not empty it will be used in place of
# DEFAULTDELIVERY. Courier mail server will also use esmtp when doing
# authenticated ESMTP.
#
# This example is a little bit modified adaptation of vmail-sql
# database scheme:
#
# MYSQL_SELECT_CLAUSE SELECT CONCAT(popbox.local_part, '@', popbox.domain_name),
\
# CONCAT('{MD5}', popbox.password_hash), \
# popbox.clearpw, \
# domain.uid, \
# domain.gid, \
# CONCAT(domain.path, '/', popbox.mbox_name), \
# '', \
# domain.quota, \
# '', \
# CONCAT("allowimap=",allowimap,",allowpop3=", \
# allowpop3,",allowwebmail=",allowwebmail, \
# ",sharedgroup=",sharedgroup) \
# FROM popbox, domain \
# WHERE popbox.local_part = '$(local_part)' \
# AND popbox.domain_name = '$(domain)' \
# AND popbox.domain_name = domain.domain_name


##NAME: MYSQL_ENUMERATE_CLAUSE:0
#
# {EXPERIMENTAL}
# Optional custom SQL query used to enumerate accounts for authenumerate,
# in order to compile a list of accounts for shared folders. The query
# should return the following fields: name, uid, gid, homedir, maildir
#
# Example:
# MYSQL_ENUMERATE_CLAUSE SELECT CONCAT(popbox.local_part, '@',
popbox.domain_name), \
# domain.uid, \
# domain.gid, \
# CONCAT(domain.path, '/', popbox.mbox_name), \
# '' \
# FROM popbox, domain \
# WHERE popbox.local_part = '$(local_part)' \
# AND popbox.domain_name = '$(domain)' \
# AND popbox.domain_name = domain.domain_name

##NAME: MYSQL_CHPASS_CLAUSE:0
#
# (EXPERIMENTAL)
# This is optional, MYSQL_CHPASS_CLAUSE can be set when you have a database,
# which is structuraly different from proposed. The fixed string will
# be used to do an UPDATE operation on database. In other words, it is
# used, when changing password.
#
# There are four variables, which you can use. Substitution will be made
# for them, so you can put entered username (local part) and domain name
# in the right place of your query. There variables are:
# $(local_part) , $(domain) , $(newpass) , $(newpass_crypt)
#
# If a $(domain) is empty (not given by the remote user) the default domain
# name is used in its place.
# $(newpass) contains plain password
# $(newpass_crypt) contains its crypted form
#
# MYSQL_CHPASS_CLAUSE UPDATE popbox \
# SET clearpw='$(newpass)', \
# password_hash='$(newpass_crypt)' \
# WHERE local_part='$(local_part)' \
# AND domain_name='$(domain)'
#
#
#==================== FIM AUTHMYSQLRC ===============

ATENÇÃO:
Não deixe espaços ou tab no começo do nome Exemplo:

MYSQL_MAILDIR_FIELD maildir
MYSQL_QUOTA_FIELD quota

Isso causa erro para o Maildrop.

MYSQL_QUOTA_FIELD quota

Criar link

[root@localhost courier]# cds
[root@localhost init.d]# ln -s /usr/lib/courier/imapd.rc imapd
[root@localhost init.d]# ln -s /usr/lib/courier/pop3d.rc pop3d

Inicie o serviço

[root@localhost init.d]# ./imapd start
[root@localhost init.d]# ./pop3d start

Coloque as seguintes linhas no arquivo /etc/rc.d/rc.local para que os serviços
IMAP e POP3 sejam iniciados automaticamente durante a inicialização da máquina.

/etc/init.d/imapd start
/etc/init.d/pop3d start

Teste se os serviços IMAP e POP iniciaram sem problema, vamos rodar os seguintes
comandos:

[root@localhost init.d]# ps ax
/usr/lib/courier/authlib/authdaemond.mysql start
/usr/lib/courier/authlib/authdaemond.mysql start
/usr/lib/courier/authlib/authdaemond.mysql start
/usr/lib/courier/couriertcpd -address=0 -stderrlogger
/usr/lib/courier/authlib/authdaemond.mysql start
/usr/lib/courier/authlib/authdaemond.mysql start
/usr/lib/courier/authlib/authdaemond.mysql start
/usr/lib/courier/courierlogger imapd
/usr/lib/courier/couriertcpd -address=0 -stderrlogger
/usr/lib/courier/courierlogger pop3d

Deve aparecer algo como isso. As linhas indicam que os serviços imap e pop3
subiram usando a autenticação pelo MySQL. Vamos checar se as portas dos serviços
estão abertas e respondendo:

[root@localhost init.d]# netstat -a | less
tcp 0 0 *:mysql *:* OUÇA
tcp 0 0 *:pop-3 *:* OUÇA
tcp 0 0 *:imap2 *:* OUÇA


Teste do IMAP
---------------

[root@localhost init.d]# 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-2004 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.


Teste do POP3
----------------

[root@localhost init.d]# telnet 0 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.

Se aparecer isso, então esta ok.


========================================
INSTALANDO O MAILDROP
========================================

download maildrop


O Maildrop será responsável pela entrega propriamente dita da mensagem à sua
respectiva caixa postal. Ele também fará o controle da cota de disco. Com o
Maildrop você também poderá implementar algumas regras de filtragem.
Descompacte o arquivo que baixou na net no diretorio /source/.


Instalando
-------------

[root@localhost init.d]# cd /source/maildrop-1.6.3
[root@localhost maildrop-1.6.3]# ./configure
--prefix=/usr/
--sysconfdir=/etc/maildrop
--enable-maildrop-uid=108
--enable-maildrop-gid=108
--enable-syslog=1
--enable-maildropmysql
--enable-maildirquota


[root@localhost maildrop-1.6.3]# make


Antes de instalar, certifique-se que a compilação deu certo hablitando o suporte
do MySQL ao Maildrop:

[root@localhost maildrop-1.6.3]# ./maildrop/maildrop -v

maildrop 1.6.3 Copyright 1998-2003 Double Precision, Inc.
GDBM extensions enabled.
Maildir quota extension enabled.
Virtual user database via MySQL extension enabled.
This program is distributed under the terms of the GNU General Public
License. See COPYING for additional information.

Beleza !!!


[root@localhost maildrop-1.6.3]# make install

[root@localhost maildrop-1.6.3]# mkdir /etc/maildrop
[root@localhost maildrop-1.6.3]# cp maildropmysql.config /etc/
[root@localhost maildrop-1.6.3]# cp maildir/quotawarnmsg /etc/maildrop


Configurando o MAILDROP
-------------------------

Configure o Maildrop para acessar o MySQL. Edite o arquivo
/etc/maildropmysql.config

[root@localhost maildrop-1.6.3]# vi /etc/maildropmysql.config
# ============ INICIO DO maildropmysql.config ==========
# The attributes are:
#
# mail - The full email address of the user (ie user@yourdomain.com)
# This is the primary attribute searched upon by maildrop.
#
# maildir - The location (full path including name) of the users
# mail directory (Maildir)
#
# homedirectory - The location (full path including name) of the
# users home directory. This may be the same as the
# users maildir.
#
# uidnumber - The uid of the user that owns the mail files for
# this user. This may be a specific uid per user,
# or a single uid for every user (full 'virtual' user
# configuration), or a combination.
#
# gidnumber - The gid of the user that owns the mail files for
# this user. This may be a specific gid per user,
# or a single gid for every user (full 'virtual' user
# configuration), or a combination.
#
# quota - *OPTIONAL* The quota for this user. If blank, or
# non-existent defaults to no quota.
# mailstatus - account status
#
# A sample LDAP entry is given at the end of this file.
#
# --- Actual configuration begins here -----------------------------

# hostname - host name of your ldap server
hostname localhost
port 3306
socket /var/lib/mysql/mysql.sock
database postfix
dbuser maildrop
dbpw xxxxx # senha do usuario maildrop
dbtable mailbox

#not used now
#timeout 5

# default_uid - default uid (number only) to use incase uidnumber attribute not
# found in users mysql entry
default_uidnumber 108

# default_gid - default gid (number only) to use incase gidnumber attribute not
# found in users ldap entry
default_gidnumber 108

# MySQL Field definitions
#
# This section allows you to specify the actual attributes you
# use in your Mysql record
#
# The example attribute mapping shown below is also the default
# mapping used by maildrop in the case that any are missing

# UID_FIELD - MySQL attribute which contains the users name (w or w/o domain)
uid_field username

# UIDNUMBER_FIELD - MySQL attribute which contains the system uid to deliver
# mail as
uidnumber_field uid

# GIDNUMBER_FIELD - MySQL attribute which contains the system gid to deliver
# mail as
gidnumber_field gid

# MAILDIR_FIELD - MySQL attribute which contains the path to the users
# custom maildir
maildir_field maildir

# HOMEDIRECTORY_FIELD - MySQL attribute which contains the path to the users
# home directory
homedirectory_field home

# QUOTA_FIELD - MySQL attribute which contains the users quota
quota_field quota

# MYSQL_DEFAULT_STATUS_FIELD - MySQL attribute which could be created in the
# MySQL entry to set whether or not the user is allowed to receive email on
# this box..
# -- looks unused for now; but must be valid column ! (2001-11-03)
mailstatus_field active

# MYSQL_DEFAULT_WHERE_CLAUSE - This is optional !
# It can be set to any fixed string starting with keyword 'AND'.
# It will then be appended to the WHERE clause of our query.
where_clause ""
#
# ============ FIM DO maildropmysql.config ==========


DICA:
O Maildrop, possui um recurso de aviso de email para o usuário caso a sua caixa
postal ultrapasse a porcentagem de utilização de um valor especificado. Nesse
tutorial usarei o valor de 90% (explicado mais adiante.).
Sendo assim, você pode personalizar a mensagem de aviso que o usuário ira
receber, bastando para isso editar o arquivo "/etc/maildrop/quotawarnmsg"

Alterei a mensagem final para:

Sua caixa postal esta ultrapassando a 95% do total. De modo que voce possa
continuar recebendo seus email's, voce precisa remover algumas mensagens de sua
caixa postal.


========================================
INSTALANDO O POSTFIX
========================================

http://www.postfix.org

Vamos instalar o Postfix com suporte a Maildir+SASL+MySQL, na maioria das
distribuições isso não vem habilitado por padrão sendo necessário uma nova
compilação. O Postfix também não tem suporte a cota de disco com o formato
Maildir, sendo necessário, em alguns casos, a instalação de uma Patch para tal.
No nosso caso, como já explicado, a cota será administrada pelo MAILDROP, sendo
assim, não será necessário a instalação de nenhum PATCH.
Obs.: Deve estar instalada uma versao anterior (versao que vem com a distro) do
postfix para que os comandos abaixo funcionem.

Baixe o Postfix de:
postfix


Instalando
--------------

Descompact o arquivo no diretorio /source/

[root@localhost maildrop-1.6.3]# cd /source/postfix-2.0.19/
[root@localhost postfix-2.0.19]# make -f Makefile.init makefiles

'CCARGS=-DHAS_MYSQL
-I/usr/include/mysql -DUSE_SASL_AUTH
-I/usr/include/sasl'
'AUXLIBS=/usr/lib/libmysqlclient.so -lm
-L/usr/lib -R/usr/lib -lsasl2'

[root@localhost postfix-2.0.19]# make
[root@localhost postfix-2.0.19]# make upgrade

Verifique se o suporte ao MySQL foi habilitado:

[root@localhost postfix-2.0.19]# postconf -m
static
pcre
nis
regexp
environ
proxy
mysql
btree
unix
hash


Configurando o Postfix
-------------------------

Crie 4 arquivos dentro do diretório /etc/postfix/ com o seguinte conteúdo:

[root@localhost postfix-2.0.19]# cd /etc/postfix

mysql_virtual_alias_maps.cf
-----------------------------
user = postfix # Usuario postfix
password = xxxxx # Senha do usurario postfix
dbname = postfix
table = alias
select_field = goto
where_field = address
hosts = localhost

mysql_virtual_mailbox_maps.cf
------------------------------
user = postfix # Usuario postfix
password = xxxxx # Senha do usurario postfix
dbname = postfix
table = mailbox
select_field = maildir
where_field = username
hosts = localhost

mysql_transport_maps.cf
--------------------------
user = postfix # Usuario postfix
password = xxxxx # Senha do usurario postfix
dbname = postfix
table = domain
select_field = transport
where_field = domain
hosts = localhost

mysql_virtual_mailbox_limit_maps.cf
------------------------------------
user = postfix # Usuario postfix
password = xxxxx # Senha do usurario postfix
dbname = postfix
table = mailbox
select_field = quota
where_field = username
hosts = localhost

OBS: Não esqueça de configurar as linhas "user,password" conforme a sua
configuração.


MASTER.CF
------------

[root@localhost postfix]# vi master.cf


OBS:
Nesse ambiente, não irei utilizar o Postfix com a opção de CHROOT, sendo assim,
edite o /etc/postfix/master.cf e troque TODOS os "y" por "n" na coluna "chroot"
Ex:
----------------------------------------------------------------------
#service type private unpriv chroot wakeup maxproc command + args
smtp inet n - n - - smtpd
virtual unix - n n - - virtual
pickup fifo n - n 60 1 pickup
----------------------------------------------------------------------

Configure o suporte ao Maildrop:
----------------------------------------------------------------------
maildrop unix - n n - - pipe
flags=DRhu user=maildrop argv=/usr/bin/maildrop -w 95 -d ${recipient}
----------------------------------------------------------------------

OBS:
- A configuração da segunda linha, deve ter pelo menos 2 espaços no começo da
linha, conforme o exemplo.
- O parâmetro "-w 95", representa a porcentagem de utilização da caixa postal,
chegando a este limite o usuario e avisado pelo sistema. A mensagem de aviso é
enviado pelo MAILDROP com o conteúdo do arquivo "/etc/maildrop/quotawarnmsg"

MAIN.CF
---------

Faça o backup do arquivo original e modifique o /etc/postfix/main.cf com o
seguinte conteúdo:

[root@localhost postfix]# vi main.cf
#======================= INICIO MAIN.CF ===================================
# Global Postfix configuration file. This file lists only a subset
# of all 250+ parameters. See the sample-xxx.cf files for a full list.
#
# The general format is lines with parameter = value pairs. Lines
# that begin with whitespace continue the previous line. A value can
# contain references to other $names or ${name}s.
#
# NOTE - CHANGE NO MORE THAN 2-3 PARAMETERS AT A TIME, AND TEST IF
# POSTFIX STILL WORKS AFTER EVERY CHANGE.

# SOFT BOUNCE
#
# The soft_bounce parameter provides a limited safety net for
# testing. When soft_bounce is enabled, mail will remain queued that
# would otherwise bounce. This parameter disables locally-generated
# bounces, and prevents the SMTP server from rejecting mail permanently
# (by changing 5xx replies into 4xx replies). However, soft_bounce
# is no cure for address rewriting mistakes or mail routing mistakes.
#
#soft_bounce = no

# LOCAL PATHNAME INFORMATION
#
# The queue_directory specifies the location of the Postfix queue.
# This is also the root directory of Postfix daemons that run chrooted.
# See the files in examples/chroot-setup for setting up Postfix chroot
# environments on different UNIX systems.
#
queue_directory = /var/spool/postfix

# The command_directory parameter specifies the location of all
# postXXX commands.
#
command_directory = /usr/sbin

# The daemon_directory parameter specifies the location of all Postfix
# daemon programs (i.e. programs listed in the master.cf file). This
# directory must be owned by root.
#
daemon_directory = /usr/lib/postfix

# QUEUE AND PROCESS OWNERSHIP
#
# The mail_owner parameter specifies the owner of the Postfix queue
# and of most Postfix daemon processes. Specify the name of a user
# account THAT DOES NOT SHARE ITS USER OR GROUP ID WITH OTHER ACCOUNTS
# AND THAT OWNS NO OTHER FILES OR PROCESSES ON THE SYSTEM. In
# particular, don't specify nobody or daemon. PLEASE USE A DEDICATED
# USER.
#
mail_owner = postfix

# The default_privs parameter specifies the default rights used by
# the local delivery agent for delivery to external file or command.
# These rights are used in the absence of a recipient user context.
# DO NOT SPECIFY A PRIVILEGED USER OR THE POSTFIX OWNER.
#
default_privs = nobody

# INTERNET HOST AND DOMAIN NAMES
#
# The myhostname parameter specifies the internet hostname of this
# mail system. The default is to use the fully-qualified domain name
# from gethostname(). $myhostname is used as a default value for many
# other configuration parameters.
#
#myhostname = host.domain.tld
#myhostname = virtual.domain.tld
myhostname = dnsservidormail.dominio.com.br

# The mydomain parameter specifies the local internet domain name.
# The default is to use $myhostname minus the first component.
# $mydomain is used as a default value for many other configuration
# parameters.
#
#mydomain = domain.tld
mydomain = dominio.com.br

# SENDING MAIL
#
# The myorigin parameter specifies the domain that locally-posted
# mail appears to come from. The default is to append $myhostname,
# which is fine for small sites. If you run a domain with multiple
# machines, you should (1) change this to $mydomain and (2) set up
# a domain-wide alias database that aliases each user to
# user@that.users.mailhost.
#
# For the sake of consistency between sender and recipient addresses,
# myorigin also specifies the default domain name that is appended
# to recipient addresses that have no @domain part.
#
#myorigin = $myhostname
#myorigin = $mydomain
myorigin = $mydomain

# RECEIVING MAIL

# The inet_interfaces parameter specifies the network interface
# addresses that this mail system receives mail on. By default,
# the software claims all active interfaces on the machine. The
# parameter also controls delivery of mail to user@[ip.address].
#
# See also the proxy_interfaces parameter, for network addresses that
# are forwarded to us via a proxy or network address translator.
#
# Note: you need to stop/start Postfix when this parameter changes.
#
#inet_interfaces = all
#inet_interfaces = $myhostname
#inet_interfaces = $myhostname, localhost

# The proxy_interfaces parameter specifies the network interface
# addresses that this mail system receives mail on by way of a
# proxy or network address translation unit. This setting extends
# the address list specified with the inet_interfaces parameter.
#
# You must specify your proxy/NAT addresses when your system is a
# backup MX host for other domains, otherwise mail delivery loops
# will happen when the primary MX host is down.
#
#proxy_interfaces =
#proxy_interfaces = 1.2.3.4

# The mydestination parameter specifies the list of domains that this
# machine considers itself the final destination for.
#
# These domains are routed to the delivery agent specified with the
# local_transport parameter setting. By default, that is the UNIX
# compatible delivery agent that lookups all recipients in /etc/passwd
# and /etc/aliases or their equivalent.
#
# The default is $myhostname + localhost.$mydomain. On a mail domain
# gateway, you should also include $mydomain.
#
# Do not specify the names of virtual domains - those domains are
# specified elsewhere (see sample-virtual.cf).
#
# Do not specify the names of domains that this machine is backup MX
# host for. Specify those names via the relay_domains settings for
# the SMTP server, or use permit_mx_backup if you are lazy (see
# sample-smtpd.cf).
#
# The local machine is always the final destination for mail addressed
# to user@[the.net.work.address] of an interface that the mail system
# receives mail on (see the inet_interfaces parameter).
#
# Specify a list of host or domain names, /file/name or type:table
# patterns, separated by commas and/or whitespace. A /file/name
# pattern is replaced by its contents; a type:table is matched when
# a name matches a lookup key (the right-hand side is ignored).
# Continue long lines by starting the next line with whitespace.
#
# See also below, section "REJECTING MAIL FOR UNKNOWN LOCAL USERS".
#
#mydestination = $myhostname, localhost.$mydomain
#mydestination = $myhostname, localhost.$mydomain $mydomain
#mydestination = $myhostname, localhost.$mydomain, $mydomain,
# mail.$mydomain, www.$mydomain, ftp.$mydomain
mydestination = $mydomain, $transport_maps

# REJECTING MAIL FOR UNKNOWN LOCAL USERS
#
# The local_recipient_maps parameter specifies optional lookup tables
# with all names or addresses of users that are local with respect
# to $mydestination and $inet_interfaces.
#
# If this parameter is defined, then the SMTP server will reject
# mail for unknown local users. This parameter is defined by default.
#
# To turn off local recipient checking in the SMTP server, specify
# local_recipient_maps = (i.e. empty).
#
# The default setting assumes that you use the default Postfix local
# delivery agent for local delivery. You need to update the
# local_recipient_maps setting if:
#
# - You define $mydestination domain recipients in files other than
# /etc/passwd, /etc/aliases, or the $virtual_alias_maps files.
# For example, you define $mydestination domain recipients in
# the $virtual_mailbox_maps files.
#
# - You redefine the local delivery agent in master.cf.
#
# - You redefine the "local_transport" setting in main.cf.
#
# - You use the "luser_relay", "mailbox_transport", or "fallback_transport"
# feature of the Postfix local delivery agent (see sample-local.cf).
#
# Details are described in the LOCAL_RECIPIENT_README file.
#
# Beware: if the Postfix SMTP server runs chrooted, you probably have
# to access the passwd file via the proxymap service, in order to
# overcome chroot restrictions. The alternative, having a copy of
# the system passwd file in the chroot jail is just not practical.
#
# The right-hand side of the lookup tables is conveniently ignored.
# In the left-hand side, specify a bare username, an @domain.tld
# wild-card, or specify a user@domain.tld address.
#
#local_recipient_maps = unix:passwd.byname $alias_maps
#local_recipient_maps = proxy:unix:passwd.byname $alias_maps
#local_recipient_maps =

#----------- MYSQL ------------
virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cf
virtual_mailbox_base = /postfix
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
virtual_uid_maps = static:108
virtual_gid_maps = static:108
transport_maps = mysql:/etc/postfix/mysql_transport_maps.cf
#--------------------------------

#---------- QUOTA ------------
virtual_mailbox_limit_inbox = no
virtual_mailbox_limit_maps =
mysql:/etc/postfix/mysql_virtual_mailbox_limit_maps.cf
virtual_mailbox_limit_override = yes
virtual_maildir_extended = yes
virtual_create_maildirsize = yes
virtual_mailbox_limit = 100000000
virtual_maildir_limit_message = Desculpe, o usuario maildir ultrapassou a cota
de disco, por favor tente mais tarde.
virtual_overquota_bounce = yes
fallback_transport = /usr/bin/maildrop
#--------------------------------

default_transport = smtp

# The unknown_local_recipient_reject_code specifies the SMTP server
# response code when a recipient domain matches $mydestination or
# $inet_interfaces, while $local_recipient_maps is non-empty and the
# recipient address or address local-part is not found.
#
# The default setting is 550 (reject mail) but it is safer to start
# with 450 (try again later) until you are certain that your
# local_recipient_maps settings are OK.
#
#unknown_local_recipient_reject_code = 550
unknown_local_recipient_reject_code = 450

# TRUST AND RELAY CONTROL

# The mynetworks parameter specifies the list of "trusted" SMTP
# clients that have more privileges than "strangers".
#
# In particular, "trusted" SMTP clients are allowed to relay mail
# through Postfix. See the smtpd_recipient_restrictions parameter
# in file sample-smtpd.cf.
#
# You can specify the list of "trusted" network addresses by hand
# or you can let Postfix do it for you (which is the default).
#
# By default (mynetworks_style = subnet), Postfix "trusts" SMTP
# clients in the same IP subnetworks as the local machine.
# On Linux, this does works correctly only with interfaces specified
# with the "ifconfig" command.
#
# Specify "mynetworks_style = class" when Postfix should "trust" SMTP
# clients in the same IP class A/B/C networks as the local machine.
# Don't do this with a dialup site - it would cause Postfix to "trust"
# your entire provider's network. Instead, specify an explicit
# mynetworks list by hand, as described below.
#
# Specify "mynetworks_style = host" when Postfix should "trust"
# only the local machine.
#
#mynetworks_style = class
#mynetworks_style = subnet
#mynetworks_style = host

# Alternatively, you can specify the mynetworks list by hand, in
# which case Postfix ignores the mynetworks_style setting.
#
# Specify an explicit list of network/netmask patterns, where the
# mask specifies the number of bits in the network part of a host
# address.
#
# You can also specify the absolute pathname of a pattern file instead
# of listing the patterns here. Specify type:table for table-based lookups
# (the value on the table right-hand side is not used).
#
#mynetworks = 168.100.189.0/28, 127.0.0.0/8
#mynetworks = $config_directory/mynetworks
#mynetworks = hash:/etc/postfix/network_table
mynetworks = 192.168.0.0/24, 127.0.0.0/8

# The relay_domains parameter restricts what destinations this system will
# relay mail to. See the smtpd_recipient_restrictions restriction in the
# file sample-smtpd.cf for detailed information.
#
# By default, Postfix relays mail
# - from "trusted" clients (IP address matches $mynetworks) to any destination,
# - from "untrusted" clients to destinations that match $relay_domains or
# subdomains thereof, except addresses with sender-specified routing.
# The default relay_domains value is $mydestination.
#
# In addition to the above, the Postfix SMTP server by default accepts mail
# that Postfix is final destination for:
# - destinations that match $inet_interfaces,
# - destinations that match $mydestination
# - destinations that match $virtual_alias_domains,
# - destinations that match $virtual_mailbox_domains.
# These destinations do not need to be listed in $relay_domains.
#
# Specify a list of hosts or domains, /file/name patterns or type:name
# lookup tables, separated by commas and/or whitespace. Continue
# long lines by starting the next line with whitespace. A file name
# is replaced by its contents; a type:name table is matched when a
# (parent) domain appears as lookup key.
#
# NOTE: Postfix will not automatically forward mail for domains that
# list this system as their primary or backup MX host. See the
# permit_mx_backup restriction in the file sample-smtpd.cf.
#
#relay_domains = $mydestination

# INTERNET OR INTRANET

# The relayhost parameter specifies the default host to send mail to
# when no entry is matched in the optional transport(5) table. When
# no relayhost is given, mail is routed directly to the destination.
#
# On an intranet, specify the organizational domain name. If your
# internal DNS uses no MX records, specify the name of the intranet
# gateway host instead.
#
# In the case of SMTP, specify a domain, host, host:port, [host]:port,
# [address] or [address]:port; the form [host] turns off MX lookups.
#
# If you're connected via UUCP, see also the default_transport parameter.
#
#relayhost = $mydomain
#relayhost = gateway.my.domain
#relayhost = uucphost
#relayhost = [an.ip.add.ress]

# REJECTING UNKNOWN RELAY USERS
#
# The relay_recipient_maps parameter specifies optional lookup tables
# with all addresses in the domains that match $relay_domains.
#
# If this parameter is defined, then the SMTP server will reject
# mail for unknown relay users. This feature is off by default.
#
# The right-hand side of the lookup tables is conveniently ignored.
# In the left-hand side, specify an @domain.tld wild-card, or specify
# a user@domain.tld address.
#
#relay_recipient_maps = hash:/etc/postfix/relay_recipients

# INPUT RATE CONTROL
#
# The in_flow_delay configuration parameter implements mail input
# flow control. This feature is turned on by default, although it
# still needs further development (it's disabled on SCO UNIX due
# to an SCO bug).
#
# A Postfix process will pause for $in_flow_delay seconds before
# accepting a new message, when the message arrival rate exceeds the
# message delivery rate. With the default 50 SMTP server process
# limit, this limits the mail inflow to 50 messages a second more
# than the number of messages delivered per second.
#
# Specify 0 to disable the feature. Valid delays are 0..10.
#
#in_flow_delay = 1s

# ADDRESS REWRITING
#
# Insert text from sample-rewrite.cf if you need to do address
# masquerading.
#
# Insert text from sample-canonical.cf if you need to do address
# rewriting, or if you need username->Firstname.Lastname mapping.

# ADDRESS REDIRECTION (VIRTUAL DOMAIN)
#
# Insert text from sample-virtual.cf if you need virtual domain support.

# "USER HAS MOVED" BOUNCE MESSAGES
#
# Insert text from sample-relocated.cf if you need "user has moved"
# style bounce messages. Alternatively, you can bounce recipients
# with an SMTP server access table. See sample-smtpd.cf.

# TRANSPORT MAP
#
# Insert text from sample-transport.cf if you need explicit routing.

# ALIAS DATABASE
#
# The alias_maps parameter specifies the list of alias databases used
# by the local delivery agent. The default list is system dependent.
#
# On systems with NIS, the default is to search the local alias
# database, then the NIS alias database. See aliases(5) for syntax
# details.
#
# If you change the alias database, run "postalias /etc/aliases" (or
# wherever your system stores the mail alias file), or simply run
# "newaliases" to build the necessary DBM or DB file.
#
# It will take a minute or so before changes become visible. Use
# "postfix reload" to eliminate the delay.
#
#alias_maps = dbm:/etc/aliases
alias_maps = hash:/etc/postfix/aliases
#alias_maps = hash:/etc/aliases, nis:mail.aliases
#alias_maps = netinfo:/aliases

# The alias_database parameter specifies the alias database(s) that
# are built with "newaliases" or "sendmail -bi". This is a separate
# configuration parameter, because alias_maps (see above) may specify
# tables that are not necessarily all under control by Postfix.
#
#alias_database = dbm:/etc/aliases
alias_database = hash:/etc/postfix/aliases
#alias_database = hash:/etc/aliases
#alias_database = hash:/etc/aliases, hash:/opt/majordomo/aliases

# ADDRESS EXTENSIONS (e.g., user+foo)
#
# The recipient_delimiter parameter specifies the separator between
# user names and address extensions (user+foo). See canonical(5),
# local(8), relocated(5) and virtual(5) for the effects this has on
# aliases, canonical, virtual, relocated and .forward file lookups.
# Basically, the software tries user+foo and .forward+foo before
# trying user and .forward.
#
#recipient_delimiter = +

# DELIVERY TO MAILBOX
#
# The home_mailbox parameter specifies the optional pathname of a
# mailbox file relative to a user's home directory. The default
# mailbox file is /var/spool/mail/user or /var/mail/user. Specify
# "Maildir/" for qmail-style delivery (the / is required).
#
#home_mailbox = Mailbox
#home_mailbox = Maildir/
home_mailbox = Maildir/

# The mail_spool_directory parameter specifies the directory where
# UNIX-style mailboxes are kept. The default setting depends on the
# system type.
#
#mail_spool_directory = /var/mail
#mail_spool_directory = /var/spool/mail

# The mailbox_command parameter specifies the optional external
# command to use instead of mailbox delivery. The command is run as
# the recipient with proper HOME, SHELL and LOGNAME environment settings.
# Exception: delivery for root is done as $default_user.
#
# Other environment variables of interest: USER (recipient username),
# EXTENSION (address extension), DOMAIN (domain part of address),
# and LOCAL (the address localpart).
#
# Unlike other Postfix configuration parameters, the mailbox_command
# parameter is not subjected to $parameter substitutions. This is to
# make it easier to specify shell syntax (see example below).
#
# Avoid shell meta characters because they will force Postfix to run
# an expensive shell process. Procmail alone is expensive enough.
#
# IF YOU USE THIS TO DELIVER MAIL SYSTEM-WIDE, YOU MUST SET UP AN
# ALIAS THAT FORWARDS MAIL FOR ROOT TO A REAL USER.
#
mailbox_command = /usr/bin/procmail
#mailbox_command = /some/where/procmail -a "$EXTENSION"

# The mailbox_transport specifies the optional transport in master.cf
# to use after processing aliases and .forward files. This parameter
# has precedence over the mailbox_command, fallback_transport and
# luser_relay parameters.
#
# Specify a string of the form transport:nexthop, where transport is
# the name of a mail delivery transport defined in master.cf. The
# :nexthop part is optional. For more details see the sample transport
# configuration file.
#
# NOTE: if you use this feature for accounts not in the UNIX password
# file, then you must update the "local_recipient_maps" setting in
# the main.cf file, otherwise the SMTP server will reject mail for
# non-UNIX accounts with "User unknown in local recipient table".
#
#mailbox_transport = lmtp:unix:/file/name
#mailbox_transport = cyrus

# The fallback_transport specifies the optional transport in master.cf
# to use for recipients that are not found in the UNIX passwd database.
# This parameter has precedence over the luser_relay parameter.
#
# Specify a string of the form transport:nexthop, where transport is
# the name of a mail delivery transport defined in master.cf. The
# :nexthop part is optional. For more details see the sample transport
# configuration file.
#
# NOTE: if you use this feature for accounts not in the UNIX password
# file, then you must update the "local_recipient_maps" setting in
# the main.cf file, otherwise the SMTP server will reject mail for
# non-UNIX accounts with "User unknown in local recipient table".
#
#fallback_transport = lmtp:unix:/file/name
#fallback_transport = cyrus
#fallback_transport =
# The luser_relay parameter specifies an optional destination address
# for unknown recipients. By default, mail for unknown@$mydestination
# and unknown@[$inet_interfaces] is returned as undeliverable.
#
# The following expansions are done on luser_relay: $user (recipient
# username), $shell (recipient shell), $home (recipient home directory),
# $recipient (full recipient address), $extension (recipient address
# extension), $domain (recipient domain), $local (entire recipient
# localpart), $recipient_delimiter. Specify ${name?value} or
# ${name:value} to expand value only when $name does (does not) exist.
#
# luser_relay works only for the default Postfix local delivery agent.
#
# NOTE: if you use this feature for accounts not in the UNIX password
# file, then you must specify "local_recipient_maps =" (i.e. empty) in
# the main.cf file, otherwise the SMTP server will reject mail for
# non-UNIX accounts with "User unknown in local recipient table".
#
#luser_relay = $user@other.host
#luser_relay = $local@other.host
#luser_relay = admin+$local

# JUNK MAIL CONTROLS
#
# The controls listed here are only a very small subset. See the file
# sample-smtpd.cf for an elaborate list of anti-UCE controls.

# The header_checks parameter specifies an optional table with patterns
# that each logical message header is matched against, including
# headers that span multiple physical lines.
#
# By default, these patterns also apply to MIME headers and to the
# headers of attached messages. With older Postfix versions, MIME and
# attached message headers were treated as body text.
#
# For details, see the sample-filter.cf file.
#
#header_checks = regexp:/etc/postfix/header_checks

# FAST ETRN SERVICE
#
# Postfix maintains per-destination logfiles with information about
# deferred mail, so that mail can be flushed quickly with the SMTP
# "ETRN domain.tld" command, or by executing "sendmail -qRdomain.tld".
#
# By default, Postfix maintains deferred mail logfile information
# only for destinations that Postfix is willing to relay to (as
# specified in the relay_domains parameter). For other destinations,
# Postfix attempts to deliver ALL queued mail after receiving the
# SMTP "ETRN domain.tld" command, or after execution of "sendmail
# -qRdomain.tld". This can be slow when a lot of mail is queued.
#
# The fast_flush_domains parameter controls what destinations are
# eligible for this "fast ETRN/sendmail -qR" service.
#
#fast_flush_domains = $relay_domains
#fast_flush_domains =

# SHOW SOFTWARE VERSION OR NOT
#
# The smtpd_banner parameter specifies the text that follows the 220
# code in the SMTP server's greeting banner. Some people like to see
# the mail version advertised. By default, Postfix shows no version.
#
# You MUST specify $myhostname at the start of the text. That is an
# RFC requirement. Postfix itself does not care.
#
#smtpd_banner = $myhostname ESMTP $mail_name
#smtpd_banner = $myhostname ESMTP $mail_name ($mail_version)
smtpd_banner = $myhostname ESMTP $mydomain ($mail_version)

# PARALLEL DELIVERY TO THE SAME DESTINATION
#
# How many parallel deliveries to the same user or domain? With local
# delivery, it does not make sense to do massively parallel delivery
# to the same user, because mailbox updates must happen sequentially,
# and expensive pipelines in .forward files can cause disasters when
# too many are run at the same time. With SMTP deliveries, 10
# simultaneous connections to the same domain could be sufficient to
# raise eyebrows.
#
# Each message delivery transport has its XXX_destination_concurrency_limit
# parameter. The default is $default_destination_concurrency_limit for
# most delivery transports. For the local delivery agent the default is 2.

#local_destination_concurrency_limit = 2
#default_destination_concurrency_limit = 10

# DEBUGGING CONTROL
#
# The debug_peer_level parameter specifies the increment in verbose
# logging level when an SMTP client or server host name or address
# matches a pattern in the debug_peer_list parameter.
#
debug_peer_level = 2

# The debug_peer_list parameter specifies an optional list of domain
# or network patterns, /file/name patterns or type:name tables. When
# an SMTP client or server host name or address matches a pattern,
# increase the verbose logging level by the amount specified in the
# debug_peer_level parameter.
#
#debug_peer_list = 127.0.0.1
#debug_peer_list = some.domain

# The debugger_command specifies the external command that is executed
# when a Postfix daemon program is run with the -D option.
#
# Use "command .. & sleep 5" so that the debugger can attach before
# the process marches on. If you use an X-based debugger, be sure to
# set up your XAUTHORITY environment variable before starting Postfix.
#
debugger_command =
PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
xxgdb $daemon_directory/$process_name $process_id & sleep 5

# If you don't have X installed on the Postfix machine, try:
# debugger_command =
# PATH=/bin:/usr/bin:/usr/local/bin; export PATH; (echo cont;
# echo where) | gdb $daemon_directory/$process_name $process_id 2>&1
# >$config_directory/$process_name.$process_id.log & sleep 5

# INSTALL-TIME CONFIGURATION INFORMATION
#
# The following parameters are used when installing a new Postfix version.
#
# sendmail_path: The full pathname of the Postfix sendmail command.
# This is the Sendmail-compatible mail posting interface.
#
sendmail_path = /usr/sbin/sendmail

# newaliases_path: The full pathname of the Postfix newaliases command.
# This is the Sendmail-compatible command to build alias databases.
#
newaliases_path = /usr/bin/newaliases

# mailq_path: The full pathname of the Postfix mailq command. This
# is the Sendmail-compatible mail queue listing command.
#
mailq_path = /usr/bin/mailq

# setgid_group: The group for mail submission and queue management
# commands. This must be a group name with a numerical group ID that
# is not shared with other accounts, not even with the Postfix account.
#
setgid_group = postdrop

# manpage_directory: The location of the Postfix on-line manual pages.
#
manpage_directory = /usr/share/man

# sample_directory: The location of the Postfix sample configuration files.
#
sample_directory = /etc/postfix/sample

# readme_directory: The location of the Postfix README files.
#
readme_directory = no
#--------------- SASL -------------------
#smtpd_sasl_auth_enable = yes
#smtpd_sasl_security_options = noanonymous
#broken_sasl_auth_clients = yes
#smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks,
check_relay_domains
#------------------------------------------
#======================= FIM MAIN.CF ============


OBS:
- Essa é a configuração básica deste arquivo, fique a vontade para incluir novas
implementaçoes.
- Note que as linhas referentes ao SASL estão comentadas, elas só seram úteis
durante a sua configuração.
- O parametro "maildrop_destination_recipient_limit" faz com que o MAILDROP
entregue os email para mais de um destinatário, caso contrario, apenas um irá
receber a mensagem.

Verificar estas opcoes pois elas se referem ao volume do email a ser enviado e
recebido


Configuração finais
---------------------

[root@localhost postfix]# rm -rf /var/spool/postfix/etc
[root@localhost postfix]# rm /usr/lib/sendmail
[root@localhost postfix]# ln -s /usr/sbin/sendmail /usr/lib/sendmail

Agora é hora de testar se o Postfix esta se comunicando com o MySQL.

[root@localhost postfix]# cds
[root@localhost init.d]# ./postfix start

Insira no final do arquivo /etc/rc.d/rc.local a seguinte linha para poder
iniciar o servico do postfix se caso tiver que reiniciar a maquina.

/etc/init.d/postfix start

Precisamos criar um domínio e um usuário para teste. Vamos fazer, primeiramente
na "mão", fazendo passo a passo para você visualizar todo o procedimento de
criação de um usuário virtual.
Logue-se como ROOT no MySQL e faça:

[root@localhost init.d]# mysql -D postfix -p
mysql>

Criando o Dominio VIRTUAL e LOCAL
-----------------------------------

mysql> INSERT INTO domain(
domain,
description,
transport,
active)
VALUES (
'dominio1.com.br' ,
'Dominio de Teste' ,
'maildrop' ,
'1');

Query OK, 1 row affected (0.01 sec)


mysql> INSERT INTO domain(
domain,
description,
transport,
active)
VALUES (
'local.com.br' ,
'Dominio LOCAL da Máquina' ,
'local' ,
'1');

Query OK, 1 row affected (0.00 sec)

mysql> SELECT domain,description,transport,active FROM domain;
+-----------------+--------------------------+-----------+--------+
| domain | description | transport | active |
+-----------------+--------------------------+-----------+--------+
| dominio1.com.br | Dominio de Teste | maildrop | 1 |
| local.com.br | Dominio LOCAL da Máquina | local | 1 |
+-----------------+--------------------------+-----------+--------+


Criando o Usuário
-------------------


ATENÇÃO: Não esqueça de escolher uma senha em "encrypt('xxxxx')"

mysql> INSERT INTO mailbox(
username,
password,
name,
home,
maildir,
quota,
domain)
VALUES (
'alex@dominio1.com.br',
encrypt('xxxxx') ,
'Alexandro Batista',
'/postfix/',
'dominio1.com.br/alex/Maildir/',
'102400000S',
'dominio1.com.br');

Query OK, 1 row affected (0.05 sec)


mysql> SELECT username,name,home,maildir,quota,domain FROM mailbox;
+--------------------+---------+---------+-----------------------------+--------
--+---------------+
| username | name | home | maildir | quota
| domain |
+--------------------+---------+---------+-----------------------------+--------
--+---------------+
|alex@dominio1.com.br|Alexandro|/postfix/|dominio1.com.br/alex/Maildir/|10240000
0S|dominio1.com.br|
+--------------------+---------+---------+-----------------------------+--------
--+---------------+


Criando o seu ALIAS
-------------------

mysql> INSERT INTO alias (
address,
goto,
domain,
create_date,
change_date)
VALUES (
'alex@dominio1.com.br',
'alex@dominio1.com.br',
'dominio1.com.br',
NOW(),
NOW());

mysql> SELECT * FROM alias WHERE address='alex@dominio1.com.br';
mysql> exit
Bye


Criando o HOME do usuário
--------------------------

[root@localhost init.d]# mkdir -p /postfix/dominio1.com.br/alex
[root@localhost init.d]# maildirmake /postfix/dominio1.com.br/alex/Maildir
[root@localhost init.d]# chown maildrop:www /postfix/ -R
[root@localhost init.d]# chmod 770 /postfix/ -R


DICA
Criar um arquivo de execucao no diretorio de sua escolha (/source) para criacao
dos diretorios automaticamente e permissoes de pastas, pois senao tera que
executar os comandos acimas cada vez que criar um novo usuario de email.

sugestao de script bash
#========= Inicio novousuario ===============
#
#!/bin/sh
usario="usuario"
dominio="dominio.com.br"
#
mkdir -p /postfix/$dominio/$usuario
maildirmake /postfix/$dominio/$usuario/Maildir
chown maildrop:www /postfix/ -R
chmod 770 /postfix/ -R
#
#========= Fim do arquivo ===================

De permissao de execucao ao arquivo:

[root@localhost init.d]# chmod 700 /source/novousuario

E execute com o seguinte comando ./novousuario. Lembrando altere os valores das
variaveis para aqueles que convem ao usario de email e seu dominio.


TESTE MAILDROP
---------


Teste se o MAILDROP consegue enviar o email para a caixa postal do usuários

[root@localhost init.d]# cat /etc/my.cnf | maildrop -d
alex@dominio1.com.br

***** LOG DO MYSQL ******

031105 15:19:27 62 Connect maildrop@localhost on
62 Init DB postfix
62 Query SELECT username, uid, gid, home, maildir,
quota FROM mailbox WHERE username = "alex@dominio1.com.br" ""
62 Quit

*************************


[root@localhost init.d]# ls /postfix/dominio1.com.br/alex/Maildir/new/
1068052088.M222683P4357V0000000000000302I00013C90_0.alex,S=621

Beleza, funcionou.


TESTE POSTFIX
---------------


Usuário LOCAL
---------------

[root@localhost init.d]# echo "Funcionou..." | mail -s "TESTE do POSTFIX"
alex@local.com.br

******************** LOG DO MYSQL *******************
031111 14:23:52 170 Query select goto from alias where address =
'alex@local.com.br'
170 Query select goto from alias where address =
'alex'
170 Query select goto from alias where address =
'@local.com.br'
******************************************************

******************** LOG DO POSTFIX *******************
Nov 11 14:24:39 marco postfix/pickup[21819]: F285215721: uid=0 from=
Nov 11 14:24:39 marco postfix/cleanup[21880]: F285215721:
message-id=<20031111162439.F285215721@postfix.dominio.com.br>
Nov 11 14:24:39 alex postfix/nqmgr[21820]: F285215721: from=,
size=327, nrcpt=1 (queue active)
Nov 11 14:24:40 alex postfix/local[21884]: F285215721: to=,
orig_to=, relay=local, delay=1, status=sent (maildir)
********************************************************

[root@localhost init.d]# ls /home/alex/Maildir/new/
1068567812.V302I15701.alex.local.com.br

Beleza, funcionou....


Usuário VIRTUAL
----------------

[root@localhost init.d]# echo "Funcionou..." | mail -s "TESTE do POSTFIX"
alex@dominio1.com.br

******************** LOG DO MYSQL *******************
031107 14:28:00 23 Connect postfix@localhost on postfix
23 Query select goto from alias where address =
'alex@dominio1.com.br'
23 Query select goto from alias where address =
'@dominio1.com.br'
24 Connect maildrop@localhost on
24 Init DB postfix
24 Query SELECT username, uid, gid, home, maildir,
quota FROM mailbox WHERE username = "alex@dominio1.com.br" ""
24 Quit
****************************************************

******************** LOG DO POSTFIX *******************
Nov 7 14:28:00 teste postfix/pickup[20191]: 82EE0143AD: uid=0 from=
Nov 7 14:28:00 teste postfix/cleanup[20226]: 82EE0143AD:
message-id=<20031107162800.82EE0143AD@postfix.dominio.com.br>
Nov 7 14:28:00 teste postfix/nqmgr[20192]: 82EE0143AD:
from=, size=817, nrcpt=1 (queue active)
Nov 7 14:28:00 teste postfix/pipe[20228]: 82EE0143AD:
to=, relay=maildrop, delay=0, status=sent
(dominio1.com.br)
************************************************

[root@localhost init.d]# ls /postfix/dominio1.com.br/alex/Maildir/new/
1068222707.M754502P20250V0000000000000302I000135EA_0.teste,S=342

Opa, acho que foi:

[root@localhost init.d]# cat postfix/dominio1.com.br/alex/Maildir/new/
1068222707.M754502P20250V0000000000000302I000135EA_0.teste\,S\=342
-------------------------------------------------------------
Received: by postfix.dominio.com.br (Postfix, from userid 0)
id AE1ED143AD; Fri, 7 Nov 2003 14:31:47 -0200 (BRST)
To: alex@dominio1.com.br
Subject: TESTE do POSTFIX
Message-Id: <20031107163147.AE1ED143AD@postfix.dominio.com.br>
Date: Fri, 7 Nov 2003 14:31:47 -0200 (BRST)
From: root@local.com.br,.local.com.br (root)

Funcionou...
-------------------------------------------------------------

É, foi!!!!! :-)


FUMEGOUUUUUUU !!!!! :-)


Teste de Autenticação do IMAP
------------------------------

[root@localhost init.d]# telnet 0 143
Trying 0.0.0.0...
Connected to 0 (0.0.0.0).
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT
THREAD=REFERENCES SORT QUOTA IDLE STARTTLS] Courier-IMAP ready. Copyright
1998-2003
Double Precision, Inc. See COPYING for distribution information.

0 login alex@dominio1.com.br xxxxxx
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 1068222985] Ok
0 OK [READ-WRITE] Ok

0 logout
* BYE Courier-IMAP server shutting down
0 OK LOGOUT completed
Connection closed by foreign host.

Beleza, funcionou.!!!!


Teste de Autenticação do POP3
------------------------------

[root@localhost init.d]# telnet 0 110
Trying 0.0.0.0...
Connected to 0 (0.0.0.0).
Escape character is '^]'.
+OK Hello there.

user alex@dominio1.com.br
+OK Password required.

pass xxxxx
+OK logged in.

list
+OK POP3 clients that break here, they violate STD53.
1 351
.

quit
+OK Bye-bye.
Connection closed by foreign host.

Beleza, funcionou.!!!!

DICA:
Em caso de erro de autenticação, sempre dê uma olhada nos logs do MySQL e veja
se foi feito e como foi feito o SELECT do courier. Isso pode ser útil para
identificar erros no arquivo de configuração do courier.
Um outro problema pode ser no MySQL, ou o serviço não esta funcionando ou o
usuário não tem permissão de acesso ao banco de dados.


========================================
INSTALANDO O POSTFIXADMIN
========================================

http://high5.net/postfixadmin/

O PostfixAdmin é um ambiente de administração do Postfix+MySQL, feito totalmente
em PHP. Com ele, você pode:

- Criar domínio virtuais
- Criar/Excluir contas Virtuais
- Criar/Excluir Aliases
- Alteração de Senhas etc..

Você também pode adaptá-lo as suas necessidades, bastando apenas um conhecimento
da linguagem PHP.
Para esse ambiente, foi necessário fazer algumas alterações no código original
para adequá-lo ao Maildrop.
Essas foram algumas das minhas alterações:

- Tradução do Ambiente para Português BR
- Adaptação de 2 script para CRIAÇÃO e EXCLUSÃO de usuário. Isso foi necessário,
pois o MAILDROP nesse ambiente, não cria o MAILDIR/ do usuário caso ele não
exista. Para a EXCLUSÃO, o Postfixadmin não apaga o diretório dos usuários. Com
esses 2 scripts, você também pode realizar outras configurações, no meu caso por
exemplo, a configuração de um Webmail.
- Uso do SUDO para dar permissões de execução para esses dois scripts.
- Inclusão do campo ATIVO na página de administração com a possibilidade de
ativar/desativar um conta de usuário.
- Mudança na forma de apresentação do valor da COTA de disco
- Mudança na forma de apresentação da DATA de alteração da conta, para um
formato BR


Dependências
---------------

Apache
PHP
php-mysql
php-ini


ATENÇÃO:
Caso você não esteja utilizando o Mandrake, certamente a sua distribuição deve
possuir o Apache e o PHP nos CD's de instalação.
Não entrarei em detalhes sobre configuração do APACHE, pois o foco aqui é outro.
Usarei a configuração DEFAULT do servidor.


Instalação
--------------

Se você for utilizar a minha versão com essas alterações, baixe-o nesse link:

download postfixadmin-MODIFICADO

Após o download, descompacte no diretório ROOT do servidor WEB ou em algum
outro, lembrando apenas de criar um ALIAS na configuração do servidor.

Copie os scrips para um outro diretório e mude as permissoes.

[root@localhost init.d]# mv /srv/www/default/html/postfixadmin/*.sh /srv/www/
[root@localhost init.d]# chmod 700 /srv/www/*.sh

Edite o arquivo adduser.sh e altere a ultima linha onde consta apache para www.

Mude as permissões.

[root@localhost init.d]# chown www:www /srv/www/default/html/postfixadmin/ -R
[root@localhost init.d]# cd /srv/www/default/html/postfixadmin/
[root@localhost postfixadmin]#


Configuração do SUDO
----------------------

Como comentei antes, por causa do MAILDROP, nesse ambiente precisei criar 2
scripts "adduser.sh e userdel.sh". Esses scripts devem possuir permissão de ROOT
para execução. A forma que achei para resolver esse problema, foi o uso do SUDO.

* Se alguém tiver alguma sugestão melhor, por favor entre em contato.


Edite o arquivo /etc/sudoers e adicione as seguintes linhas:
#POSTFIXADMIN
apache ALL=NOPASSWD:/srv/www/adduser.sh
apache ALL=NOPASSWD:/srv/www/userdel.sh

Faca uma copia e edite o arquivo
/srv/www/default/html/postfixadmin/config.inc.php e configure as variáveis
conforme a sua configuração.

As principais são:
#========================= INICIO CONFIG.INC.PHP =======

/*
//
// If config.inc.php is called directly, redirect to login.php
//
if (ereg("config.inc.php", $_SERVER[PHP_SELF])) {
header("Location: login.php");
}

// Login information for the database
$db_host = "localhost";
$db_name = "postfix";
$db_user = "postfixadmin";
$db_pass = "xxxxx"; // senha do usuario postfixadmin

// Default aliases that need to be created for all domains
$default_aliases = array (
"abuse" => "abuse@example.com",
"hostmaster" => "hostmaster@example.com",
"postmaster" => "postmaster@example.com",
"webmaster" => "webmaster@example.com"
);

// Back to main website information
// If you don't want to use this option set this to "NO".
$show_organization_info = "NO";
$organization_name = "Visão Geral";
$organization_link = "http://172.16.128.45/postfixadmin/main.php";

// Admin email address
$admin_email = "alex@dominio1.com.br";

// If you wish to keep each domain in its own subdirectory beneath the
// $virtual_mailbox_base directory, set this to "YES".
$use_subdir = "YES";

// When you want to offer the "vacation" daemon to your users,
// set this to "YES".
// You need to install the vacation module first!
$use_vacation = "NO";
$vacation_text = "Resposta automática, caso você esteja fora do escritório.";
$vacation_file = "vacation.php";
$vacation_email = "vacation@local.com.br";

// If you want to view the aliases that are created for the mailboxes set
// this to "YES".
$alias_control = "YES";

// Specify the table where you have your quotas, leave empty if you don't
// enforce quotas. For example a 2MB mailbox quota:
// $quota_table = "quota";
// $default_quota = "2000000";
$quota_table = "quota";
$default_quota = "100000000S";

// Show Postfix Admin information
$show_postfix_admin_info = "NO";

// Title used for all pages except login.php
$title = "Mail Admin";

// Header used for login.php
$welcome_header = ":: Bem Vindo ao Mail Admin ::";

// Title used for login.php
$welcome_title = ":: Bem Vindo ao Mail Admin ::";


==========================================

Modificaões feitas por Marco A. S. Máximo

==========================================

//Comando SUDO
$sudo_path= "/usr/bin/sudo";

//PATH do script adduser.sh e userdel.sh
$adduser_path= "/srv/www/adduser.sh";
$userdel_path= "/srv/www/userdel.sh";

// Diretório base das caixas postais dos usuários
$home_base = "/postfix/";

#============= FIM CONFIG.INC.PHP ===================

Depois de configurado as variáveis, habilite o acesso a pagina de administração
de domínio do PostfixAdmin, no meu caso usarei o usuário "admin".

[root@localhost postfixadmin]# cd admin/
[root@localhost admin]# htpasswd .htpasswd admin

New password:
Re-type new password:
Updating password for user admin

Inicie o servidor apache
[root@localhost admin]# cds
[root@localhost init.d]# ./httpd start

Starting apache: [ OK ]

Execute no browser http://localhost/postfixadmin/admin

Ele ira lhe pedir o usuário o password que você cadastrou no arquivo .htpasswd.
No PostfixAdmin, você precisa cadastrar os administradores correspondentes para
cada domínio que você possui na máquina.

Agora execute no browser http://localhost/postfixadmin

Não irei entrar em detalhes sobre o funcionamento do PostfixAdmin, pois a sua
interface é muito intuitiva.


========================================
WEBMAIL - SQUIRRELMAIL
========================================

http://www.squirrelmail.org/

O Squirrelmail, é um completo Webmail que se integra completamente nesse ambiente com domínios virtuais. Ele é escrito em PHP, o que possibilita a sua total personalização.
Um outro recurso muito interessante, é a possibilidade de se aumentar as funcionalidades do Squirrelmail com a instalação de plugins.
Vou demonstrar uma instalação simples com suporte a MySQL e a instalação de um plugin para mudança de senha.

Dependências
-------------

APACHE
PHP
php-pear


Instalando
------------

No site existe versões em RPM, mas aconselho a utilizar as versão SOURCE devido
a sua facilidade de personalização.

Faça o download em:

download squirrelmail

Desconpacte o arquivo baixado no diretorio do servidor web

[root@localhost init.d]# cd /source/squirrelmail-1.4.2
[root@localhost init.d]# mv squirrelmail-1.4.2/ /srv/www/default/html/webmail/
[root@localhost init.d]# chown root:root /srv/www/default/html/webmail/ -R
[root@localhost init.d]# chmod 755 /srv/www/default/html/webmail/ -R
[root@localhost init.d]# cd /srv/www/default/html/webmail/
[root@localhost webmail]#


Configurando
--------------

A configuração do Squirrelmail, pode ser feita de duas formas:

- Por um script de configuração "configure"
- Editando diretamente o arquivo "webmail/config/config.php"

Irei mostrar a configuração do arquivo "config.php" , pois a utilização do
script de configuração é bastante fácil.

Como estamos utilizando o MySQL, nada mais cômodo como guardar as configuração
dos usuário e seus livros de endereços em tabelas SQL. O Squirrelmail permite
essa facilidade. sendo assim, verifique se foram criadas corretamente as
tabelas.

[root@localhost webmail]# mysql webmail -p

Teste se foi criado:
mysql> show tables;
+-------------------+
| Tables_in_webmail |
+-------------------+
| address |
| userprefs |
+-------------------+

mysql> quit

Agora vamos configurar o Squirrelmail.

Dentro do diretório webmail/config/, existe um arquivo chamado
"config_default.php" esse arquivo explica para que serve cada parâmetro de
configuração. Crie um arquivo chamado "config.php" com o conteúdo do arquivo
"config_default.php", ex:

[root@localhost webmail]# cd config
[root@localhost config]# cp config_default.php config.php

Uma outra forma de gerar esse arquivo, é usando o script de configuração:

[root@localhost webmail]# ./configure

Recomendo essa última forma, pois cria um arquivo config.php mais "limpo".

Essas são as principais linhas que devem ser alteradas no arquivo
"webmail/config/config.php" para a configuração do seu domínio com suporte a
MySQL e Courier-IMAP.

#============= INICIO CONFIG.PHP ==================
/*
* SquirrelMail Configuration File
* Created using the configure script, conf.pl

global $version;
$config_version = '1.4.0';
$config_use_color = 2;

$org_name = "EMPRESA";
$org_logo = SM_PATH . 'images/sm_logo.png';
$org_logo_width = '308';
$org_logo_height = '111';
$org_title = "EMPRESA $version";
$signout_page = '';
$frame_top = '_top';

$provider_uri = 'http://www.SUAEMPRESA.com.br/';

$provider_name = 'EMPRESA';

$motd = "";

$squirrelmail_default_language = 'pt_BR';

$domain = 'dominio.com.br';
$imapServerAddress = 'localhost';
$imapPort = 143;
$useSendmail = false;
$smtpServerAddress = 'localhost';
$smtpPort = 25;
$sendmail_path = '/usr/sbin/sendmail';
$pop_before_smtp = false;
$imap_server_type = 'courier';
$invert_time = false;
$optional_delimiter = 'detect';

$default_folder_prefix = '';
$trash_folder = 'INBOX.Trash';
$sent_folder = 'INBOX.Sent';
$draft_folder = 'INBOX.Drafts';
$default_move_to_trash = true;
$default_move_to_sent = true;
$default_save_as_draft = true;
$show_prefix_option = true;
$list_special_folders_first = true;
$use_special_folder_color = true;
$auto_expunge = true;
$default_sub_of_inbox = true;
$show_contain_subfolders_option = true;
$default_unseen_notify = 2;
$default_unseen_type = 1;
$auto_create_special = true;
$delete_folder = false;
$noselect_fix_enable = true;

$default_charset = 'iso-8859-1';
$data_dir = SM_PATH.'data/';
$attachment_dir = $data_dir;
$dir_hash_level = 0;
$default_left_size = '150';
$force_username_lowercase = true;
$default_use_priority = true;
$hide_sm_attributions = true;
$default_use_mdn = true;
$edit_identity = true;
$edit_name = true;
$allow_thread_sort = true;
$allow_server_sort = true;
$allow_charset_search = true;
$uid_support = true;

$theme_css = '';
$theme_default = 0;
$theme[0]['PATH'] = SM_PATH . 'themes/default_theme.php';
$theme[0]['NAME'] = 'Default';
$theme[1]['PATH'] = SM_PATH . 'themes/plain_blue_theme.php';
$theme[1]['NAME'] = 'Plain Blue';
$theme[2]['PATH'] = SM_PATH . 'themes/sandstorm_theme.php';
$theme[2]['NAME'] = 'Sand Storm';
$theme[3]['PATH'] = SM_PATH . 'themes/deepocean_theme.php';
$theme[3]['NAME'] = 'Deep Ocean';
$theme[4]['PATH'] = SM_PATH . 'themes/slashdot_theme.php';
$theme[4]['NAME'] = 'Slashdot';
$theme[5]['PATH'] = SM_PATH . 'themes/purple_theme.php';
$theme[5]['NAME'] = 'Purple';
$theme[6]['PATH'] = SM_PATH . 'themes/forest_theme.php';
$theme[6]['NAME'] = 'Forest';
$theme[7]['PATH'] = SM_PATH . 'themes/ice_theme.php';
$theme[7]['NAME'] = 'Ice';
$theme[8]['PATH'] = SM_PATH . 'themes/seaspray_theme.php';
$theme[8]['NAME'] = 'Sea Spray';
$theme[9]['PATH'] = SM_PATH . 'themes/bluesteel_theme.php';
$theme[9]['NAME'] = 'Blue Steel';
$theme[10]['PATH'] = SM_PATH . 'themes/dark_grey_theme.php';
$theme[10]['NAME'] = 'Dark Grey';
$theme[11]['PATH'] = SM_PATH . 'themes/high_contrast_theme.php';
$theme[11]['NAME'] = 'High Contrast';
$theme[12]['PATH'] = SM_PATH . 'themes/black_bean_burrito_theme.php';
$theme[12]['NAME'] = 'Black Bean Burrito';
$theme[13]['PATH'] = SM_PATH . 'themes/servery_theme.php';
$theme[13]['NAME'] = 'Servery';
$theme[14]['PATH'] = SM_PATH . 'themes/maize_theme.php';
$theme[14]['NAME'] = 'Maize';
$theme[15]['PATH'] = SM_PATH . 'themes/bluesnews_theme.php';
$theme[15]['NAME'] = 'BluesNews';
$theme[16]['PATH'] = SM_PATH . 'themes/deepocean2_theme.php';
$theme[16]['NAME'] = 'Deep Ocean 2';
$theme[17]['PATH'] = SM_PATH . 'themes/blue_grey_theme.php';
$theme[17]['NAME'] = 'Blue Grey';
$theme[18]['PATH'] = SM_PATH . 'themes/dompie_theme.php';
$theme[18]['NAME'] = 'Dompie';
$theme[19]['PATH'] = SM_PATH . 'themes/methodical_theme.php';
$theme[19]['NAME'] = 'Methodical';
$theme[20]['PATH'] = SM_PATH . 'themes/greenhouse_effect.php';
$theme[20]['NAME'] = 'Greenhouse Effect (Changes)';
$theme[21]['PATH'] = SM_PATH . 'themes/in_the_pink.php';
$theme[21]['NAME'] = 'In The Pink (Changes)';
$theme[22]['PATH'] = SM_PATH . 'themes/kind_of_blue.php';
$theme[22]['NAME'] = 'Kind of Blue (Changes)';
$theme[23]['PATH'] = SM_PATH . 'themes/monostochastic.php';
$theme[23]['NAME'] = 'Monostochastic (Changes)';
$theme[24]['PATH'] = SM_PATH . 'themes/shades_of_grey.php';
$theme[24]['NAME'] = 'Shades of Grey (Changes)';
$theme[25]['PATH'] = SM_PATH . 'themes/spice_of_life.php';
$theme[25]['NAME'] = 'Spice of Life (Changes)';
$theme[26]['PATH'] = SM_PATH . 'themes/spice_of_life_lite.php';
$theme[26]['NAME'] = 'Spice of Life - Lite (Changes)';
$theme[27]['PATH'] = SM_PATH . 'themes/spice_of_life_dark.php';
$theme[27]['NAME'] = 'Spice of Life - Dark (Changes)';
$theme[28]['PATH'] = SM_PATH . 'themes/christmas.php';
$theme[28]['NAME'] = 'Holiday - Christmas';
$theme[29]['PATH'] = SM_PATH . 'themes/darkness.php';
$theme[29]['NAME'] = 'Darkness (Changes)';
$theme[30]['PATH'] = SM_PATH . 'themes/random.php';
$theme[30]['NAME'] = 'Random (Changes every login)';
$theme[31]['PATH'] = SM_PATH . 'themes/midnight.php';
$theme[31]['NAME'] = 'Midnight';
$theme[32]['PATH'] = SM_PATH . 'themes/alien_glow.php';
$theme[32]['NAME'] = 'Alien Glow';
$theme[33]['PATH'] = SM_PATH . 'themes/dark_green.php';
$theme[33]['NAME'] = 'Dark Green';
$theme[34]['PATH'] = SM_PATH . 'themes/penguin.php';
$theme[34]['NAME'] = 'Penguin';
$theme[35]['PATH'] = SM_PATH . 'themes/minimal_bw.php';
$theme[35]['NAME'] = 'Minimal BW';

$default_use_javascript_addr_book = true;
$addrbook_dsn = 'mysql://squirreluser:xxxxx@localhost/webmail'; // senha do
usuario squirreluser
$addrbook_table = 'address';

$prefs_dsn = 'mysql://squirreluser:xxxxx@localhost/webmail'; // senha do usuario
squirreluser
$prefs_table = 'userprefs';
$prefs_user_field = 'user';
$prefs_key_field = 'prefkey';
$prefs_val_field = 'prefval';
$no_list_for_subscribe = false;
$smtp_auth_mech = 'none';
$imap_auth_mech = 'login';
$use_imap_tls = false;
$use_smtp_tls = false;
$session_name = 'SQMSESSID';

@include SM_PATH . 'config/config_local.php';


* Make sure there are no characters after the PHP closing
* tag below (including newline characters and whitespace).
* Otherwise, that character will cause the headers to be
* sent and regular output to begin, which will majorly screw
* things up when we try to send more headers later.
*/
#============== FIM CONFIG.PHP ================

DICA:
- Quase todos os plugins do Squirrelmail vem desabilitados por default.
- Usando o script de configuração, escolha a opção 8 e habilite-os digitando os
seu número correspondente.

Agora acesse o webmail pelo link:

http://ip_do_servidor/webmail/

Para logar no webmail você precisa fornecer seu nome completo de usuário, ou
seja, usuario@dominio. Ex:

user: alex@dominio1.com.br
pass: xxxxxx


Instalando Plugins
--------------------


Como eu havia falado, uma outra forma de você aumentar as funcionalidades do
Squirrelmail é instalando novos plugins. No site, atualmente estão listados 174
plugins. Vamos instalar um plugin útil para a mudança de senha dos usuários
VIRTUAIS, chamado change_mysqlpass, para isso você precisa também de outro
plugin chamado de compatibility.

Baixe-os em:
http://www.squirrelmail.org/countdl.php?fileurl=http%3A%2F%2Fwww.squirrelmail.org%2Fplugins%2Fcompatibility-1.2.tar.gz
http://www.squirrelmail.org/countdl.php?fileurl=http%3A%2F%2Fwww.squirrelmail.org%2Fplugins%2Fchange_mysqlpass-3.2-1.2.8.tar.gz

Instalando
------------

Descompacte os arquivos baixados no diretorio
/srv/www/default/html/webmail/plugins/
[root@localhost webmail]# cd plugins/change_mysqlpass/
[root@localhost change_mysqlpass]# cp config.php.sample config.php
[root@localhost change_mysqlpass]# chown root:www config.php
[root@localhost change_mysqlpass]# chmod 640 config.php

Edite o arquivo "config.php" e configure as seguintes variáveis:

#============ INICIO CONFIG.PHP =================
// Global Variables, don't touch these unless you want to break the
plugin
//
global $mysql_server, $mysql_database, $mysql_table,
$mysql_userid_field,
$mysql_password_field, $mysql_manager_id, $mysql_manager_pw,
$mysql_saslcrypt, $mysql_unixcrypt, $mysql_MD5crypt,
$use_ssl_for_password_change, $mysql_password_force,
$mysql_password_change_field,
$mysql_password_change_field_delimiter,
$mysql_password_change_yes_value,
$mysql_password_change_no_value,
$split_username_query, $split_username_expression,
$split_username_domain_field, $debug, $update_clear_passwd_field;

// The MySQL Server that SASL uses
$mysql_server = 'localhost';

// Database and table that SASL uses for auth
$mysql_database = 'postfix';
$mysql_table = 'mailbox';

// The names of the user ID and password columns
$mysql_userid_field = 'username';
$mysql_password_field ='password';

// The user to log into MySQL with (must have rights)
$mysql_manager_id = 'postfixadmin';
$mysql_manager_pw = 'xxxxx'; //Senha do usuario postfixadmin

//---------------------------------------------------------
// Password encryption (or lack thereof)
//---------------------------------------------------------

// Set only one of the options below to 1.

// Set to 1 if the password column is encrypted
// using the MySQL password() function.
$mysql_saslcrypt = 0;

// Set to 1 if the password column is encrypted
// using the UNIX crypt() function.
$mysql_unixcrypt = 1;

// Set to 1 if the password column is to use MD5 encryption
$mysql_MD5crypt = 0;

// Set both to 0 if the password is stored in the
// column in plaintext.

//---------------------------------------------------------
// SSL encryption during password change
//---------------------------------------------------------
// Set to 1 to enforce SSL connections when
// changing passwords. NOTE - This should be
// turned OFF if you serve your entire webmail
// in https!
$use_ssl_for_password_change = 1;

//---------------------------------------------------------
// Force password change mode
//---------------------------------------------------------
// Enable functionality to force users to change
// their passwords
$mysql_password_force = 1;

// Force password change field
$mysql_password_change_field = 'passwd_expire';

// Set this as a double quote if the above-defined
// field is a character data field, otherwise,
// set it to an empty string
$mysql_password_change_field_delimiter = '"';
//$mysql_password_change_field_delimiter = '';

// Force password YES and NO values
// the value the above-defined field will be set to
// to indicate that the user must change passwords
// upon next login (and not)
//
$mysql_password_change_yes_value = 'Y';
$mysql_password_change_no_value = 'N';
//$mysql_password_change_yes_value = 1;
//$mysql_password_change_no_value = 0;

//---------------------------------------------------------
// Multiple database field setup
//---------------------------------------------------------
// The following settings ONLY apply if your IMAP
// login is comprised of a join between two separate
// database columns
//
// Set this to 1 to turn such functionality on
//
$split_username_query = 0;

// This is typically the @ sign, although it can be any
// regular expression which should be used to split the
// full user name into two separate pieces (for example,
// using @, "jose@myowndomain.com" becomes "jose" and
// "myowndomain.com")
//
$split_username_expression = '@';

// This is the name of the second database column to query
//
$split_username_domain_field = 'domain';

//---------------------------------------------------------
// Multiple password fields
//---------------------------------------------------------
// The following settings ONLY apply if you keep
// a cleartext copy of users' passwords along with
// an encrypted one (CAREFUL!). Set this variable
// to the name of the cleartext password field
// and it will be updated IN ADDITION to the encrypted
// field indicated above. Others should leave this
// setting as an empty string.
//
$update_clear_passwd_field = '';

//---------------------------------------------------------
// Debug mode
//---------------------------------------------------------
// Debug
$debug = 0;
#=========== FIM CONFIG.PHP ======================

[root@localhost change_mysqlpass]# cd /srv/www/default/html/webmail/
[root@localhost webmail]# ./configure

Escolha a opção 8 e habilite os dois plugins ( compatibility, change_mysqlpass).
E faça um reload no seu browser.
Todo o usuário criado ao se logar pela primeira vez no webmail, recebera um
pedido de mudança de senha. Isso é causado pelo valor "Y" no campo
"passwd_expire" da tabela "mailbox".

DICA:
Caso ocorra algum erro, pode ser devido a variável "$use_ssl_for_password_change
= 1;" . Caso o seu servidor não esteja com o suporte SSL ativo. Altere para 0
para resolver o problema.


Plugins Recomendados
---------------------

msg_flags : Icones para as mensagens
smallcal : Pequeno calendário na barra lateral
newuser_wiz : Ajuda o usuário configurar alguns dados iniciais
vlogin : Completa o login do usuário com o seu dominio "@dominio.com.br"


========================================
ANTI-VÍRUS ClamAV
========================================

Autor: Gleydson Soares (gsoares) - Deives Michellis "thefallen"

http://www.unitednerds.org/thefallen/docs/index.php?area=Postfix&tuto=Clamav-gsoares

Aumento de Desempenho
Muitos admins sofreram ou ainda sofrem com o aumento de virus na Internet,
causando lentidao na entrega e recebimento em seus MTAs. Tudo isso por falta de
um filtro que trabalhasse diretamente com o postfix sem precisar passar pelo
amavis ou mailscanner (os famosos consumidores de memoria e cpu ;)).

Quem não já teve a experiencia de integrar o postfix com expressões body_checks
para rejeitar o email antes mesmo que ele passe pelo amavis ou mailscanner e se
surpreendeu com o alto desempenho. Porem a solução ideal é integrar um antivirus
diretamente com o MTA. Nesse tutorial usaremos o postfix junto com o clamav
(antivirus livre).

Software Utilizado

ClamAv - http://www.clamav.net/
http://aleron.dl.sourceforge.net/sourceforge/clamav/clamav-0.70.tar.gz
Clamav Filter - http://www.unitednerds.org/projects/mail/
http://www.unitednerds.org/projects/mail/clamav-filter.sh.bz2


Partindo pra instalacao ClamAV

Primeiramente, descompacte o tar.gz do ClamAV e crie os usuarios padrao.
[root@localhost source]# tar -xvzf clamav-0.70.tar.gz
[root@localhost source]# groupadd clamav
[root@localhost source]# adduser -g clamav -s/bin/false -c"ANTI-VIRUS
Clamav"

clamav

Para compilarmos, vamos usar algumas opcoes no ./configure:

[root@localhost source]# cd /clamav-0.70
[root@localhost clamav-0.70]# ./configure --prefix=/usr --sysconfdir=/etc &&
make && make install

Pronto, seu ClamAV está instalado, agora so falta configurar o seu
/etc/clamav.conf.

Apenas algumas linhas precisam ser alteradas. Entre elas, precisamos comentar a
linha "Example" e descomentar as linhas "ScanMail" e "User clamav". Voce pode
querer tambem alterar algumas variaveis do ClamAV, como lugar em que eh gerado o unix socket. Segue abaixo um exemplo de clamav.conf:

#/etc/clamav.conf
LogTime
# Voce pode ter o log no syslog ou em um arquivo de log, ou os 2.
LogSyslog
LogFile /var/log/clam/clamd.log
PidFile /var/run/clam/clamd.pid
LocalSocket /var/run/clam/clamd.sock
FixStaleSocket
MaxThreads 50
ThreadTimeout 600
MaxDirectoryRecursion 15
FollowFileSymlinks
SelfCheck 600
User clamav
ScanMail
ScanArchive
ArchiveMaxFileSize 10M
ArchiveMaxRecursion 5
ArchiveMaxFiles 1000

Nesse exemplo, foram usados os diretorios (inexistentes) /var/run/clam,
/var/log/clam. Crie ambos e de permissoes para o usuario "clamav" (caso queira
usar essa estrutura de diretorios):

[root@localhost clamav-0.70]# mkdir /var/run/clam /var/log/clam
[root@localhost clamav-0.70]# chown -R clamav:clamav /var/run/clam
/var/log/clam

Nao se esqueca de colocar o /usr/sbin/clamd para ser iniciado no boot(adicione
no final do arquivo /etc/rc.d/rc.local). Note que eh uma boa ideia inicia-lo
ANTES do Postfix (assim, quando o Postfix requisitar o antivirus, ele ja esta
la.)


Instalando o ClamAV Filter
-----------------------------------

Bem, aqui devemos dar nosso agradecimento ao thefallen em ter aberto nossos
olhos em relação a essa implementação e pelo desenvolvimento desse filtro.

Pegue o script em http://www.unitednerds.org/projects/mail/clamav-filter.sh.bz2

Descompacte o script no diretorio : /usr/lib/postfix (ou /usr/libexec/postfix),
e dê permissao de execução com o comando "chmod 0755 clamav-filter.sh".

Nao se esqueca de criar o diretorio de spool /var/spool/filter com o usuario
"clamav" como owner.

[root@localhost clamav-0.70]# cd /usr/lib/postfix
[root@localhost postfix]# bunzip2 clamav-filter.sh.bz2
[root@localhost postfix]# chmod 0755 clamav-filter.sh
[root@localhost postfix]# mkdir /var/spool/filter
[root@localhost postfix]# chown clamav:clamav /var/spool/filter

Dentro do arquivo master.cf altere a seguinte linha:

smtp inet n - n - - smtpd -o
content_filter=clamav:clamav

E insira as seguintes linhas:

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

OBS - se voce antes usava amavis, nao se esqueca de comentar as linhas
referentes a ele no master.cf e se atente em tirar a linha "content_filter =
smtp-amavis:[127.0.0.1]:10024" dentro do main.cf.


Integrando com o SpamAssassin
------------------------------------------------------

Eh bastante simples integrarmos o SpamAssassin ao nosso script do Clamav Filter.
Supondo que voce ja tenha o SpamAssassin instalado, e o "spamd" rodando, basta
editar o clamav-filter.sh e mudar a linha:

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

Para:

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

Agradecimentos a David da Guia Carvalho pela dica :)


Acertando alguns detalhes no Postfix
--------------------------------------------------------

Podemos acertar alguns detalhes no Postfix para evitar que o filtro de timeout
sob carga pesada. No master.cf, voce pode limitar a quantidade de processos do
filtro rodando ao mesmo tempo (para evitar que o workload da maquina suba
muito). No exemplo abaixo, limitamos a 15 instancias do filtro; aumente esse
limite com calma e veja ate onde seu servidor aguenta sem "abrir o bico" :)

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

Precisamos tambem ajustar a variavel "command_time_limit" no main.cf. Essa
variavel diz quanto tempo um comando externo ao Postfix pode rodar antes de ser
"morto" pelo processo "master". O default eh de 1000s; esse valor deve ser
suficiente para a maioria dos ambientes. No entanto, em horarios de pico de
utilizacao da maquina, ou sob ataque, esse limite pode causar erros de "Timeout
Exceeded" no Postfix. Pode aumenta-lo para um valor maior (talvez 1h) para
evitar isso. Basta colocar no main.cf uma linha assim:

#/etc/postfix/main.cf:
command_time_limit = 1h


Mantendo o "banco de dados" do ClamAV sempre atualizado
-------------------------------------------------------------------------

O ClamAV ja vem com uma ferramenta para fazer isso, o "freshclam". Pode-se
inicia-lo como um "daemon" no sistema e deixar que ele verifique se ha
atualizacoes no "banco de dados" do ClamAV. Voce pode inicia-lo com o comando:

/usr/bin/freshclam --log-verbose --daemon-notify --daemon --checks=50
--log=/var/log/clam/freshclam.log

Depois que se sentir "seguro" com o funcionamento do ClamAV (depois que ja tiver
mostrado pro seu chefe que o ClamAV se atualiza sozinho mesmo :D), voce pode
remover as opcoes de "verbose" do clamav.conf e do freshclam. Isso economiza
espaco em disco, descartando logs desnecessarios.

Ah, não se esqueca de colocar o freshclam para rodar no boot tambem :)

Alexandro Batista
Email: alexandrobatista@pop.com.br

Postado por fuji em julho 8, 2004 05:33 PM

Comentários para "Configurando o MTA PostFix no CL9"

» Postado por: Bruno em setembro 23, 2004 11:07 AM, 200.103.32.:

 

Antes de comentar...

- Preserve a qualidade desta discussão
- Leia os Termos de Uso.
- Este formulário deve ser usado para comentários sobre a notícia. Se você tem dúvidas ou precisa de ajuda, use o Fórum.
- Mantenha o foco nos argumentos e no assunto
- Não faça ataques pessoais.
- Pense 5 vezes antes de entrar em discussões inúteis, como "qual é a melhor distribuição/ambiente gráfico/linguagem de programação/etc.", mesmo se alguém já tiver provocado - um erro não justifica o outro
- Não seja um e-mala ;-)


O Arquivo Histórico do BR-Linux.org mantém no ar (sem alteração, exceto quanto à formatação) notícias, artigos e outros textos publicados originalmente no site na segunda metade da década de 1990 e na primeira década do século XXI, que contam parte considerável a história do Linux e do Open Source no Brasil. Exceto quando indicado em contrário, a autoria dos textos é de Augusto Campos, e os termos de uso podem ser consultados na capa do BR-Linux.org. Considerando seu caráter histórico, é provável que boa parte dos links estejam quebrados, e que as informações deste texto estejam desatualizadas.