Ferramentas de Usuário

Ferramentas de Site


pt:buster:email:imap:dovecot

5.1.1 Servidor IMAP(S): Dovecot

Instalação de um servidor email com suporte para protocolo IMAPS.

Instalação

root@server:~# apt install dovecot-imapd

Configuração

Toda a configuração será guardada em diferentes ficheiros na diretoria /etc/dovecot/conf.d. Cada ficheiro de configuração é responsável por uma funcionalidade do dovecot.

O servidor de email dovecot só aceita ligações encriptadas via TLS (Transport Layer Security) ou SSL (Secure Sockets Layer). Ambos necessitam de certificados digitais.

Os certificados SSL para o dovecot são gerados automaticamente durante a instalação. No entanto, podemos utilizar os nosso próprios 3.5.1 Certificados Auto-Assinados ou os certificados 3.5.2 Certificados LetsEncrypt previamente gerados:

##
## SSL settings
##

# SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt>
#ssl = no
ssl = required

# PEM encoded X.509 SSL/TLS certificate and private key. They're opened before
# dropping root privileges, so keep the key file unreadable by anyone but
# root. Included doc/mkcert.sh can be used to easily generate self-signed
# certificate, just make sure to update the domains in dovecot-openssl.cnf
#ssl_cert = </etc/dovecot/dovecot.pem
#ssl_key = </etc/dovecot/private/dovecot.pem

# Certificados Let's Encrypt:
#ssl_cert = </etc/letsencrypt/live/home.example.com/cert.pem
#ssl_key = </etc/letsencrypt/live/home.example.com/privkey.pem

# Certificados auto-assinados:
ssl_cert = </etc/ssl/certs/server.crt
ssl_key = </etc/ssl/private/server.key

# [...]

Desativar ligações IMAP não seguras:

# [...]
service imap-login {
  inet_listener imap {
    #port = 143
    port = 0
  }
# [...]

A localização das caixas de correio também deve ser indicada, para evitar ambiguidades. Neste caso estão numa sub-directoria na directoria home de cada utilizador chamada “Maildir”:

# [...]
##
## Mailbox locations and namespaces
##

# Location for users' mailboxes. The default is empty, which means that Dovecot
# tries to find the mailboxes automatically. This won't work if the user
# doesn't yet have any mail, so you should explicitly tell Dovecot the full
# location.
#
# If you're using mbox, giving a path to the INBOX file (eg. /var/mail/%u)
# isn't enough. You'll also need to tell Dovecot where the other mailboxes are
# kept. This is called the "root mail directory", and it must be the first
# path given in the mail_location setting.
#
# There are a few special variables you can use, eg.:
#
#   %u - username
#   %n - user part in user@domain, same as %u if there's no domain
#   %d - domain part in user@domain, empty if there's no domain
#   %h - home directory
#
# See doc/wiki/Variables.txt for full list. Some examples:
#
#   mail_location = maildir:~/Maildir
#   mail_location = mbox:~/mail:INBOX=/var/mail/%u
#   mail_location = mbox:/var/mail/%d/%1n/%n:INDEX=/var/indexes/%d/%1n/%n
#
# <doc/wiki/MailLocation.txt>
#
#mail_location = mbox:~/mail:INBOX=/var/mail/%u
mail_location = maildir:~/Maildir

# [...]

O máximo de ligações permitidas por endereço IP pode ser aumentado, caso se preveja a necessidade de efetuar muitas ligações a partir de um único endereço.

# [...]

protocol imap {
  # Space separated list of plugins to load (default is global mail_plugins).
  mail_plugins = $mail_plugins

  # Maximum number of IMAP connections allowed for a user from each IP address.
  # NOTE: The username is compared case-sensitively.
  #mail_max_userip_connections = 10
  mail_max_userip_connections = 20
}

# [...]
}
[...]

Se existirem clientes mais antigos como o Outlook Express (Windows XP) ou o Microsoft Mail (Windows Vista), será necessário acrescentar o mecanismo de autenticação login, para além do plain. Apesar de estes serem mecanismos não encriptados, a opção disable_plaintext_auth = yes garante que estes só serão aceites através de uma ligação encriptada.

# [...]

##
## Authentication processes
##

