Servidores de Email

Fedora oferece muitos aplicativos avançados para atender e acessar email. Este capítulo descreve os modernos protocolos de email em uso atualmente e alguns dos programas criados para enviar e receber email.

Protocolos de email

Hoje, o email é entregue usando uma arquitetura cliente / servidor. Uma mensagem de email é criada usando um programa de cliente de email. Este programa envia a mensagem para um servidor. O servidor encaminha a mensagem para o servidor de email do destinatário, onde a mensagem é fornecida ao cliente de email do destinatário.

Para habilitar esse processo, uma variedade de protocolos de rede padrão permite que máquinas diferentes, geralmente executando sistemas operacionais diferentes e usando programas de email diferentes, enviem e recebam emails.

Os seguintes protocolos discutidos são os mais usados na transferência de email.

Protocolos de Transporte de Mail

A entrega de correio de um aplicativo cliente para o servidor e de um servidor de origem para o servidor de destino é tratada pelo Simple Mail Transfer Protocol (SMTP).

SMTP The primary purpose of SMTP is

to transfer email between mail servers. However, it is critical for email clients as well. To send email, the client sends the message to an outgoing mail server, which in turn contacts the destination mail server for delivery. For this reason, it is necessary to specify an SMTP server when configuring an email client.

Debaixo Fedora, um usuário pode configurar um servidor SMTP na máquina local para lidar com a entrega de mensagens. No entanto, também é possível configurar servidores SMTP remotos para email de saída.

Um ponto importante a destacar sobre o protocolo SMTP é que ele não requer autenticação. Isso permite que qualquer pessoa na Internet envie e-mail para qualquer outra pessoa ou mesmo para grandes grupos de pessoas. É essa característica do SMTP que gera lixo eletrônico ou spam possible. A imposição de restrições de retransmissão limita que usuários aleatórios na Internet enviem email pelo servidor SMTP para outros servidores na Internet. Os servidores que não impõem essas restrições são chamados open relay servers.

Fedora fornece os programas SMTP Postfix e Sendmail.

Protocolos de acesso a email

Aqui estão dois protocolos principais usados pelos aplicativos clientes de email para recuperar emails de servidores de email: o Post Office Protocol (POP) e o Internet Message Access Protocol (IMAP).

POP The default POP server under

Fedora is Dovecot and is provided by the dovecot package.

Instalando o pacote dovecot

Para ser usado o Dovecot, primeiro verifique se o pacote dovecot está instalado no seu sistema executando, como root

~]# dnf install dovecot

For more information on installing packages with DNF, see Installing Packages.

Ao usar um servidor POP, as mensagens de email são baixadas pelos aplicativos clientes de email. Por padrão, a maioria dos clientes de email POP é configurada automaticamente para excluir a mensagem no servidor de email depois que ela foi transferida com êxito, no entanto, essa configuração geralmente pode ser alterada.

O POP é totalmente compatível com padrões importantes de mensagens da Internet, como Multipurpose Internet Mail Extensions (MIME), que permitem anexos de email.

O POP funciona melhor para usuários que possuem um sistema no qual ler e-mails. Também funciona bem para usuários que não têm uma conexão persistente com a Internet ou a rede que contém o servidor de email. Infelizmente para aqueles com conexões de rede lentas, o POP exige que os programas clientes, durante a autenticação, baixem todo o conteúdo de cada mensagem. Isso pode levar um longo tempo se alguma mensagem tiver anexos grandes.

A versão mais atual do protocolo padrão POP é o` POP3`.

Existem, no entanto, uma variedade de variantes de protocolo POP menos usadas:

  • * APOP * - POP3 com autenticação` MD5`. Um hash codificado da senha do usuário é enviado do cliente de email para o servidor, em vez de enviar uma senha não criptografada.

  • KPOPPOP3 com Kerberos authentication.

  • * RPOP * - POP3 com autenticação` RPOP`. Isso usa um ID por usuário, semelhante a uma senha, para autenticar solicitações POP. No entanto, esse ID não é criptografado, portanto, o RPOP não é mais seguro que o` POP` padrão

Para maior segurança, é possível usar Secure Socket Layer (SSL) criptografia para autenticação de cliente e sessões de transferência de dados. Isso pode ser ativado usando o aplicativo stunnel . Para obter mais informações sobre como proteger a comunicação por email, Veja Mail_Servers.adoc#s2-email-security.

IMAP The default IMAP server under

Fedora is Dovecot and is provided by the dovecot package. See Mail_Servers.adoc#s3-email-protocols-pop for information on how to install Dovecot.

Ao usar um servidor de email IMAP, as mensagens de email permanecem no servidor em que os usuários podem lê-las ou excluí-las. O IMAP também permite aos aplicativos clientes criar, renomear ou excluir diretórios de correio no servidor para organizar e armazenar emails.

O IMAP é particularmente útil para usuários que acessam seus e-mails usando várias máquinas. O protocolo também é conveniente para usuários que se conectam ao servidor de correio por uma conexão lenta, porque somente as informações do cabeçalho do e-mail são baixadas para mensagens até serem abertas, economizando largura de banda. O usuário também pode excluir mensagens sem visualizá-las ou baixá-las.

Por conveniência, os aplicativos clientes IMAP são capazes de armazenar em cache cópias das mensagens localmente, para que o usuário possa navegar pelas mensagens lidas anteriormente quando não estiver diretamente conectado ao servidor` IMAP`.

IMAP, como` POP`, é totalmente compatível com importantes padrões de mensagens da Internet, como MIME, que permitem anexos de e-mail.

Para maior segurança, é possível usar a criptografia SSL para autenticação de cliente e sessões de transferência de dados. Isso pode ser ativado usando o serviço imaps , ou usando o programa stunnel . Para obter mais informações sobre como proteger a comunicação por email, consulte Mail_Servers.adoc#s2-email-security.

Estão disponíveis outros clientes e servidores IMAP gratuitos e comerciais, muitos dos quais estendem o protocolo IMAP e fornecem funcionalidade adicional.

Dovecot The

imap-login and pop3-login processes which implement the IMAP and POP3 protocols are spawned by the master dovecot daemon included in the dovecot package. The use of IMAP and POP is configured through the /etc/dovecot/dovecot.conf configuration file; by default dovecot runs IMAP and POP3 together with their secure versions using SSL. To configure dovecot to use POP, complete the following steps:

  1. Edite o arquivo de configuração /etc/dovecot/dovecot.conf para garantir que a variável` protocolos` não seja comentada (remova o sinal de hash (# `) no início da linha) e contenha o argumento pop3`. Por exemplo:

    protocolos = imap pop3 lmtp

    Quando a variável `protocolos ` é deixada comentada, dovecot usará os valores padrão conforme descrito acima.

  2. Torne a alteração operacional para a sessão atual executando o seguinte comando como root:

    ~]# systemctl restart dovecot
  3. Torne a alteração operacional após a próxima reinicialização executando o comando:

    ~]# systemctl enable dovecot
    ln -s '/usr/lib/systemd/system/dovecot' '/etc/systemd/system/multi-user.target.wants/dovecot'
    O serviço dovecot inicia o servidor POP3

    Observe que [command] dovecot apenas informa que iniciou o servidor IMAP, mas também inicia o servidor` POP3`.

