Board logo

标题: Postfix+SASL2+Courier-IMAP+QUOTA+PostgreSQL HOW-TO [打印本页]

作者: 精灵萌萌    时间: 2006-1-17 10:55     标题: Postfix+SASL2+Courier-IMAP+QUOTA+PostgreSQL HOW-TO

  转
感觉这篇文档很不错,虽然是法文的但是仔细看看也不难可以看懂。
Postfix+SASL2+Courier-IMAP+QUOTA+PostgreSQL HOW-TO

Postfix+SASL2+Courier-IMAP+QUOTA+PostgreSQL HOW-TO

Este HOW-TO Foi escrito para auxiliar os Administradores que necessitam instalar um mailserver com suporte a domínios virtuais. Decidi usar o PostgreSQL como Banco de dados, pois este agrega uma série de funções mais complexas, e pensando que a instalação do servidor não é a única parte do processo. Talvez o administrador não queira usar  somente um gerenciador de  Domínios virtuais, e sim, fazer o controle do seu provedor inteiro dentro do PostgreSQL, via seu próprio "ISP Manager". Lógicamente, é necessário uma máquina bem parruda para faze-lo, mas acredito que seja uma boa solução no que diz respeito à domínios virtuais.

Infelizmente, ainda não pude adicionar ao HOW-TO, nada relacionado à filtragem de mensagens, pois o maildrop não dá suporte ao PostgreSQL.
Consta também neste HOW-TO a implementação de soft quota para controle das caixas postais. O controle é feito pelo próprio postfix, mas necessita a aplicação de um patch.

Para Administração simples dos domínios, iniciei o desenvolvimento do Post-MailAdmin, que é baseado no ótimo PostfixAdmin, que gerencia os domínios virtuais no MySQL.

Faça o Download do Post-MailAdmin
Alguns screenshots.

Tela de Login, Add Dominio, Add Mailbox







Iniciando o Processo

Instale o PostgreSQL(Faça download da ultima versão, ou baixe para sua distribuição)
Mais informações sobre o PostgreSQL aqui:
Baixe o cyrus-sasl e o patch para Crypt passwords.

O programa:

ftp://ftp.andrew.cmu.edu/pub/cyrus-mail/

O patch

http://frost.ath.cx/software/cyrus-sasl-patches/

Descompacte o software, aplique o Patch, compile e instale o programa:

[ root@server/~] # tar xvzf cyrus-sasl-2.*.*.tar.gz
[ root@server/~] # cd cyrus-sasl-2.*.*/
[ root@server/~] # patch -p0 <../cyrus-sasl-2.1.17-checkpw.c.patch
[ root@server/~] # ./configure --enable-login --enable-plain --enable-sql --with-pgsql=PATH-PARA-O-PGSQL
[ root@server/~] # make
[ root@server/~] # make install
[ root@server/~] # ln -s /usr/local/lib/sasl2 /usr/lib/sasl2
*** Não deixe de fazer isto, pois o cyrus-sasl não dá suporte à passwords crypt . Se está usando o sasl da sua distribuição, remova-o e instale a partir dos fontes***

Crie o arquivo /usr/lib/sasl2/smtpd.conf com o seguinte conteúdo:

pwcheck_method: auxprop
auxprop_plugin: sql
allowanonymouslogin: no
allowplaintext: yes
mech_list: PLAIN LOGIN
srp_mda: md5

srvtab: /dev/null
opiekeys: /dev/null

password_format: crypt

sql_engine: pgsql
sql_user: postfix
sql_passwd: postfix
sql_hostnames: localhost
sql_database: postfix
sql_select: SELECT password FROM mailbox WHERE username = &#39;%u@%r&#39; AND domain = &#39;%r&#39;
Baixe a ultima versão estável do Postfix:

[ root@server/~ ]# wget ftp://ftp.matrix.com.br/pub/postfix/official/postfix-*.tar.gz
[ root@server/~ ]# tar xvjf postfix-*.tar.gz

Baixe o patch para controle de quotas referente a versão que você baixou do postfix:
http://web.onda.com.br/nadal/

[ root@server/~ ]# gunzip postfix-*-trash.patch.gz
[ root@server/~ ]# patch -p0 <postfix-*-trash.patch
[ root@server/~ ]# cd postfix-*/
[ root@server/~ ]# make tidy
[ root@server/~ ]# make -f Makefile.init makefiles &#39;CCARGS=-DHAS_PGSQL -I/usr/local/pgsql/include -DUSE_SASL_AUTH -I/usr/local/include&#39; &#39;AUXLIBS=-L/usr/local/pgsql/lib -lpq -L/usr/local/lib/sasl2 -lsasl2&#39;