# Disable LOGIN command and all other plaintext authentications unless
# SSL/TLS is used (LOGINDISABLED capability). Note that if the remote IP
# matches the local IP (ie. you're connecting from the same computer), the
# connection is considered secure and plaintext authentication is allowed.
# See also ssl=required setting.
disable_plaintext_auth = yes

# [...]

# Space separated list of wanted authentication mechanisms:
#   plain login digest-md5 cram-md5 ntlm rpa apop anonymous gssapi otp skey
#   gss-spnego
# NOTE: See also disable_plaintext_auth setting.
auth_mechanisms = plain login

# [...]

A configuração pode ser verificada com o comando dovecot -n:

root@server:~# dovecot -n
# 2.2.27 (c0f36b0): /etc/dovecot/dovecot.conf
# Pigeonhole version 0.4.16 (fed8554)
# OS: Linux 4.9.0-3-amd64 x86_64 Debian 9.0
auth_mechanisms = plain login
mail_location = maildir:~/Maildir
namespace inbox {
  inbox = yes
  location =
  mailbox Drafts {
    special_use = \Drafts
  }
  mailbox Junk {
    special_use = \Junk
  }
  mailbox Sent {
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
  mailbox Trash {
    special_use = \Trash
  }
  prefix =
}
passdb {
  driver = pam
}
protocols = " imap"
ssl = required
ssl_cert = </etc/ssl/certs/server.crt
ssl_key =  # hidden, use -P to show it
userdb {
  driver = passwd
}
protocol imap {
  mail_max_userip_connections = 20
}

A arborescência Maildir deverá ser criada sob a home de cada utilizador. Para isso deve ser usado o comando maildirmake.dovecot por cada utilizador já criado.

O comando abaixo muda temporariamente a identidade do utilizador corrente para um utilizador “fribeiro” e cria a arborescência Maildir na home desse utilizador. Este comando deve ser repetido para cada utilizador já existente:

root@server:~# su - fribeiro -c 'maildirmake.dovecot ~/Maildir'

Esta arborescência deve também ser criada sob a diretoria /etc/skel. O conteúdo de /etc/skel é utilizado como modelo para a directoria home dos utilizadores a serem criados futuramente. Assim, quando forem criados novos utilizadores, a arborescência Maildir será criada automaticamente:

root@server:~# maildirmake.dovecot /etc/skel/Maildir

Finalmente, reiniciar o servidor:

root@server:~# systemctl restart dovecot

Verificação

Verificar o serviço imap para endereços locais:

root@server:~# telnet 127.0.0.1 imap
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE STARTTLS AUTH=PLAIN] Dovecot ready.
a001 login fribeiro MyPassword
a001 OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS THREAD=ORDEREDSUBJECT MULTIAPPEND URL-PARTIAL CATENATE UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS BINARY MOVE SPECIAL-USE] Logged in
a002 examine inbox
* FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
* OK [PERMANENTFLAGS ()] Read-only mailbox.
* 0 EXISTS
* 0 RECENT
* OK [UIDVALIDITY 1498137163] UIDs valid
* OK [UIDNEXT 1] Predicted next UID
a002 OK [READ-ONLY] Examine completed (0.000 + 0.000 secs).
a003 logout
* BYE Logging out
a003 OK Logout completed (0.000 + 0.000 secs).
Connection closed by foreign host.

A partir de outro sistema, verificar que são recusadas as ligações IMAP simples sem TLS por serem consideradas inseguras, uma vez que enviam as passwords em texto simples:

fribeiro@laptop:~$ telnet 192.168.1.100 imap
Trying 192.168.1.100...
Connected to 192.168.1.100.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE STARTTLS LOGINDISABLED] Dovecot ready.
a001 login fribeiro password
* BAD [ALERT] Plaintext authentication not allowed without SSL/TLS, but your client did it anyway. If anyone was listening, the password was exposed.
a NO [PRIVACYREQUIRED] Plaintext authentication disallowed on non-secure (SSL/TLS) connections.
a002 logout
* BYE Logging out
a002 OK Logout completed.
Connection closed by foreign host.

No entanto, as ligações IMAPS deverão ser aceites a partir de qualquer sistema:

fribeiro@laptop:~# openssl s_client -connect 192.168.1.100:imaps
CONNECTED(00000003)
depth=0 C = PT, ST = Portugal, O = My Home Lan, CN = *.home.lan
verify error:num=18:self signed certificate
verify return:1
depth=0 C = PT, ST = Portugal, O = My Home Lan, CN = *.home.lan
verify return:1
---
Certificate chain
 0 s:/C=PT/ST=Portugal/O=My Home Lan/CN=*.home.lan
   i:/C=PT/ST=Portugal/O=My Home Lan/CN=*.home.lan
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIDEjCCAfoCCQC5Av+vK4F/cjANBgkqhkiG9w0BAQsFADBLMQswCQYDVQQGEwJQ
VDERMA8GA1UECAwIUG9yd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lan
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: ECDH, P-384, 384 bits
---
SSL handshake has read 1480 bytes and written 334 bytes
Verification error: self signed certificate
---
New, TLSv1.2, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: 640776EE6EF4A3093038CEEF0293EA2A4596FA4762D905EAD94D45CCE368D7BA
    Session-ID-ctx:
    Master-Key: 9972DB3D88FB643D81DB65EF131FFEBF4DC94B828D550F40D4804ED2A1B18B6BEA5594A37CFB0AB42A27D669CD51B033
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 7200 (seconds)
    TLS session ticket:
    0000 - a9 91 47 56 a3 4f f9 74-08 b1 8d 9d b2 e8 18 67   ..GV.O.t.......g
    0010 - 45 e3 07 44 2b 21 f9 f8-f7 78 95 ef 0a 77 28 9d   E..D+!...x...w(.
    0020 - 4f 29 1b 8a bc 2e d6 fc-09 a6 63 ae b6 09 70 19   O)........c...p.
    0030 - f6 be da bd cf 56 9c c9-a9 5b 5d eb 60 d8 69 cc   .....V...[].`.i.
    0040 - 29 29 89 68 59 78 04 11-62 f1 2b 47 dc 07 5a 23   )).hYx..b.+G..Z#
    0050 - 34 dd 97 18 9a 91 f4 0a-e4 eb 94 d0 1f 6e 63 fb   4............nc.
    0060 - b0 8d f1 48 cf 32 61 e7-92 3f 47 91 bf a1 48 da   ...H.2a..?G...H.
    0070 - 1a 9b 2e a3 69 8f 25 b0-31 4f ac bf 1b 81 f9 14   ....i.%.1O......
    0080 - bb e0 6b 7e 7c 9b 76 24-f4 17 42 e6 65 5e 16 ea   ..k~|.v$..B.e^..
    0090 - 50 c8 15 eb ef 6a f9 fb-d9 88 0d 82 a7 62 bf c3   P....j.......b..

    Start Time: 1498137742
    Timeout   : 7200 (sec)
    Verify return code: 18 (self signed certificate)
    Extended master secret: yes
---
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE AUTH=PLAIN] Dovecot ready.
a001 login fribeiro MyPassword
a001 OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS THREAD=ORDEREDSUBJECT MULTIAPPEND URL-PARTIAL CATENATE UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS BINARY MOVE SPECIAL-USE] Logged in
a002 examine inbox
* FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
* OK [PERMANENTFLAGS ()] Read-only mailbox.
* 0 EXISTS
* 0 RECENT
* OK [UIDVALIDITY 1498137163] UIDs valid
* OK [UIDNEXT 1] Predicted next UID
a002 OK [READ-ONLY] Examine completed (0.000 + 0.000 secs).
a003 logout
* BYE Logging out
a003 OK Logout completed (0.000 + 0.000 secs).
closed

Configuração clientes

Como verificação final poderá ser criada uma conta num cliente email, como o Thunderbird: deverá ser seleccionado protocolo IMAP, a ligação requer TLS (porta 143) ou SSL (porta 993) e o endereço será o do servidor (192.168.1.100 ou mail.home.lan, se tiver sido configurado um 3.1.3 Servidor DNS Local para a rede local).

Se for configurado o acesso sem TLS ou SSL, o acesso será negado:

Certificados Auto-assinados

Dado que os certificados são auto-assinados, os clientes email alertarão para o facto de não conhecerem a autoridade de certificação.

Alerta para a utilização de um certificado inválido

Uma verificação deverá indicar que o certificado utilizado é realmente o que pretendemos:

Verificação do conteúdo do certificado

Uma vez verificado, o certificado poderá ser acrescentado à lista de excepções de segurança.

Referências

pt/buster/email/imap/dovecot.txt · Última modificação em: 2024-02-15 01:05 por 127.0.0.1