Diferentemente do SMTP, o` IMAP` e o POP3 exigem a conexão dos clientes para autenticação, usando um nome de usuário e senha. Por padrão, as senhas dos dois protocolos são passadas pela rede sem criptografia.

Para configurar o SSL em dovecot:

  • Edite o arquivo de configuração /etc/pki/dovecot/dovecot-openssl.cnf como preferir. No entanto, em uma instalação típica, esse arquivo não requer modificação.

  • Renomeie, mova ou exclua os arquivos /etc/pki/dovecot/certs/dovecot.pem e` /etc/pki/dovecot/private/dovecot.pem`.

  • Execute o script /usr/libexec/dovecot/mkcert.sh, que cria os certificados autoassinados dovecot . Estes certificados são copiados nos diretórios /etc/pki/dovecot/certs e` /etc/pki/dovecot/private`. Para implementar as alterações, reinicie [command] # dovecot # emitindo o seguinte comando como root:

    ~]# systemctl restart dovecot

More details on dovecot can be found online at http://www.dovecot.org.

Classificações do programa de e-mail

Em geral, todos os aplicativos de email se enquadram em pelo menos uma das três classificações. Cada classificação desempenha um papel específico no processo de mover e gerenciar mensagens de email. Embora a maioria dos usuários esteja ciente do programa de email específico usado para receber e enviar mensagens, cada um é importante para garantir que o email chegue ao destino correto.

Agente de Transporte de Email

Um Mail Transport Agent (MTA) transporta mensagens de email entre hosts usando o SMTP. Uma mensagem pode envolver vários MTAs à medida que se move para o destino pretendido.

Embora a entrega de mensagens entre máquinas possa parecer bastante direta, todo o processo de decidir se um MTA específico pode ou deve aceitar uma mensagem para entrega é bastante complicado. Além disso, devido a problemas de spam, o uso de um MTA específico geralmente é restrito pela configuração do MTA ou pela configuração de acesso da rede na qual o MTA reside.

Muitos programas modernos de cliente de email podem atuar como um MTA ao enviar email. No entanto, essa ação não deve ser confundida com o papel de um verdadeiro MTA. A única razão pela qual os programas clientes de email são capazes de enviar email como um MTA é porque o host que está executando o aplicativo não possui seu próprio MTA. Isso é particularmente verdadeiro para programas de cliente de email em sistemas operacionais não baseados em UNIX. No entanto, esses programas clientes enviam apenas mensagens de saída para um MTA que eles estão autorizados a usar e não entregam diretamente a mensagem ao servidor de email do destinatário pretendido.

Como o Fedora oferece dois MTAs, Postfix e Sendmail, os programas de cliente de email geralmente não precisam atuar como um MTA. Fedora também inclui um MTA de finalidade especial chamado Fetchmail.

Para obter mais informações sobre Postfix, Sendmail e Fetchmail, consulte xref: Mail_Servers.adoc # s1-email-mta [Mail Transport Agents].

Agente de Entrega de Email

Um Mail Delivery Agent (MDA) é chamado pelo MTA para arquivar e-mails recebidos na caixa de correio do usuário apropriado. Em muitos casos, o MDA é realmente um Local Delivery Agent (LDA), como mail ou Procmail.

Qualquer programa que realmente lida com uma mensagem para entrega até o ponto em que pode ser lido por um aplicativo cliente de email pode ser considerado um MDA. Por esse motivo, alguns MTAs (como Sendmail e Postfix) podem preencher a função de um MDA quando anexam novas mensagens de email ao arquivo de spool de email do usuário local. Em geral, os MDAs não transportam mensagens entre sistemas nem fornecem uma interface com o usuário; Os MDAs distribuem e classificam mensagens na máquina local para um aplicativo cliente de email acessar.

Mail User Agent

Um Mail User Agent (MUA) é sinônimo de um aplicativo cliente de email. Um MUA é um programa que, no mínimo, permite ao usuário ler e compor mensagens de email. Muitos MUAs são capazes de recuperar mensagens através dos protocolos POP ou` IMAP`, configurar caixas de correio para armazenar mensagens e enviar mensagens de saída para um MTA.

Os MUAs podem ser gráficos, como [application] * Evolution *, ou ter interfaces simples baseadas em texto, como [application] * Mutt *.

Mail Transport Agents

O Fedora oferece dois MTAs principais: Postfix e Sendmail. O Postfix está configurado como o MTA padrão e o Sendmail é considerado obsoleto. Se necessário, para mudar o MTA padrão para o Sendmail, você pode desinstalar o Postfix ou usar o seguinte comando como root para mudar para o Sendmail:

~]# alternatives --config mta

Você também pode usar o seguinte comando para ativar o serviço desejado:

~]# systemctl enable service

Da mesma forma, para desativar o serviço, digite o seguinte em um prompt de shell:

~]# systemctl disable service

For more information on how to manage system services in Fedora 27, see Services and Daemons.

Postfix

Originalmente desenvolvido na IBM pelo especialista em segurança e programador Wietse Venema, o Postfix é um MTA compatível com o Sendmail, projetado para ser seguro, rápido e fácil de configurar.

Para melhorar a segurança, o Postfix usa um design modular, em que pequenos processos com privilégios limitados são iniciados por um daemon master. Os processos menores e menos privilegiados realizam tarefas muito específicas relacionadas aos vários estágios da entrega de mensagens e são executados em um ambiente raiz alterado para limitar os efeitos dos ataques.

A configuração do Postfix para aceitar conexões de rede de hosts diferentes do computador local leva apenas algumas pequenas alterações em seu arquivo de configuração. No entanto, para aqueles com necessidades mais complexas, o Postfix oferece uma variedade de opções de configuração, além de complementos de terceiros que o tornam um MTA muito versátil e completo.

Os arquivos de configuração do Postfix são legíveis por humanos e suportam mais de 250 diretivas. Diferentemente do Sendmail, nenhum processamento de macro é necessário para que as alterações entrem em vigor e a maioria das opções mais usadas é descrita nos arquivos muito comentados.

The Default Postfix Installation indexterm:[Postfix,default

installation] The Postfix executable is postfix. This daemon launches all related processes needed to handle mail delivery.

O Postfix armazena seus arquivos de configuração no diretório /etc/postfix/. A seguir, é apresentada uma lista dos arquivos mais usados:

  • access - Usado para controle de acesso, este arquivo especifica quais hosts podem se conectar ao Postfix.

  • main.cf - O arquivo de configuração global do Postfix. A maioria das opções de configuração está especificada neste arquivo.

  • master.cf - Especifica como o Postfix interage com vários processos para realizar a entrega de mensagens.

  • transport - Mapeia endereços de email para retransmitir hosts.

O arquivo aliases pode ser encontrado no diretório /etc/. Este arquivo é compartilhado entre o Postfix e o Sendmail. É uma lista configurável requerida pelo protocolo de correio que descreve aliases de ID do usuário.

Configurando o Postfix como um servidor para outros clientes