(Altere o caminho dos headers e das libs conforme a sua instalação do postgre e sasl2)

[ root@server/~ ]# make
[ root@server/~ ]# make install  #Se houver algum erro relacionado à sasl2, coloque o path "/usr/lib" em /etc/ld.so.conf

Inicie o PostgreSQL:

Se for baseado no Red Hat:

[ root@server/~ ]# service postgresql start
[ root@server/~ ]# su - postgres

Caso contrário:

[ root@server/~ ]# su - postgres
[ postgres@server/~ ]$ /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
[ postgres@server/~ ]$ postmaster -D /usr/local/pgsql/data >postgresql.log 2>&1 &

Crie o usuário a database e o user postfix:

[ postgres@server/~ ]$ createdb postfix
[ postgres@server/~ ]$ createuser postfix

Tabelas no PostgreSQL

[ postgres@server/~ ] $ psql postfix -U postfix

Caso não logar, descomente no /usr/local/pgsql/data/pg_hba.conf a linha abaixo (use isto, somente se o BD postfix, for para uso exclusivo do usuário postfix, e só para localhost), pois assim localmente, o usuário postfix do PostgreSQL não precisa de senha:
引用:
# TYPE  DATABASE  IP_ADDRESS  MASK  AUTH_TYPE  AUTH_ARGUMENT
local postfix seu_ip sua_mascara trust
Outro detalhe, é habilitar o PostgreSQL a escutar os pedidos de conexão.
Edite o postgresql.conf e habilite as linhas:

tcpip_socket = true
port = 5432

Logue no Postgre, crie as tabelas e dê permissão.

[ postgres@server/~ ] $ psql postfix -U postfix

CREATE TABLE "admin" (
"username" character varying(255) NOT NULL,
"password" character varying(255) NOT NULL,
"created" timestamp(13) with time zone DEFAULT &#39;1999-04-23 01:05:06&#39;,
"modified" timestamp(13) with time zone DEFAULT &#39;1999-04-23 01:05:06&#39;,
"active" boolean default true,
Constraint "admin_key" Primary Key ("username")
);

GRANT ALL ON admin TO postfix;

CREATE TABLE "alias" (
"address" character varying(255) NOT NULL,
"goto" text NOT NULL,
"domain" character varying(255) NOT NULL,
"created" timestamp(13) with time zone DEFAULT &#39;1999-04-23 01:05:06&#39;,
"modified" timestamp(13) with time zone DEFAULT &#39;1999-04-23 01:05:06&#39;,
"active" boolean default true,
Constraint "alias_key" Primary Key ("address")
);

GRANT ALL ON alias TO postfix;
CREATE TABLE "domain" (
"domain" character varying(255) NOT NULL,
"description" character varying(255) NOT NULL,
"aliases" numeric(10,0) DEFAULT &#39;0&#39; NOT NULL,
"mailboxes" numeric(10,0) DEFAULT &#39;0&#39; NOT NULL,
"maxquota" numeric(10,0) DEFAULT &#39;0&#39; NOT NULL,
"created" timestamp(13) with time zone DEFAULT &#39;1999-04-23 01:05:06&#39;,
"modified" timestamp(13) with time zone DEFAULT &#39;1999-04-23 01:05:06&#39;,
"active" boolean default true,
Constraint "domain_key" Primary Key ("domain")
);

GRANT ALL ON domain TO postfix;

CREATE TABLE "domain_admins" (
"username" character varying(255) NOT NULL,
"domains" character varying(255) NOT NULL,
"created" timestamp(13) with time zone DEFAULT &#39;1999-04-23 01:05:06&#39;,
"active" boolean default true,
Constraint "domain_admins_key" Primary Key ("username")
);

GRANT ALL ON domain_admins TO postfix;

