Instalação de um servidor email com suporte para protocolo IMAPS.
root@server:~# apt-get install dovecot-imapd
Toda a configuração será guardada no ficheiro /etc/dovecot/local.conf. Caso o ficheiro não exista, pode ser criado com o comando touch
:
root@server:~# touch /etc/dovecot/local.conf
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 Ssl Auto-Assinados previamente gerados:
## ## SSL settings ## # SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt> ssl = yes # 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 ssl_cert = </etc/ssl/certs/server.crt ssl_key = </etc/ssl/private/server.key # [...]
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 { # [...] mail_max_userip_connections = 20 # [...] } [...]
A configuração pode ser verificada com o comando dovecot -n
:
root@server:~# dovecot -n # 2.2.13: /etc/dovecot/dovecot.conf # OS: Linux 3.16.0-4-amd64 x86_64 Debian 8.0 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_cert = </etc/ssl/certs/server.crt ssl_key = </etc/ssl/private/server.key userdb { driver = passwd }
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:~# service dovecot restart
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 AUTH=LOGIN] Dovecot ready. a001 login fribeiro password 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 SPECIAL-USE BINARY MOVE] Logged in a002 examine inbox * FLAGS (\Answered \Flagged \Deleted \Seen \Draft $MDNSent Junk NonJunk $Forwarded $label1 $label2 $label3 $label4 $label5 $NotJunk) * OK [PERMANENTFLAGS ()] Read-only mailbox. * 249 EXISTS * 0 RECENT * OK [UIDVALIDITY 1039012516] UIDs valid * OK [UIDNEXT 204882] Predicted next UID * OK [HIGHESTMODSEQ 94567] Highest a002 OK [READ-ONLY] Examine completed (0.000 secs). a003 logout * BYE Logging out a003 OK Logout completed. 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. a001 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=Home.lan/CN=*.home.lan verify error:num=18:self signed certificate verify return:1 depth=0 /C=PT/ST=Portugal/O=Home.lan/CN=*.home.lan verify return:1 --- Certificate chain 0 s:/C=PT/ST=Portugal/O=Home.lan/CN=*.home.lan i:/C=PT/ST=Portugal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VXiT3S8x+GQDDdFZmNn6X+lk0S3PjyW4+hHRtWfzZR9F7Pj4/aEpJEFlL+E LcTGzyBjgQhQOxL9yEgYfZoHgUzxtXx36QpiGm9KPbqGO+TYmiiwkAYHQatCYwHX 5W4h6t+tLzjuY9DLdk7BJsNKHq4CGAk5swSl2UKR7xxdSMDIBuWu3tzzvPaPKK4c 7zrbPuo6cbb8uSneC8hVGwsQLoMdmjgaH2LE/DI8z24LCha23p3MRZAvlIlMbqUx nqJcxh8HBpT/uhaSRhSvbrsN2ZSJ7nJJYELVdlHktlA/Bb+kTwzqRQ6AepdLze0V DSWPV4KPA3R5VkPUvEnkhOpSwtccoYiw+BLI8nS3aLoKWaoWrqdZaFlYVbRSaIxC Kh0NR30aLUTt22mS0KrxM6hTJGsi+jT/yZ/qFaz6ARb21GZpId1EfQsxfIw6ivcY 7q9d0D34LLrfWjt0Bq3TldVE5KLdF58y+j9qfkmYZmLCIiG/CzD5+5YTP6xvqtiN Y146nOJBEMBiZ14T1RAYi9/eDqUAySlZp4MTAtlfibu5NWSg5YpCZvXU0ubfPAe3 DdjN0VDIVj8ojCKOsr+WSZCkqxLnP6DobhV0sgOLqOlOZ4UeS99dZouzcQYMWPAu Sy+szMc+t3gxvPIGtc/MHcMcuLlP7ajuzCx6WXmxyh3qVQKIrzUH+vDnST/GNwg6 aJplmnltkwzQpy8e -----END CERTIFICATE----- subject=/C=PT/ST=Portugal/O=Home.lan/CN=*.home.lan issuer=/C=PT/ST=Portugal/O=Home.lan/CN=*.home.lan --- No client certificate CA names sent --- SSL handshake has read 2263 bytes and written 328 bytes --- New, TLSv1/SSLv3, Cipher is DHE-RSA-AES256-SHA Server public key is 4096 bit Secure Renegotiation IS supported Compression: NONE Expansion: NONE SSL-Session: Protocol : TLSv1 Cipher : DHE-RSA-AES256-SHA Session-ID: 55B89EC0A810855C28BDB08BAA38293634ACA7CA83E1E858617CB21D04C8E1AE Session-ID-ctx: Master-Key: 230F33E408B50323C36E1827F97E53DDC1DA355A6E3C1F5FA770B5367A7BAA992FA070E6D88C789C6C094BE37B27F160 Key-Arg : None Start Time: 1430073995 Timeout : 300 (sec) Verify return code: 18 (self signed certificate) --- * OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE AUTH=PLAIN AUTH=LOGIN] Dovecot ready. a001 login fribeiro password 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 SPECIAL-USE BINARY MOVE] Logged in a002 examine inbox * FLAGS (\Answered \Flagged \Deleted \Seen \Draft $MDNSent Junk NonJunk $Forwarded $label1 $label2 $label3 $label4 $label5 $NotJunk) * OK [PERMANENTFLAGS ()] Read-only mailbox. * 249 EXISTS * 0 RECENT * OK [UIDVALIDITY 1039012516] UIDs valid * OK [UIDNEXT 204882] Predicted next UID * OK [HIGHESTMODSEQ 94567] Highest a002 OK [READ-ONLY] Examine completed (0.000 secs). a003 logout * BYE Logging out a003 OK Logout completed. closed
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:
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.
Uma verificação deverá indicar que o certificado utilizado é realmente o que pretendemos:
Uma vez verificado, o certificado poderá ser acrescentado à lista de excepções de segurança.