O arquivo padrão /etc/postfix/main.cf não permite que o Postfix aceite conexões de rede de um host que não seja o computador local. Para obter instruções sobre como configurar o Postfix como servidor para outros clientes, consulte xref: Mail_Servers.adoc # s3-email-mta-postfix-conf [Configuração básica do Postfix].

Reinicie o serviço postfix depois de alterar qualquer opção nos arquivos de configuração no diretório` /etc/postfix` para que essas alterações entrem em vigor. Para fazer isso, execute o seguinte comando como root:

~]# systemctl restart postfix
Basic Postfix Configuration

Por padrão, o Postfix não aceita conexões de rede de nenhum host que não seja o host local. Execute as seguintes etapas como root para habilitar a entrega de correio para outros hosts na rede:

  • Edite o arquivo /etc/postfix/main.cf com um editor de texto, como vi.

  • Uncomment the mydomain line by removing the hash sign (), and replace domain.tld with the domain the mail server is servicing, such as [command]#example.com.

  • Uncomment the myorigin = $mydomain line.

  • Uncomment the myhostname line, and replace host.domain.tld with the host name for the machine.

  • Uncomment the mydestination = $myhostname, localhost.$mydomain line.

  • Uncomment the mynetworks line, and replace 168.100.189.0/28 with a valid network setting for hosts that can connect to the server.

  • Uncomment the inet_interfaces = all line.

  • Comment the inet_interfaces = localhost line.

  • Restart the postfix service.

Depois que essas etapas são concluídas, o host aceita e-mails externos para entrega.

O Postfix possui uma grande variedade de opções de configuração. Uma das melhores maneiras de aprender a configurar o Postfix é ler os comentários no arquivo de configuração /etc/postfix/main.cf. Recursos adicionais, incluindo informações sobre a configuração do Postfix, integração do SpamAssassin ou descrições detalhadas dos parâmetros /etc/postfix/main.cf estão disponíveis on-line no link: http://www.postfix.org/ [http:

Using Postfix with LDAP

O Postfix pode usar um diretório LDAP como fonte para várias tabelas de pesquisa (por exemplo:` aliases`, virtual,` canonical`, etc.). Isso permite que o LDAP armazene informações hierárquicas do usuário e que o Postfix receba apenas o resultado de consultas do` LDAP` quando necessário. Ao não armazenar essas informações localmente, os administradores podem mantê-las facilmente.

O exemplo de pesquisa do /etc/aliases

A seguir, é apresentado um exemplo básico de uso do LDAP para procurar o arquivo`/etc/aliases`. Verifique se o seu arquivo /etc/postfix/main.cf contém o seguinte:

alias_maps = hash:/etc/aliases, ldap:/etc/postfix/ldap-aliases.cf

Crie um arquivo /etc/postfix/ldap-aliases.cf se você ainda não tiver um e verifique se ele contém o seguinte:

server_host = ldap.example.com
search_base = dc=example, dc=com

onde ldap.example.com,` exemplo` e com são parâmetros que precisam ser substituídos pela especificação de um servidor` LDAP` disponível.

O arquivo /etc/postfix/ldap-aliases.cf

O arquivo /etc/postfix/ldap-aliases.cf pode especificar vários parâmetros, incluindo parâmetros que ativam o` LDAP` SSL e` STARTTLS`. Para mais informações, consulte a página do manual ldap_table (5).

For more information on LDAP, see Directory_Servers.adoc#s1-OpenLDAP.

Sendmail

O objetivo principal do Sendmail, como outros MTAs, é transferir e-mails com segurança entre hosts, geralmente usando o protocolo SMTP. Observe que o Sendmail é considerado obsoleto e os usuários são incentivados a usar o Postfix quando possível. consulte xref: Mail_Servers.adoc # s2-email-mta-postfix [Postfix] para obter mais informações.

Purpose and Limitations

It is important to be aware of what Sendmail is and what it can do, as opposed to what it is not. In these days of monolithic applications that fulfill multiple roles, Sendmail may seem like the only application needed to run an email server within an organization. Technically, this is true, as Sendmail can spool mail to each users' directory and deliver outbound mail for users. However, most users actually require much more than simple email delivery. Users usually want to interact with their email using an MUA, that uses POP or IMAP, to download their messages to their local machine. Or, they may prefer a Web interface to gain access to their mailbox. These other applications can work in conjunction with Sendmail, but they actually exist for different reasons and can operate separately from one another.

Está além do escopo desta seção abordar tudo o que o Sendmail deve ou pode estar configurado para fazer. Com literalmente centenas de opções e conjuntos de regras diferentes, volumes inteiros foram dedicados a ajudar a explicar tudo o que pode ser feito e como consertar coisas que dão errado. Consulte xref: Mail_Servers.adoc # s1-email-additional-resources [Recursos adicionais] para obter uma lista dos recursos do Sendmail.

Esta seção analisa os arquivos instalados com o Sendmail por padrão e analisa as alterações básicas de configuração, incluindo como interromper emails indesejados (spam) e estender o Sendmail com o _ LDAP (_Lightweight Directory Access Protocol) _.

The Default Sendmail Installation indexterm:[Sendmail,default

installation] In order to use Sendmail, first ensure the sendmail package is installed on your system by running, as root:

~]# dnf install sendmail

Para configurar o Sendmail, verifique se o pacote [package]*sendmail-cf * está instalado no seu sistema executando, como root:

~]# dnf install sendmail-cf

For more information on installing packages with DNF, see Installing Packages.

Antes de usar o Sendmail, o MTA padrão deve ser alterado do Postfix. Para obter mais informações sobre como alternar o MTA padrão, consulte xref: Mail_Servers.adoc#s1-email-mta[Mail Transport Agents].

O executável do Sendmail é sendmail.

O arquivo de configuração detalhado e longo do Sendmail é /etc/mail/sendmail.cf. Evite editar o arquivo sendmail.cf diretamente. Para fazer alterações na configuração do Sendmail, edite o arquivo /etc/mail/sendmail.mc, faça backup do arquivo`/etc/mail/sendmail.cf` original e use as seguintes alternativas para gerar um novo arquivo de configuração:

  • Use o makefile incluído em /etc/mail/ para criar um novo arquivo de configuração /etc/mail/sendmail.cf:

    ~]# make all -C /etc/mail/

    Todos os outros arquivos gerados em /etc/mail (db files) serão regenerados, se necessário. Os comandos antigos do makemap ainda são utilizáveis. O comando make é usado automaticamente sempre que você inicia ou reinicia o serviço sendmail.

Mais informações sobre a configuração do Sendmail podem ser encontradas em Mail_Servers.adoc#s3-email-mta-sendmail-changes.

Vários arquivos de configuração do Sendmail estão instalados no diretório /etc/mail/, incluindo:

  • access - Especifica quais sistemas podem usar o Sendmail para enviar e-mails.

  • domaintable - Especifica o mapeamento de nomes de domínio.

  • local-host-names - Especifica aliases para o host.

  • mailertable - Especifica instruções que substituem o roteamento para domínios específicos.

  • virtusertable - Especifica uma forma específica de domínio de alias, permitindo que vários domínios virtuais sejam hospedados em uma máquina.