CREATE TABLE "mailbox" (
"username" character varying(255) NOT NULL,
"password" character varying(255) NOT NULL,
"name" character varying(255) NOT NULL,
"maildir" character varying(255) NOT NULL,
"quota" numeric(10,0) DEFAULT &#39;0&#39; NOT NULL,
"domain" character varying(255) NOT NULL,
"created" timestamp(13) with time zone DEFAULT &#39;1999-04-23 01:05:06&#39;,
"modified" timestamp(13) with time zone DEFAULT &#39;1999-04-23 01:05:06&#39;,
"active" boolean DEFAULT &#39;t&#39;::bool,
"home" character varying(255) DEFAULT &#39;/var/spool/virtual/&#39;,
"uid" numeric(3,0) DEFAULT 200,
"gid" numeric(3,0) DEFAULT 200,
Constraint "mailbox_key" Primary Key ("username")
);


GRANT ALL ON mailbox TO postfix;

CREATE TABLE "vacation" (
"email" character varying(255) NOT NULL,
"subject" character varying(255) NOT NULL,
"body" text,
"cache" text NOT NULL,
"domain" character varying(255) NOT NULL,
"created" timestamp(13) with time zone DEFAULT &#39;1999-04-23 01:05:06&#39;,
"active" boolean default true,
Constraint "vacation_key" Primary Key ("email")
);

GRANT ALL ON vacation TO postfix;

De "q" para sair do psql

Configuração do Postfix para utilizar usuários Virtuais.
Lembre-se que esta configuração é para os usuários virtuais, seu postfix já tem que possuir as configurações default!

Adicione ao /etc/passwd:

vuser:x:200:200::/var/spool/virtual:/bin/false

Adicione ao /etc/group:

vgroup:x:200:

Crie o diretório e dê permissão:

[ root@server/~ ]# mkdir /var/spool/virtual
[ root@server/~ ]# chown 200:200 /var/spool/virtual

Crie os seguintes arquivos com os seguintes conteúdos:

/etc/postfix/pgsql_virtual_domains_maps.cf

user = postfix
password = postfix
dbname = postfix
table = domain
select_field = domain
where_field = domain
additional_conditions = and active = true

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

/etc/postfix/pgsql_virtual_mailbox_maps.cf

user = postfix
password = postfix
dbname = postfix
table = mailbox
select_field = maildir
where_field = username
additional_conditions = and active = true

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

/etc/postfix/pgsql_virtual_mailbox_size.cf

user = postfix
password = postfix
dbname = postfix
table = mailbox
select_field = quota
where_field = username
additional_conditions = and active = true

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


/etc/postfix/pgsql_virtual_alias_maps.cf

user = postfix
password = postfix
dbname = postfix
table = alias
select_field = goto
where_field = address
additional_conditions = and active = true

Edite o arquivo /etc/postfix/main.cf e adicione as seguintes configurações:
Lembrando novamente que estou supondo que você já fez a configuração básica do mesmo.
#PGSQL
virtual_uid_maps = static:200
virtual_gid_maps = static:200
virtual_mailbox_base = /var/spool/virtual
virtual_mailbox_domains = pgsql:/etc/postfix/pgsql_virtual_domains_maps.cf
virtual_mailbox_maps = pgsql:/etc/postfix/pgsql_virtual_mailbox_maps.cf
virtual_alias_maps = pgsql:/etc/postfix/pgsql_virtual_alias_maps.cf
virtual_mailbox_limit = 51200000
virtual_transport = virtual

#SASL2
smtpd_sasl_auth_enable = yes
smtpd_recipient_restrictions = permit_sasl_authenticated
        reject_unauth_destination, permit_mynetworks
smtpd_sasl_application_name = smtpd
broken_sasl_auth_clients = yes

#QUOTA
virtual_mailbox_limit_inbox = no
virtual_mailbox_limit_maps = pgsql:/etc/postfix/pgsql_virtual_mailbox_size.cf
virtual_mailbox_limit_override = yes
virtual_maildir_extended = yes
virtual_create_maildirsize = yes
virtual_mailbox_limit = 100000000

Simples teste:

Primeiro insira alguma coisa nas tabelas