Vários dos arquivos de configuração no diretório /etc/mail/, como access,` domaintable`, mailertable e` virtusertable`, devem realmente armazenar suas informações nos arquivos do banco de dados antes que o Sendmail possa usar qualquer alteração na configuração. Para incluir quaisquer alterações feitas nessas configurações em seus arquivos de banco de dados, execute os seguintes comandos, como root:

~]# cd /etc/mail/
~]# make all

Isso atualizará virtusertable.db,` access.db`, domaintable.db,` mailertable.db`, sendmail.cf e` submit.cf`.

Para atualizar todos os arquivos de banco de dados listados acima e para atualizar um arquivo de banco de dados personalizado, use um comando no seguinte formato:

make name.db all

where name representa o nome do arquivo de banco de dados customizado a ser atualizado.

To update a single database, use a command in the following format:

make name.db

onde name.db representa o nome do arquivo de banco de dados a ser atualizado.

Você também pode reiniciar o serviço sendmail para que as alterações entrem em vigor executando:

~]# systemctl restart sendmail

Por exemplo, para que todos os emails endereçados ao domínio example.com sejam entregues em` bob@other-example.com`, adicione a seguinte linha ao arquivo virtusertable:

@example.com bob@other-example.com

To finalize the change, the virtusertable.db file must be updated:

~]# make virtusertable.db all

Usar a opção [option] all resultará na atualização do` virtusertable.db` e do access.db ao mesmo tempo.

Common Sendmail Configuration Changes indexterm:[Sendmail,common

configuration changes] When altering the Sendmail configuration file, it is best not to edit an existing file, but to generate an entirely new /etc/mail/sendmail.cf file.

Faça backup do arquivo sendmail.cf antes de alterar seu conteúdo

Antes de substituir ou fazer alterações no arquivo sendmail.cf, crie uma cópia de backup.

Para adicionar a funcionalidade desejada ao Sendmail, edite o arquivo /etc/mail/sendmail.mc como` root`. Quando terminar, reinicie o serviço sendmail e, se o pacote [package]*m4 * estiver instalado, o processador de macro m4 gerará automaticamente um novo arquivo de configuração` sendmail.cf`:

~]# systemctl restart sendmail
Configurando o Sendmail como um servidor para outros clientes

O arquivo padrão sendmail.cf não permite que o Sendmail aceite conexões de rede de qualquer host que não seja o computador local. Para configurar o Sendmail como um servidor para outros clientes, edite o arquivo /etc/mail/sendmail.mc e altere o endereço especificado na opção Addr= da diretiva DAEMON_OPTIONS de 127.0.0.1 para o endereço IP de um dispositivo de rede ativo ou comente a diretiva DAEMON_OPTIONS todos juntos, colocando dnl no início da linha. Quando terminar, gere novamente o arquivo /etc/mail/sendmail.cf, reiniciando o serviço:

~]# systemctl restart sendmail

The default configuration in Fedora works for most SMTP-only sites. However, it does not work for UUCP (UNIX-to-UNIX Copy Protocol) sites. If using UUCP mail transfers, the /etc/mail/sendmail.mc file must be reconfigured and a new /etc/mail/sendmail.cf file must be generated.

Consult the /usr/share/sendmail-cf/README file before editing any files in the directories under the /usr/share/sendmail-cf/ directory, as they can affect the future configuration of the /etc/mail/sendmail.cf file.

Masquerading

One common Sendmail configuration is to have a single machine act as a mail gateway for all machines on the network. For example, a company may want to have a machine called mail.example.com that handles all of their email and assigns a consistent return address to all outgoing mail.

In this situation, the Sendmail server must masquerade the machine names on the company network so that their return address is user@example.com instead of user@host.example.com.

To do this, add the following lines to /etc/mail/sendmail.mc:

FEATURE(always_add_domain)dnl
FEATURE(`masquerade_entire_domain')dnl
FEATURE(`masquerade_envelope')dnl
FEATURE(`allmasquerade')dnl
MASQUERADE_AS(`example.com.')dnl
MASQUERADE_DOMAIN(`example.com.')dnl
MASQUERADE_AS(example.com)dnl

After generating a new sendmail.cf file using the m4 macro processor, this configuration makes all mail from inside the network appear as if it were sent from example.com.

Stopping Spam Email spam can be defined as

unnecessary and unwanted email received by a user who never requested the communication. It is a disruptive, costly, and widespread abuse of Internet communication standards.

Sendmail makes it relatively easy to block new spamming techniques being employed to send junk email. It even blocks many of the more usual spamming methods by default. Main anti-spam features available in sendmail are header checks, relaying denial (default from version 8.9), access database and sender information checks.

For example, forwarding of SMTP messages, also called relaying, has been disabled by default since Sendmail version 8.9. Before this change occurred, Sendmail directed the mail host (x.edu) to accept messages from one party (y.com) and sent them to a different party (z.net). Now, however, Sendmail must be configured to permit any domain to relay mail through the server. To configure relay domains, edit the /etc/mail/relay-domains file and restart Sendmail

~]# systemctl restart sendmail

However users can also be sent spam from from servers on the Internet. In these instances, Sendmail’s access control features available through the /etc/mail/access file can be used to prevent connections from unwanted hosts. The following example illustrates how this file can be used to both block and specifically allow access to the Sendmail server:

badspammer.com ERROR:550 "Go away and do not spam us anymore" tux.badspammer.com OK 10.0 RELAY

This example shows that any email sent from badspammer.com is blocked with a 550 RFC-821 compliant error code, with a message sent back. Email sent from the tux.badspammer.com sub-domain, is accepted. The last line shows that any email sent from the 10.0.. network can be relayed through the mail server.

Because the /etc/mail/access.db file is a database, use the makemap command to update any changes. Do this using the following command as root:

~]# makemap hash /etc/mail/access < /etc/mail/access

Message header analysis allows you to reject mail based on header contents. SMTP servers store information about an email’s journey in the message header. As the message travels from one MTA to another, each puts in a Received header above all the other Received headers. It is important to note that this information may be altered by spammers.

The above examples only represent a small part of what Sendmail can do in terms of allowing or blocking access. See the /usr/share/sendmail-cf/README file for more information and examples.

Since Sendmail calls the Procmail MDA when delivering mail, it is also possible to use a spam filtering program, such as SpamAssassin, to identify and file spam for users. See Mail_Servers.adoc#s3-email-mda-spam for more information about using SpamAssassin.

Using Sendmail with LDAP Using LDAP

is a very quick and powerful way to find specific information about a particular user from a much larger group. For example, an LDAP server can be used to look up a particular email address from a common corporate directory by the user’s last name. In this kind of implementation, LDAP is largely separate from Sendmail, with LDAP storing the hierarchical user information and Sendmail only being given the result of LDAP queries in pre-addressed email messages.

However, Sendmail supports a much greater integration with LDAP, where it uses LDAP to replace separately maintained files, such as /etc/aliases and /etc/mail/virtusertables, on different mail servers that work together to support a medium- to enterprise-level organization. In short, LDAP abstracts the mail routing level from Sendmail and its separate configuration files to a powerful LDAP cluster that can be leveraged by many different applications.

The current version of Sendmail contains support for LDAP. To extend the Sendmail server using LDAP, first get an LDAP server, such as OpenLDAP, running and properly configured. Then edit the /etc/mail/sendmail.mc to include the following:

LDAPROUTE_DOMAIN('yourdomain.com')dnl
FEATURE('ldap_routing')dnl
Advanced configuration

This is only for a very basic configuration of Sendmail with LDAP. The configuration can differ greatly from this depending on the implementation of LDAP, especially when configuring several Sendmail machines to use a common LDAP server.

Consult /usr/share/sendmail-cf/README for detailed LDAP routing configuration instructions and examples.

Next, recreate the /etc/mail/sendmail.cf file by running the m4 macro processor and again restarting Sendmail. See Mail_Servers.adoc#s3-email-mta-sendmail-changes for instructions.

For more information on LDAP, see Directory_Servers.adoc#s1-OpenLDAP.

Fetchmail

Fetchmail is an MTA which retrieves email from remote servers and delivers it to the local MTA. Many users appreciate the ability to separate the process of downloading their messages located on a remote server from the process of reading and organizing their email in an MUA. Designed with the needs of dial-up users in mind, Fetchmail connects and quickly downloads all of the email messages to the mail spool file using any number of protocols, including POP3 and IMAP. It can even forward email messages to an SMTP server, if necessary.

Installing the fetchmail package

In order to use Fetchmail, first ensure the fetchmail package is installed on your system by running, as root:

~]# dnf install fetchmail

For more information on installing packages with DNF, see Installing Packages.

Fetchmail is configured for each user through the use of a .fetchmailrc file in the user’s home directory. If it does not already exist, create the .fetchmailrc file in your home directory

Using preferences in the .fetchmailrc file, Fetchmail checks for email on a remote server and downloads it. It then delivers it to port 25 on the local machine, using the local MTA to place the email in the correct user’s spool file. If Procmail is available, it is launched to filter the email and place it in a mailbox so that it can be read by an MUA.

Fetchmail Configuration Options indexterm:[Fetchmail,configuration

options] Although it is possible to pass all necessary options on the command line to check for email on a remote server when executing Fetchmail, using a .fetchmailrc file is much easier. Place any desired configuration options in the .fetchmailrc file for those options to be used each time the fetchmail command is issued. It is possible to override these at the time Fetchmail is run by specifying that option on the command line.

A user’s .fetchmailrc file contains three classes of configuration options:

  • global options — Gives Fetchmail instructions that control the operation of the program or provide settings for every connection that checks for email.

  • server options — Specifies necessary information about the server being polled, such as the host name, as well as preferences for specific email servers, such as the port to check or number of seconds to wait before timing out. These options affect every user using that server.

  • user options — Contains information, such as user name and password, necessary to authenticate and check for email using a specified email server.

Global options appear at the top of the .fetchmailrc file, followed by one or more server options, each of which designate a different email server that Fetchmail should check. User options follow server options for each user account checking that email server. Like server options, multiple user options may be specified for use with a particular server as well as to check multiple email accounts on the same server.

Server options are called into service in the .fetchmailrc file by the use of a special option verb, poll or skip, that precedes any of the server information. The poll action tells Fetchmail to use this server option when it is run, which checks for email using the specified user options. Any server options after a skip action, however, are not checked unless this server’s host name is specified when Fetchmail is invoked. The skip option is useful when testing configurations in the .fetchmailrc file because it only checks skipped servers when specifically invoked, and does not affect any currently working configurations.

The following is an example of a .fetchmailrc file:

set postmaster "user1"
set bouncemail

poll pop.domain.com proto pop3
    user 'user1' there with password 'secret' is user1 here

poll mail.domain2.com
    user 'user5' there with password 'secret2' is user1 here
    user 'user7' there with password 'secret3' is user1 here

In this example, the global options specify that the user is sent email as a last resort (postmaster option) and all email errors are sent to the postmaster instead of the sender (bouncemail option). The set action tells Fetchmail that this line contains a global option. Then, two email servers are specified, one set to check using POP3, the other for trying various protocols to find one that works. Two users are checked using the second server option, but all email found for any user is sent to user1's mail spool. This allows multiple mailboxes to be checked on multiple servers, while appearing in a single MUA inbox. Each user’s specific information begins with the user action.

Omitting the password from the configuration

Users are not required to place their password in the .fetchmailrc file. Omitting the with password 'password' section causes Fetchmail to ask for a password when it is launched.

Fetchmail has numerous global, server, and local options. Many of these options are rarely used or only apply to very specific situations. The fetchmail man page explains each option in detail, but the most common ones are listed in the following three sections.

Global Options indexterm:[Fetchmail,configuration options,global

options] Each global option should be placed on a single line after a set action.

  • daemon seconds — Specifies daemon-mode, where Fetchmail stays in the background. Replace seconds with the number of seconds Fetchmail is to wait before polling the server.

  • postmaster — Specifies a local user to send mail to in case of delivery problems.

  • syslog — Specifies the log file for errors and status messages. By default, this is /var/log/maillog.

Server Options indexterm:[Fetchmail,configuration options,server

options] Server options must be placed on their own line in .fetchmailrc after a poll or skip action.

  • auth auth-type — Replace auth-type with the type of authentication to be used. By default, password authentication is used, but some protocols support other types of authentication, including kerberos_v5, kerberos_v4, and ssh. If the any authentication type is used, Fetchmail first tries methods that do not require a password, then methods that mask the password, and finally attempts to send the password unencrypted to authenticate to the server.

  • interval number — Polls the specified server every number of times that it checks for email on all configured servers. This option is generally used for email servers where the user rarely receives messages.

  • port port-number — Replace port-number with the port number. This value overrides the default port number for the specified protocol.

  • proto protocol — Replace protocol with the protocol, such as pop3 or imap, to use when checking for messages on the server.

  • timeout seconds — Replace seconds with the number of seconds of server inactivity after which Fetchmail gives up on a connection attempt. If this value is not set, a default of 300 seconds is used.

User Options indexterm:[Fetchmail,configuration options,user

options] User options may be placed on their own lines beneath a server option or on the same line as the server option. In either case, the defined options must follow the user option (defined below).

  • fetchall — Orders Fetchmail to download all messages in the queue, including messages that have already been viewed. By default, Fetchmail only pulls down new messages.

  • fetchlimit number — Replace number with the number of messages to be retrieved before stopping.

  • flush — Deletes all previously viewed messages in the queue before retrieving new messages.

  • limit max-number-bytes — Replace max-number-bytes with the maximum size in bytes that messages are allowed to be when retrieved by Fetchmail. This option is useful with slow network links, when a large message takes too long to download.

  • password 'password' — Replace password with the user’s password.

  • preconnect "command" — Replace command with a command to be executed before retrieving messages for the user.

  • postconnect "command" — Replace command with a command to be executed after retrieving messages for the user.

  • ssl — Activates SSL encryption.

  • user "username" — Replace username with the username used by Fetchmail to retrieve messages. This option must precede all other user options.

Fetchmail Command Options Most

Fetchmail options used on the command line when executing the fetchmail command mirror the .fetchmailrc configuration options. In this way, Fetchmail may be used with or without a configuration file. These options are not used on the command line by most users because it is easier to leave them in the .fetchmailrc file.

There may be times when it is desirable to run the fetchmail command with other options for a particular purpose. It is possible to issue command options to temporarily override a .fetchmailrc setting that is causing an error, as any options specified at the command line override configuration file options.

Informational or Debugging Options indexterm:[Fetchmail,command

options,informational] Certain options used after the fetchmail command can supply important information.

  • --configdump — Displays every possible option based on information from .fetchmailrc and Fetchmail defaults. No email is retrieved for any users when using this option.

  • -s — Executes Fetchmail in silent mode, preventing any messages, other than errors, from appearing after the fetchmail command.

  • -v — Executes Fetchmail in verbose mode, displaying every communication between Fetchmail and remote email servers.

  • -V — Displays detailed version information, lists its global options, and shows settings to be used with each user, including the email protocol and authentication method. No email is retrieved for any users when using this option.

Special Options These

options are occasionally useful for overriding defaults often found in the .fetchmailrc file.

  • -a — Fetchmail downloads all messages from the remote email server, whether new or previously viewed. By default, Fetchmail only downloads new messages.

  • -k — Fetchmail leaves the messages on the remote email server after downloading them. This option overrides the default behavior of deleting messages after downloading them.

  • -l max-number-bytes — Fetchmail does not download any messages over a particular size and leaves them on the remote email server.

  • --quit — Quits the Fetchmail daemon process.

More commands and .fetchmailrc options can be found in the fetchmail man page.

Mail Transport Agent (MTA) Configuration

A Mail Transport Agent (MTA) is essential for sending email. A Mail User Agent (MUA) such as Evolution, Thunderbird, and Mutt, is used to read and compose email. When a user sends an email from an MUA, the message is handed off to the MTA, which sends the message through a series of MTAs until it reaches its destination.

Even if a user does not plan to send email from the system, some automated tasks or system programs might use the mail command to send email containing log messages to the root user of the local system. Fedora 27 provides two MTAs: Postfix and Sendmail. If both are installed, Postfix is the default MTA. Note that Sendmail is considered deprecated in MAJOROS;.

Mail Delivery Agents

Fedora includes two primary MDAs, Procmail and mail. Both of the applications are considered LDAs and both move email from the MTA’s spool file into the user’s mailbox. However, Procmail provides a robust filtering system.

This section details only Procmail. For information on the mail command, consult its man page (man mail). Procmail delivers and filters email as it is placed in the mail spool file of the localhost. It is powerful, gentle on system resources, and widely used. Procmail can play a critical role in delivering email to be read by email client applications.

Procmail can be invoked in several different ways. Whenever an MTA places an email into the mail spool file, Procmail is launched. Procmail then filters and files the email for the MUA and quits. Alternatively, the MUA can be configured to execute Procmail any time a message is received so that messages are moved into their correct mailboxes. By default, the presence of /etc/procmailrc or of a ~/.procmailrc file (also called an rc file) in the user’s home directory invokes Procmail whenever an MTA receives a new message.

By default, no system-wide rc files exist in the /etc/ directory and no .procmailrc files exist in any user’s home directory. Therefore, to use Procmail, each user must construct a .procmailrc file with specific environment variables and rules.

Whether Procmail acts upon an email message depends upon whether the message matches a specified set of conditions or recipes in the rc file. If a message matches a recipe, then the email is placed in a specified file, is deleted, or is otherwise processed.

When Procmail starts, it reads the email message and separates the body from the header information. Next, Procmail looks for a /etc/procmailrc file and rc files in the /etc/procmailrcs directory for default, system-wide, Procmail environmental variables and recipes. Procmail then searches for a .procmailrc file in the user’s home directory. Many users also create additional rc files for Procmail that are referred to within the .procmailrc file in their home directory.

Procmail Configuration

The Procmail configuration file contains important environmental variables. These variables specify things such as which messages to sort and what to do with the messages that do not match any recipes.

These environmental variables usually appear at the beginning of the ~/.procmailrc file in the following format:

env-variable="value"

In this example, env-variable is the name of the variable and value defines the variable.

There are many environment variables not used by most Procmail users and many of the more important environment variables are already defined by a default value. Most of the time, the following variables are used:

  • DEFAULT — Sets the default mailbox where messages that do not match any recipes are placed.

    The default DEFAULT value is the same as $ORGMAIL.

  • INCLUDERC — Specifies additional rc files containing more recipes for messages to be checked against. This breaks up the Procmail recipe lists into individual files that fulfill different roles, such as blocking spam and managing email lists, that can then be turned off or on by using comment characters in the user’s ~/.procmailrc file.

    For example, lines in a user’s ~/.procmailrc file may look like this:

    MAILDIR=$HOME/Msgs
    INCLUDERC=$MAILDIR/lists.rc
    INCLUDERC=$MAILDIR/spam.rc

    To turn off Procmail filtering of email lists but leaving spam control in place, comment out the first INCLUDERC line with a hash sign (#). Note that it uses paths relative to the current directory.

  • LOCKSLEEP — Sets the amount of time, in seconds, between attempts by Procmail to use a particular lockfile. The default is 8 seconds.

  • LOCKTIMEOUT — Sets the amount of time, in seconds, that must pass after a lockfile was last modified before Procmail assumes that the lockfile is old and can be deleted. The default is 1024 seconds.

  • LOGFILE — The file to which any Procmail information or error messages are written.

  • MAILDIR — Sets the current working directory for Procmail. If set, all other Procmail paths are relative to this directory.

  • ORGMAIL — Specifies the original mailbox, or another place to put the messages if they cannot be placed in the default or recipe-required location.

    By default, a value of /var/spool/mail/$LOGNAME is used.

  • SUSPEND — Sets the amount of time, in seconds, that Procmail pauses if a necessary resource, such as swap space, is not available.

  • SWITCHRC — Allows a user to specify an external file containing additional Procmail recipes, much like the INCLUDERC option, except that recipe checking is actually stopped on the referring configuration file and only the recipes on the SWITCHRC-specified file are used.

  • VERBOSE — Causes Procmail to log more information. This option is useful for debugging.

Other important environmental variables are pulled from the shell, such as LOGNAME, the login name; HOME, the location of the home directory; and SHELL, the default shell.

A comprehensive explanation of all environments variables, and their default values, is available in the procmailrc man page.

Procmail Recipes

New users often find the construction of recipes the most difficult part of learning to use Procmail. This difficulty is often attributed to recipes matching messages by using regular expressions which are used to specify qualifications for string matching. However, regular expressions are not very difficult to construct and even less difficult to understand when read. Additionally, the consistency of the way Procmail recipes are written, regardless of regular expressions, makes it easy to learn by example. To see example Procmail recipes, see Mail_Servers.adoc#s3-email-procmail-recipes-examples.

Procmail recipes take the following form:

:0 flags : lockfile-name
*  condition_1_special-condition-character condition_1_regular_expression
*  condition_2_special-condition-character condition-2_regular_expression
*  condition_N_special-condition-character condition-N_regular_expression
        special-action-character
        action-to-perform

The first two characters in a Procmail recipe are a colon and a zero. Various flags can be placed after the zero to control how Procmail processes the recipe. A colon after the flags section specifies that a lockfile is created for this message. If a lockfile is created, the name can be specified by replacing lockfile-name.

A recipe can contain several conditions to match against the message. If it has no conditions, every message matches the recipe. Regular expressions are placed in some conditions to facilitate message matching. If multiple conditions are used, they must all match for the action to be performed. Conditions are checked based on the flags set in the recipe’s first line. Optional special characters placed after the asterisk character (*) can further control the condition.

The action-to-perform argument specifies the action taken when the message matches one of the conditions. There can only be one action per recipe. In many cases, the name of a mailbox is used here to direct matching messages into that file, effectively sorting the email. Special action characters may also be used before the action is specified. See Mail_Servers.adoc#s3-email-procmail-recipes-special for more information.

Delivering vs. Non-Delivering Recipes

The action used if the recipe matches a particular message determines whether it is considered a delivering or non-delivering recipe. A delivering recipe contains an action that writes the message to a file, sends the message to another program, or forwards the message to another email address. A non-delivering recipe covers any other actions, such as a nesting block. A nesting block is a set of actions, contained in braces { }, that are performed on messages which match the recipe’s conditions. Nesting blocks can be nested inside one another, providing greater control for identifying and performing actions on messages.

When messages match a delivering recipe, Procmail performs the specified action and stops comparing the message against any other recipes. Messages that match non-delivering recipes continue to be compared against other recipes.

Flags Flags are essential to

determine how or if a recipe’s conditions are compared to a message. The egrep utility is used internally for matching of the conditions. The following flags are commonly used:

  • A — Specifies that this recipe is only used if the previous recipe without an A or a flag also matched this message.

  • a — Specifies that this recipe is only used if the previous recipe with an A or a flag also matched this message and was successfully completed.

  • B — Parses the body of the message and looks for matching conditions.

  • b — Uses the body in any resulting action, such as writing the message to a file or forwarding it. This is the default behavior.

  • c — Generates a carbon copy of the email. This is useful with delivering recipes, since the required action can be performed on the message and a copy of the message can continue being processed in the rc files.

  • D — Makes the egrep comparison case-sensitive. By default, the comparison process is not case-sensitive.

  • E — While similar to the A flag, the conditions in the recipe are only compared to the message if the immediately preceding recipe without an E flag did not match. This is comparable to an else action.

  • e — The recipe is compared to the message only if the action specified in the immediately preceding recipe fails.

  • f — Uses the pipe as a filter.

  • H — Parses the header of the message and looks for matching conditions. This is the default behavior.

  • h — Uses the header in a resulting action. This is the default behavior.

  • w — Tells Procmail to wait for the specified filter or program to finish, and reports whether or not it was successful before considering the message filtered.

  • W — Is identical to w except that "Program failure" messages are suppressed.

For a detailed list of additional flags, see the procmailrc man page.

Specifying a Local Lockfile indexterm:[Procmail,recipes,local

lockfiles] Lockfiles are very useful with Procmail to ensure that more than one process does not try to alter a message simultaneously. Specify a local lockfile by placing a colon (:) after any flags on a recipe’s first line. This creates a local lockfile based on the destination file name plus whatever has been set in the LOCKEXT global environment variable.

Alternatively, specify the name of the local lockfile to be used with this recipe after the colon.

Special Conditions and Actions indexterm:[Procmail,recipes,special

conditions] Special characters used before Procmail recipe conditions and actions change the way they are interpreted.

The following characters may be used after the asterisk character (*) at the beginning of a recipe’s condition line:

  • ! — In the condition line, this character inverts the condition, causing a match to occur only if the condition does not match the message.

  • < — Checks if the message is under a specified number of bytes.

  • > — Checks if the message is over a specified number of bytes.

The following characters are used to perform special actions:

  • ! — In the action line, this character tells Procmail to forward the message to the specified email addresses.

  • $ — Refers to a variable set earlier in the rc file. This is often used to set a common mailbox that is referred to by various recipes.

  • | — Starts a specified program to process the message.

  • { and } — Constructs a nesting block, used to contain additional recipes to apply to matching messages.

If no special character is used at the beginning of the action line, Procmail assumes that the action line is specifying the mailbox in which to write the message.

Recipe Examples Procmail is an

extremely flexible program, but as a result of this flexibility, composing Procmail recipes from scratch can be difficult for new users.

The best way to develop the skills to build Procmail recipe conditions stems from a strong understanding of regular expressions combined with looking at many examples built by others. A thorough explanation of regular expressions is beyond the scope of this section. The structure of Procmail recipes and useful sample Procmail recipes can be found at various places on the Internet. The proper use and adaptation of regular expressions can be derived by viewing these recipe examples. In addition, introductory information about basic regular expression rules can be found in the grep(1) man page.

The following simple examples demonstrate the basic structure of Procmail recipes and can provide the foundation for more intricate constructions.

A basic recipe may not even contain conditions, as is illustrated in the following example:

:0:
new-mail.spool

The first line specifies that a local lockfile is to be created but does not specify a name, so Procmail uses the destination file name and appends the value specified in the LOCKEXT environment variable. No condition is specified, so every message matches this recipe and is placed in the single spool file called new-mail.spool, located within the directory specified by the MAILDIR environment variable. An MUA can then view messages in this file.

A basic recipe, such as this, can be placed at the end of all rc files to direct messages to a default location.

The following example matched messages from a specific email address and throws them away.

:0
* ^From: spammer@domain.com
/dev/null

With this example, any messages sent by spammer@domain.com are sent to the /dev/null device, deleting them.

Sending messages to /dev/null

Be certain that rules are working as intended before sending messages to /dev/null for permanent deletion. If a recipe inadvertently catches unintended messages, and those messages disappear, it becomes difficult to troubleshoot the rule.

A better solution is to point the recipe’s action to a special mailbox, which can be checked from time to time to look for false positives. Once satisfied that no messages are accidentally being matched, delete the mailbox and direct the action to send the messages to /dev/null.

The following recipe grabs email sent from a particular mailing list and places it in a specified folder.

:0:
* ^(From|Cc|To).*tux-lug
tuxlug

Any messages sent from the tux-lug@domain.com mailing list are placed in the tuxlug mailbox automatically for the MUA. Note that the condition in this example matches the message if it has the mailing list’s email address on the From, Cc, or To lines.

Consult the many Procmail online resources available in Mail_Servers.adoc#s1-email-additional-resources for more detailed and powerful recipes.

Spam Filters

Because it is called by Sendmail, Postfix, and Fetchmail upon receiving new emails, Procmail can be used as a powerful tool for combating spam.

This is particularly true when Procmail is used in conjunction with SpamAssassin. When used together, these two applications can quickly identify spam emails, and sort or destroy them.

SpamAssassin uses header analysis, text analysis, blacklists, a spam-tracking database, and self-learning Bayesian spam analysis to quickly and accurately identify and tag spam.

Installing the spamassassin package

In order to use SpamAssassin, first ensure the spamassassin package is installed on your system by running, as root:

~]# dnf install spamassassin

For more information on installing packages with DNF, see Installing Packages.

The easiest way for a local user to use SpamAssassin is to place the following line near the top of the ~/.procmailrc file:

INCLUDERC=/etc/mail/spamassassin/spamassassin-default.rc

The /etc/mail/spamassassin/spamassassin-default.rc contains a simple Procmail rule that activates SpamAssassin for all incoming email. If an email is determined to be spam, it is tagged in the header as such and the title is prepended with the following pattern:

*****SPAM*****

The message body of the email is also prepended with a running tally of what elements caused it to be diagnosed as spam.

To file email tagged as spam, a rule similar to the following can be used:

:0 Hw * ^X-Spam-Status: Yes spam

This rule files all email tagged in the header as spam into a mailbox called spam.

Since SpamAssassin is a Perl script, it may be necessary on busy servers to use the binary SpamAssassin daemon (spamd) and the client application (spamc). Configuring SpamAssassin this way, however, requires root access to the host.

To start the spamd daemon, type the following command:

~]# systemctl start spamassassin.service

To start the SpamAssassin daemon when the system is booted, run:

systemctl enable spamassassin.service

See Services and Daemons for more information on how to configure services in Fedora.

To configure Procmail to use the SpamAssassin client application instead of the Perl script, place the following line near the top of the ~/.procmailrc file. For a system-wide configuration, place it in /etc/procmailrc:

INCLUDERC=/etc/mail/spamassassin/spamassassin-spamc.rc

Mail User Agents

Fedora offers a variety of email programs, both, graphical email client programs, such as Evolution, and text-based email programs such as mutt.

The remainder of this section focuses on securing communication between a client and a server.

Securing Communication

Popular MUAs included with Fedora, such as Evolution and Mutt offer SSL-encrypted email sessions. Like any other service that flows over a network unencrypted, important email information, such as user names, passwords, and entire messages, may be intercepted and viewed by users on the network. Additionally, since the standard POP and IMAP protocols pass authentication information unencrypted, it is possible for an attacker to gain access to user accounts by collecting user names and passwords as they are passed over the network.

Secure Email Clients Most Linux

MUAs designed to check email on remote servers support SSL encryption. To use SSL when retrieving email, it must be enabled on both the email client and the server.

SSL is easy to enable on the client-side, often done with the click of a button in the MUA’s configuration window or via an option in the MUA’s configuration file. Secure IMAP and POP have known port numbers (993 and 995, respectively) that the MUA uses to authenticate and download messages.

Securing Email Client Communications

Offering SSL encryption to IMAP and POP users on the email server is a simple matter.

First, create an SSL certificate. This can be done in two ways: by applying to a Certificate Authority (CA) for an SSL certificate or by creating a self-signed certificate.

Avoid using self-signed certificates

Self-signed certificates should be used for testing purposes only. Any server used in a production environment should use an SSL certificate signed by a CA.

To create a self-signed SSL certificate for IMAP or POP, change to the /etc/pki/dovecot/ directory, edit the certificate parameters in the /etc/pki/dovecot/dovecot-openssl.cnf configuration file as you prefer, and type the following commands, as root:

dovecot]# rm -f certs/dovecot.pem private/dovecot.pem
dovecot]# /usr/libexec/dovecot/mkcert.sh

Once finished, make sure you have the following configurations in your /etc/dovecot/conf.d/10-ssl.conf file:

ssl_cert = </etc/pki/dovecot/certs/dovecot.pem
ssl_key = </etc/pki/dovecot/private/dovecot.pem

Issue the following command to restart the dovecot daemon:

~]# systemctl restart dovecot

Alternatively, the stunnel command can be used as an encryption wrapper around the standard, non-secure connections to IMAP or POP services.

The stunnel utility uses external OpenSSL libraries included with Fedora to provide strong cryptography and to protect the network connections. It is recommended to apply to a CA to obtain an SSL certificate, but it is also possible to create a self-signed certificate.

Installing the stunnel package

In order to use stunnel, first ensure the stunnel package is installed on your system by running, as root:

~]# dnf install stunnel

For more information on installing packages with DNF, see Installing Packages.

To create a self-signed SSL certificate, change to the /etc/pki/tls/certs/ directory, and type the following command:

certs]# make stunnel.pem

Answer all of the questions to complete the process.

Once the certificate is generated, create an stunnel configuration file, for example /etc/stunnel/mail.conf, with the following content:

cert = /etc/pki/tls/certs/stunnel.pem

[pop3s]
accept  = 995
connect = 110

[imaps]
accept  = 993
connect = 143

Once you start stunnel with the created configuration file using the stunnel /etc/stunnel/mail.conf command, it will be possible to use an IMAP or a POP email client and connect to the email server using SSL encryption.

For more information on stunnel, see the stunnel(8) man page or the documents in the /usr/share/doc/stunnel/ directory.

Additional Resources

The following is a list of additional documentation about email applications.

Installed Documentation

  • Information on configuring Sendmail is included with the sendmail and sendmail-cf packages.

    • /usr/share/sendmail-cf/README — Contains information on the m4 macro processor, file locations for Sendmail, supported mailers, how to access enhanced features, and more.

      In addition, the sendmail and aliases man pages contain helpful information covering various Sendmail options and the proper configuration of the Sendmail /etc/mail/aliases file.

  • /usr/share/doc/postfix/ — Contains a large amount of information on how to configure Postfix.

  • /usr/share/doc/fetchmail/ — Contains a full list of Fetchmail features in the FEATURES file and an introductory FAQ document.

  • /usr/share/doc/procmail/ — Contains a README file that provides an overview of Procmail, a FEATURES file that explores every program feature, and an FAQ file with answers to many common configuration questions.

    When learning how Procmail works and creating new recipes, the following Procmail man pages are invaluable:

    • procmail — Provides an overview of how Procmail works and the steps involved with filtering email.

    • procmailrc — Explains the rc file format used to construct recipes.

    • procmailex — Gives a number of useful, real-world examples of Procmail recipes.

    • procmailsc — Explains the weighted scoring technique used by Procmail to match a particular recipe to a message.

    • /usr/share/doc/spamassassin/ — Contains a large amount of information pertaining to SpamAssassin.

Useful Websites

  • Sendmail Milters: A Guide for Fighting Spam by Bryan Costales and Marcia Flynt; Addison-Wesley — A good Sendmail guide that can help you customize your mail filters.

  • Sendmail by Bryan Costales with Eric Allman et al.; O’Reilly & Associates — A good Sendmail reference written with the assistance of the original creator of Delivermail and Sendmail.

  • Removing the Spam: Email Processing and Filtering by Geoff Mulligan; Addison-Wesley Publishing Company — A volume that looks at various methods used by email administrators using established tools, such as Sendmail and Procmail, to manage spam problems.

  • Internet Email Protocols: A Developer’s Guide by Kevin Johnson; Addison-Wesley Publishing Company — Provides a very thorough review of major email protocols and the security they provide.

  • Managing IMAP by Dianna Mullet and Kevin Mullet; O’Reilly & Associates — Details the steps required to configure an IMAP server.