INSERT INTO mailbox (username,password,name,maildir,quota,domain) values (&#39;teste@dominio.com.br&#39;,&#39;$1$Fi8IP53B$3yeGqD1Cnax.f.yAkLiAd1&#39;,&#39;name&#39;,&#39;teste@dominio.com.br/&#39;,1048576,&#39;dominio.com.br&#39;);

Insira a senha criptografada!

A SENHA NESTE CASO É a palavra teste e quota é de 1MB

INSERT INTO domain (domain,description,aliases,mailboxes,maxquota) values (&#39;dominio.com.br&#39;,&#39;Domínio Virtual&#39;,1,1,1);

Reinicie o Postfix:

[ root@server/~ ]# postfix stop; postfix start
Dê um telnet no host:
引用:
[root@server~/]# telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is &#39;^]&#39;.
220 server.domain.com.br ESMTP Postfix (2.1.0)
MAIL FROM: teste@dominio.com.br
250 Ok
RCPT TO: teste@dominio.com.br
250 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
teste
.
250 Ok: queued as 7B41F4665A
quit
221 Bye
Connection closed by foreign host.
[root@server~/]# cd /var/spool/virtual;ls -la
drwxr-xr-x   3   vuser  vgroup   4096 Abr 26 11:18 .
drwxr-xr-x   11  root  root    4096 Abr 26 10:44 ..
drwx------   5   vuser  vgroup   4096 Abr 26 11:18 teste@dominio.com.br
[root@server~/]#
Quando a mensagem chegar, será criado um arquivo chamado maildirsize dentro do diretório do usuário, que controlará a cota deste usuário virtual.

Courier-IMAP

Baixe o Courier-IMAP em http://www.courier-mta.org/download.php

Descompacte-o como usuário normal

[ tanga_frouxa@server/~ ]$ tar xfjv courier-imap-3.0.3.20040424.tar.bz2

Antes de iniciar o processo, certifique-se que existem os diretórios ou links /usr/include/pgsql e /usr/lib/pgsql, pois, se não existirem, pode acontecer de o courier-imap não ser compilado com suporte à PostgreSQL.

[ tanga_frouxa@server/~ ]$ ./configure --with-redhat --enable-workarounds-for-imap-client-bugs # O --with-redhat somente se vc está usando Red Hat linux.
[ tanga_frouxa@server/~ ]$ make

E como root:

[ root@server/~ ]# make install
[ root@server/~ ]# make install-configure

Configuração:

=> /usr/lib/courier-imap/etc/authdaemonrc

authmodulelist="authpgsql authpam"
authmodulelistorig="authpgsql authpam"
daemons=5  # Aumente este valor caso tiver muitos "clientes IMAP"
version=""
authdaemonvar=/usr/lib/courier-imap/var/authdaemon

=> /usr/lib/courier-imap/etc/authpgsqlrc
É provável que ele exista com o nome de authpgsqlrc.dist.

PGSQL_HOST localhost
PGSQL_PORT 5432
PGSQL_USERNAME postfix
PGSQL_PASSWORD postfix
PGSQL_DATABASE postfix
PGSQL_USER_TABLE mailbox
PGSQL_CRYPT_PWFIELD password
PGSQL_UID_FIELD uid
PGSQL_GID_FIELD gid
PGSQL_LOGIN_FIELD username
PGSQL_HOME_FIELD home
PGSQL_NAME_FIELD name
PGSQL_MAILDIR_FIELD maildir

Inicie o Courier-IMAP:

/usr/lib/courier-imap/libexec/imapd.rc start

Dê um telnet no host:
引用:
[root@server~/]# telnet localhost 110
Trying 127.0.0.1...
Connected to localhost.
Escape character is &#39;^]&#39;.
+OK Hello there.
user teste@dominio.com.br
+OK Password required.
pass teste
+OK logged in.
list
+OK POP3 clients that break here, they violate STD53.
1 1051
2 442
3 505
4 13516
5 27389
.
quit
+OK Bye-bye.
Connection closed by foreign host.
[root@server~/]#
Pronto agora é só Instalar o Post-MailAdmin para adicionar e remover os usuários. Assim que possível, coloco a parte de anti-vírus no Postfix.


--------------------------------------------------------------------------------

Bibliografia

Postfix Website: http://www.postfix.org
Pelas quotas, agradeço à Marco Máximo pelo seu HOW-TO no Link http://www.linuxit.com.br/section-viewarticle-78.html
SASL2: http://www.gfxcafe.com/Mail%20Howto.htm / http://frost.ath.cx/software/cyrus-sasl-patches/

Autor Leandro Mendes - 26/04/2004
Atualizado em: 12/07/2004
Artigo Original: http://aribabiba.cosmoquimica.com.br/leandro/
作者: jianci    时间: 2006-1-17 11:16

强啊~




欢迎光临 ExtMail服务器社区 (http://www.extmail.org/forum/) Powered by Discuz! 6.1.0