One place for hosting & domains

      Reporting

      Como Configurar MTA-STS e TLS Reporting para o seu Domínio Usando o Apache no Ubuntu 18.04


      O autor escolheu a Electronic Frontier Foundation Inc para receber uma doação como parte do programa Write for DOnations.

      Introdução

      O Mail Transport Agent Strict Transport Security (MTA-STS) é um novo padrão da Internet que lhe permite ativar o force-TLS estrito para emails enviados entre provedores de e-mail suportados. Ele é similar ao HTTP Strict Transport Security (HSTS), onde uma política force-TLS é definida e armazenada em cache por um período especificado, reduzindo o risco de ataques do tipo man-in-the-middle ou de downgrade.

      O MTA-STS é complementado pelo SMTP TLS Reporting (TLSRPT), que fornece informações sobre quais e-mails são entregues com sucesso por TLS e quais não. O TLSRPT é semelhante ao DMARC reporting, mas para TLS.

      O principal motivo para implementar o MTA-STS para o seu domínio é garantir que o e-mail confidencial enviado a você seja transmitido com segurança pelo TLS. Outros métodos para incentivar o TLS para comunicações por e-mail, como o STARTTLS, ainda são suscetíveis a ataques do tipo man-in-the-middle, pois a conexão inicial não é criptografada. O MTA-STS ajuda a garantir que, uma vez estabelecida pelo menos uma conexão segura, o TLS será usado por padrão a partir de então, o que reduz bastante o risco desses ataques.

      Um exemplo de caso de uso para o MTA-STS e o TLS Reporting é ajudar a criar um sistema seguro de atendimento ao cliente para o seu negócio. Os clientes podem enviar tíquetes de suporte por e-mail que contêm informações pessoais confidenciais, que precisam de uma conexão TLS segura. O MTA-STS ajuda a garantir a segurança da conexão, e o TLSRPT fornece relatórios diários identificando todos os e-mails que não foram enviados com segurança — fornecendo informações cruciais sobre quaisquer ataques em andamento ou anteriores ao seu sistema de e-mail.

      Neste tutorial, você aprenderá como configurar o MTA-STS e o TLSRPT para o seu nome de domínio e depois interpretar o seu primeiro relatório TLS. Embora este tutorial cubra as etapas para o uso do Apache no Ubuntu 18.04 com um certificado Let’s Encrypt, a configuração do MTA-STS/TLSRPT também funcionará em alternativas, como o Nginx no Debian.

      Pré-requisitos

      Antes de começar este guia, você precisará de:

      Depois de estar com tudo isso pronto, efetue login no servidor como usuário não-root para começar.

      Nota: Depois de concluir as etapas de implementação do MTA-STS e do TLSRPT, talvez você precise esperar até 24 horas para receber seu primeiro relatório TLS. Isso ocorre porque a maioria dos provedores de e-mail envia relatórios uma vez por dia. Você pode retomar o tutorial a partir do Passo 5 depois de receber seu primeiro relatório.

      Passo 1 — Criando um Arquivo de Política MTA-STS

      O MTA-STS é ativado e configurado usando um arquivo de configuração de texto sem formatação que você hospeda no seu site. Os servidores de e-mail suportados se conectarão automaticamente ao seu site para buscar o arquivo, o que faz com que o MTA-STS seja ativado. Nesta primeira etapa, você entenderá as opções disponíveis para esse arquivo e escolherá as mais adequadas para ele.

      Primeiro, abra um novo arquivo de texto em seu diretório home para que você tenha um lugar para anotar a sua configuração desejada:

      Vamos examinar primeiramente um exemplo e, em seguida, você escreverá seu próprio arquivo de configuração.

      A seguir, é apresentado um exemplo de um arquivo de configuração do MTA-STS:

      Arquivo de Exemplo de Configuração MTA-STS

      version: STSv1
      mode: enforce
      mx: mail1.seu-domínio
      mx: mail2.seu-domínio
      max_age: 604800
      

      Este arquivo de configuração de exemplo especifica que todos os emails entregues a mail1.seu-domínio e mail2.seu-domínio de provedores suportados devem ser entregues por uma conexão TLS válida. Se uma conexão TLS válida não puder ser estabelecida com o seu servidor de correio (por exemplo, se o certificado expirou ou é autoassinado), o email não será entregue.

      Isso tornará muito mais desafiador para um invasor interceptar e bisbilhotar/modificar seu e-mail em uma situação como um ataque man-in-the-middle. Isso ocorre porque o MTA-STS ativado corretamente permite que o e-mail seja transmitido apenas por uma conexão TLS válida, o que requer um certificado TLS válido. Seria difícil para um invasor adquirir esse certificado, pois isso geralmente requer acesso privilegiado ao seu nome de domínio e/ou site.

      Conforme mostrado no exemplo anterior neste passo, o arquivo de configuração consiste em vários pares de chave/valor:

      • version:

        • Propósito: Para especificar a versão da especificação MTA-STS a ser usada.
        • Valores Aceitos: Atualmente, o único valor aceito é STSv1.
        • Exemplo: version: STSv1
      • mode:

        • Propósito: Especificar em qual modo o MTA-STS deve ser ativado.
        • Valores Aceitos:
          • enforce: Forçar todos os emails de fornecedores suportados a usar TLS válido.
          • testing: Modo somente de relatório. O e-mail não será bloqueado, mas os relatórios TLSRPT ainda serão enviados.
          • none: Desativar MTA-STS.
        • Exemplo: mode: enforce
      • mx:

        • Propósito: Para especificar quais servidores de e-mail têm permissão para manipular e-mails do seu domínio. Isso deve corresponder aos servidores especificados em seus registros mx.
        • Valores Aceitos: Nome de domínio totalmente qualificado de um servidor de e-mail ou um host curinga. Vários valores mx: devem ser usados para especificar vários servidores de correio.
        • Exemplo: mx: mail1.seu-domínio, mx: mail2.seu-domínio, mx: *.example.org
      • max_age:

        • Propósito: Para especificar a duração máxima da política MTA-STS, em segundos.
        • Valores Aceitos: Qualquer número inteiro positivo até 31557600.
        • Exemplo: max_age: 604800 (1 semana)

      Você também pode visualizar a especificação oficial para os pares de chave/valor na Seção 3.2 do RFC do MTA-STS.

      Atenção: A ativação do MTA-STS no modo enforce pode inesperadamente causar alguns e-mails a não serem entregues a você. Em vez disso, é recomendável usar o mode: testing e um valor baixo de max_age: no início, para garantir que tudo esteja funcionando corretamente antes de ativar o MTA-STS completamente.

      Usando o arquivo de exemplo anterior, bem como os exemplos anteriores de pares de chave/valor, escreva o arquivo de política MTA-STS desejado e salve-o no arquivo que você criou no início da etapa.

      O arquivo de exemplo a seguir é ideal para testar o MTA-STS, pois não fará com que nenhum e-mail seja bloqueado inesperadamente, e tem um max_age de apenas 1 dia, o que significa que se você decidir desativá-lo, a configuração expirará rapidamente. Observe que alguns provedores de e-mail somente enviarão relatórios TLSRPT se o max_age for maior que 1 dia, razão pela qual 86401 segundos é uma boa opção (1 dia e 1 segundo).

      Example Test MTA-STS Configuration File

      version: STSv1
      mode: testing
      mx: mail1.seu-domínio
      mx: mail2.seu-domínio
      max_age: 86401
      

      Neste passo, você criou o arquivo de configuração MTA-STS desejado e o salvou no seu diretório home. No próximo passo, você configurará um servidor web Apache para servir o arquivo no formato correto.

      Passo 2 — Configurando o Apache para Servir seu Arquivo de Políticas do MTA-STS

      Neste passo, você irá configurar um virtual host no Apache para servir o seu arquivo de configuração do MTA-STS e adicionará um registro DNS para permitir que o site seja acessado a partir de um subdomínio.

      Para que seu arquivo de configuração MTA-STS seja descoberto automaticamente pelos servidores de correio, ele deve ser exibido exatamente no caminho certo: https://mta-sts.seu-domínio/.well-known/mta-sts.txt. Você deve usar o subdomínio mta-sts sobre HTTPS e o caminho /.well-known/mta-sts.txt, caso contrário sua configuração não funcionará.

      Isso pode ser conseguido com a criação de um novo virtual host no Apache para o subdomínio mta-sts, que servirá o arquivo de políticas do MTA-STS. Este passo baseia-se na configuração básica que você definiu no passo de pré-requisito Como Instalar o Servidor Web Apache no Ubuntu 18.04.

      Primeiro, crie um diretório para o seu virtual host:

      • sudo mkdir /var/www/mta-sts

      Se você estiver hospedando vários domínios diferentes no seu servidor web, é recomendável usar um virtual host MTA-STS diferente para cada um, por exemplo, /var/www/mta-sts-site1 and /var/www/mta-sts-site2

      Em seguida, você precisa criar o diretório .well-known, que é onde seu arquivo de configuração do MTA-STS será armazenado. .well-known é um diretório padronizado para arquivos ‘well-known’, como arquivos de validação de certificado TLS, security.txt, entre outros.

      • sudo mkdir /var/www/mta-sts/.well-known

      Agora você pode mover o arquivo de políticas MTA-STS que você criou no Passo 1 para o diretório do servidor web que você acabou de criar:

      • sudo mv ~/mta-sts.txt /var/www/mta-sts/.well-known/mta-sts.txt

      Você pode verificar se o arquivo foi copiado corretamente, se desejar:

      • cat /var/www/mta-sts/.well-known/mta-sts.txt

      Isso exibirá o conteúdo do arquivo que você criou no Passo 1.

      Para que o Apache sirva o arquivo, você precisará configurar o novo virtual host e ativá-lo. O MTA-STS funciona apenas em HTTPS, portanto você usará a porta 443 (HTTPS) exclusivamente, em vez de usar também a porta 80 (HTTP).

      Primeiro, crie um novo arquivo de configuração para o virtual host:

      • sudo nano /etc/apache2/sites-available/mta-sts.conf

      Como no diretório do virtual host, se você estiver hospedando vários domínios diferentes no mesmo servidor web, é recomendável usar um nome de virtual host diferente para cada um.

      Em seguida, copie a seguinte configuração de exemplo no arquivo e preencha as variáveis onde necessário:

      ~/etc/apache2/sites-available/mta-sts.conf

      <IfModule mod_ssl.c>
      <VirtualHost endereço-ipv4-do-seu-servidor:443 [endereço-ipv6-do-seu-servidor]:443>
          ServerName mta-sts.seu-domínio
          DocumentRoot /var/www/mta-sts
      
          ErrorDocument 403 "403 Forbidden - This site is used to specify the MTA-STS policy for this domain, please see '/.well-known/mta-sts.txt'. If you were not expecting to see this, please use <a href="https://seu-domínio" rel="noopener">https://seu-domínio</a> instead."
      
          RewriteEngine On
          RewriteOptions IgnoreInherit
          RewriteRule !^/.well-known/mta-sts.txt - [L,R=403]
      
          SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
          SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
          Include /etc/letsencrypt/options-ssl-apache.conf
      </VirtualHost>
      </IfModule>
      

      Esta configuração criará o virtual host mta-sts, que será servido em mta-sts.seu-domínio. Ele também redirecionará todas as solicitações, exceto aquelas para o próprio arquivo mta-sts.txt, para uma página de erro 403 Forbidden personalizada, com uma explicação amigável, falando para que serve o site do subdomínio. Isso é para ajudar a garantir que os visitantes que encontrarem acidentalmente seu site MTA-STS não fiquem confusos.

      Atualmente, um certificado TLS autoassinado é utilizado. Isso não é o ideal, pois é necessário um certificado totalmente válido/confiável para o MTA-STS funcionar corretamente. No Passo 3, você adquirirá um certificado TLS usando o Let’s Encrypt.

      Em seguida, verifique se os módulos necessários do Apache estão ativados:

      Depois disso, ative o novo virtual host:

      Em seguida, execute uma verificação de sintaxe dos arquivos de configuração do Apache, para garantir que não haja erros inesperados:

      • sudo apachectl configtest

      Quando o teste passar sem erros, você pode reiniciar o Apache para ativar completamente o novo virtual host:

      • sudo service apache2 restart

      Agora que o virtual host do Apache foi instalado e configurado, é necessário criar o(s) registro(s) de DNS necessário(s) para permitir que ele seja acessado usando o nome de domínio totalmente qualificado mta-sts.seu-domínio.

      A maneira como isso é feito depende do provedor de hospedagem DNS que você usa. No entanto, se você usa a DigitalOcean como seu provedor de DNS, simplesmente navegue até o seu projeto e depois clique em seu domínio.

      Por fim, adicione os registros DNS necessários para o subdomínio mta-sts. Se o seu Droplet usa apenas IPv4, crie um registro A para mta-sts, apontando para endereço-ipv4-do-seu-servidor. Se você usa o IPv6 também, crie um registro AAAA apontando para endereço-ipv6-do-seu-servidor.

      A screenshot of the DigitalOcean DNS control panel, showing an example DNS record for mta-sts pointing to an IPv4 address.

      Neste passo, você criou e configurou um novo virtual host no Apache para o subdomínio MTA-STS e adicionou os registros DNS necessários para permitir que ele seja acessado facilmente. No próximo passo, você adquirirá um certificado Let’s Encrypt confiável para o seu subdomínio MTA-STS.

      Passo 3 — Adquirindo um Certificado Let’s Encrypt para seu Subdomínio MTA-STS

      Neste passo, você adquirirá um certificado TLS da Let’s Encrypt, para permitir que seu site mta-sts.seu-domínio seja publicado corretamente por HTTPS.

      Para fazer isso, você usará o certbot, que você configurou como parte da etapa de pré-requisito Como proteger o Apache com o Let’s Encrypt no Ubuntu 18.04.

      Primeiramente, execute o certbot para emitir um certificado para o subdomínio mta-sts usando o método de verificação de plugin do Apache:

      • sudo certbot --apache -d mta-sts.seu-domínio

      Isso emitirá automaticamente um certificado confiável e o instalará no servidor web Apache. Quando o assistente do Certbot perguntar sobre a configuração de um redirecionamento HTTP -> HTTPS, selecione 'No’, pois isso não é necessário para o MTA-STS.

      Para finalizar, teste seu novo virtual host para garantir que ele esteja funcionando corretamente. Use um navegador para visitar https://mta-sts.seu-domínio/.well-known/mta-sts.txt ou use uma ferramenta de linha de comando como o curl:

      • curl https://mta-sts.seu-domínio/.well-known/mta-sts.txt

      Isso mostrará o arquivo de política MTA-STS que você criou na Etapa 1:

      Output

      version: STSv1 mode: testing mx: mail1.seu-domínio mx: mail2.seu-domínio max_age: 86401

      Se ocorrer um erro, verifique se a configuração do virtual host do Passo 2 está correta e se você adicionou um registro DNS para o subdomínio mta-sts.

      Neste passo, você emitiu um certificado Let’s Encrypt TLS para o subdomínio mta-sts e testou se ele está funcionando. Em seguida, você definirá alguns registros TXT no DNS para ativar completamente o MTA-STS e o TLSRPT.

      Passo 4 — Configurando os Registros DNS Necessários para Ativar o MTA-STS e o TLSRPT

      Neste passo, você configurará dois registros TXT no DNS, que habilitarão totalmente a diretiva MTA-STS que você já criou e também habilitarão o TLS Reporting (TLSRPT).

      Esses registros DNS podem ser configurados usando qualquer provedor de hospedagem DNS, mas neste exemplo, a DigitalOcean é utilizada como provedor.

      Primeiro, faça logon no painel de controle da DigitalOcean e navegue até o seu projeto; depois dê um clique em seu domínio.

      Você precisa então, adicionar os dois registros TXT a seguir:

      _mta-sts.seu-domínio IN TXT "v=STSv1; id=id-value"
      _smtp._tls.seu-domínio IN TXT "v=TLSRPTv1; rua=reporting-address"
      

      id-value é uma string usada para identificar a versão da sua política MTA-STS em vigor. Se você atualizar sua política, precisará também atualizar o valor do id para garantir que a nova versão seja detectada pelos provedores de correio. Recomenda-se usar o carimbo de data atual como o id, por exemplo, 20190811231231 (23:12:31 em 11 de agosto de 2019).

      reporting-address é o endereço para onde seus relatórios TLS serão enviados. Pode ser um endereço de e-mail com o prefixo mailto: ou um URI web, por exemplo, para uma API que coleta relatórios. O endereço para o relatório não precisa ser um endereço no seu-domínio. Você pode usar um domínio completamente diferente, se desejar.

      Por exemplo, os dois registros de exemplo a seguir são válidos:

      _mta-sts.seu-domínio IN TXT "v=STSv1; id=20190811231231"
      _smtp._tls.seu-domínio IN TXT "v=TLSRPTv1; rua=mailto:tls-reports@seu-domínio"
      

      Ajuste as variáveis conforme necessário e defina esses registros TXT de DNS em seu painel de controle da DigitalOcean (ou qualquer provedor de DNS que você esteja usando):

      A screenshot of the DigitalOcean control panel, showing the _mta-sts DNS TXT record being set.

      A screenshot of the DigitalOcean control panel, showing the _smtp._tls DNS TXT record being set.

      Depois que esses registros DNS forem definidos e propagados, o MTA-STS será ativado com a política que você criou no Passo 1 e começará a receber relatórios TLSRPT no endereço que você especificou.

      Neste passo, você configurou os registros DNS necessários para que o MTA-STS seja ativado. Em seguida, você receberá e interpretará seu primeiro relatório TLSRPT.

      Passo 5 — Interpretando seu Primeiro Relatório TLSRPT

      Agora que você ativou o MTA-STS e o TLSRPT (TLS Reporting) para o seu domínio, você começará a receber relatórios de provedores de e-mail suportados. Esses relatórios mostrarão o número de e-mails que foram ou não foram entregues com êxito pelo TLS e os motivos dos erros.

      Diferentes provedores de e-mail enviam seus relatórios em momentos diferentes; por exemplo, o Google Mail envia seus relatórios diariamente por volta das 10:00 UTC.

      Dependendo de como você configurou o registro DNS TLSRPT no Passo 5, você receberá seus relatórios por e-mail ou por uma API web. Este tutorial se concentra no método de e-mail, pois essa é a configuração mais comum.

      Se você acabou de concluir o restante deste tutorial, aguarde até receber seu primeiro relatório e poderá continuar.

      Seu relatório diário do TLSRPT por e-mail geralmente possui uma linha de assunto semelhante à seguinte:

      Report Domain: seu-domínio Submitter: google.com Report-ID: <2019.08.10T00.00.00Z+seu-domínio@google.com>
      

      Este e-mail terá um anexo no formato .gz, que é um arquivo compactado Gzip, com um nome de arquivo semelhante ao seguinte:

      google.com!seu-domínio!1565222400!1565308799!001.json.gz
      

      Para o restante deste tutorial, esse arquivo será chamado de report.json.gz.

      Salve esse arquivo na sua máquina local e extraia-o usando a ferramenta que você preferir.

      Se você estiver usando um sistema Linux baseado no Debian, poderá executar o comando gzip -d para descompactar o arquivo:

      Isso resultará em um arquivo JSON chamado report.json.

      Em seguida, você pode visualizar o relatório diretamente como a sequência JSON bruta ou usar seu formatador JSON favorito para colocá-lo em um formato mais legível. Neste exemplo, o jq será usado, mas você também pode usar o json.tool do Python, se desejar.

      Nota: Se você não possui o jq instalado, você pode instalá-lo utilizando apt install jq. Ou, para outros sistemas operacionais, use as instruções de instalação correspondentes do jq.

      Isso produzirá algo semelhante ao seguinte:

      Prettified report.json

      { "organization-name": "Google Inc.", "date-range": { "start-datetime": "2019-08-10T00:00:00Z", "end-datetime": "2019-08-10T23:59:59Z" }, "contact-info": "[email protected]", "report-id": "2019-08-10T00:00:00Z_seu-domínio", "policies": [ { "policy": { "policy-type": "sts", "policy-string": [ "version: STSv1", "mode: testing", "mx: mail1.seu-domínio", "mx: mail2.seu-domínio", "max_age: 86401" ], "policy-domain": "seu-domínio" }, "summary": { "total-successful-session-count": 230, "total-failure-session-count": 0 } } ] }

      O relatório mostra o provedor que gerou o relatório e o período do relatório, bem como a política MTA-STS que foi aplicada. No entanto, a seção principal em que você estará interessado é a summary, especificamente as contagens de sessões com êxito e com falha.

      Este relatório de exemplo mostra que 230 e-mails foram entregues com êxito por TLS do provedor de e-mail que gerou o relatório e 0 entregas de e-mail falharam ao estabelecer uma conexão TLS adequada.

      Caso haja uma falha — por exemplo, se um certificado TLS expirar ou houver um invasor na rede — o motivo da falha será documentado no relatório. Alguns exemplos de motivos de falha são:

      • starttls-not-supported: Se o servidor de e-mail de recebimento não suportar STARTTLS.
      • certificate-expired: Se um certificado expirou.
      • certificate-not-trusted: Se um certificado autoassinado ou outro certificado não confiável for usado.

      Neste passo final, você recebeu e interpretou seu primeiro relatório TLSRPT.

      Conclusão

      Neste artigo, você definiu e configurou o MTA-STS e o TLS Reporting para o seu domínio e interpretou o seu primeiro relatório TLSRPT.

      Depois que o MTA-STS estiver ativado e funcionando de maneira estável por um tempo, é recomendável ajustar a política, aumentando o valor de max_age e, eventualmente, alternando-a para o modo enforce quando você tiver certeza de que todos os emails de provedores suportados estão sendo entregue com sucesso por TLS.

      Por fim, se você quiser saber mais sobre as especificações MTA-STS e TLSRPT, poderá revisar as RFCs para os dois:



      Source link

      How To Configure MTA-STS and TLS Reporting for Your Domain Using Apache on Ubuntu 18.04


      The author selected Electronic Frontier Foundation Inc to receive a donation as part of the Write for DOnations program.

      Introduction

      Mail Transport Agent Strict Transport Security (MTA-STS) is a new internet standard that allows you to enable strict force-TLS for email sent between supported email providers. It is similar to HTTP Strict Transport Security (HSTS), where a force-TLS policy is set and then cached for a specified amount of time, reducing the risk of man-in-the-middle or downgrade attacks.

      MTA-STS is complemented by SMTP TLS Reporting (TLSRPT), which gives you insight into which emails are successfully delivered over TLS, and which aren’t. TLSRPT is similar to DMARC reporting, but for TLS.

      The primary reason for implementing MTA-STS for your domain is to ensure that confidential email that is sent to you is transmitted securely over TLS. Other methods for requiring TLS for email communications are still susceptible to man-in-the-middle attacks, as the initial connection is unencrypted. MTA-STS ensures that the initial incoming connection is using TLS by default, which greatly reduces the risk of these attacks.

      An example use case for MTA-STS and TLS Reporting is to help create a secure customer service email system for your business. Customers may send support tickets via email that contain confidential personal information, which needs a secure TLS connection. MTA-STS provides that secure connection, and TLSRPT will deliver daily reports identifying any emails that weren’t sent securely—giving crucial insight into any ongoing or previous attacks against your email system.

      In this tutorial, you will learn how to configure MTA-STS and TLSRPT for your domain name, and then interpret your first TLS Report. While this tutorial covers the steps for using Apache on Ubuntu 18.04 with a Let’s Encrypt certificate, the MTA-STS/TLSRPT configuration will also work on alternatives, such as Nginx on Debian.

      Prerequisites

      Before you begin this guide, you’ll need:

      Once you have these ready, log in to your server as your non-root user to begin.

      Note: Once you have completed the implementation steps for MTA-STS and TLSRPT, you may have to wait up to 24 hours to receive your first TLS Report. This is because most email providers send reports once per day. You may resume the tutorial from Step 5 once you’ve received your first report.

      Step 1 — Creating an MTA-STS Policy File

      MTA-STS is enabled and configured using a plain text configuration file that you host on your website. Supported mail servers will then automatically connect to your website to retrieve the file, which causes MTA-STS to be enabled. In this first step you’ll understand the available options for this file and choose the most appropriate for your file.

      Firstly, open a new text file in your home directory so that you have somewhere to write down your desired configuration:

      We will first go over an example, and then you will write your own configuration file.

      Following is an example of an MTA-STS configuration file:

      Example MTA-STS Configuration File

      version: STSv1
      mode: enforce
      mx: mail1.your-domain
      mx: mail2.your-domain
      max_age: 604800
      

      This example configuration file specifies that all email delivered to mail1.your-domain and mail2.your-domain from supported providers must be delivered over a valid TLS connection. If a valid TLS connection cannot be established with your mail server (for example, if the certificate has expired or is self-signed), the email will not be delivered.

      This will make it much more challenging for an attacker to intercept and snoop on/modify your email in a situation like a man-in-the-middle attack. This is because having MTA-STS enabled properly only allows email to be transmitted over a valid TLS connection, which requires a valid TLS certificate. It would be hard for an attacker to acquire such a certificate, as doing so usually requires privileged access to your domain name and/or website.

      As shown in the example earlier in this step, the configuration file consists of a number of key/value pairs:

      • version:

        • Purpose: To specify the version of the MTA-STS specification to use.
        • Accepted Values: Currently the only accepted value is STSv1.
        • Example: version: STSv1
      • mode:

        • Purpose: Specify which mode MTA-STS should be enabled in.
        • Accepted Values:
          • enforce: Force all incoming email from supported providers to use valid TLS.
          • testing: Report-only mode. email will not be blocked, but TLSRPT reports are still sent.
          • none: Disable MTA-STS.
        • Example: mode: enforce
      • mx:

        • Purpose: To specify which mail servers are allowed to handle email for your domain. This should match the servers specified in your mx records.
        • Accepted Values: Fully-qualified domain name of a mail server, or a wildcard host. Multiple mx: values must be used to specify multiple mail servers.
        • Example: mx: mail1.your-domain, mx: mail2.your-domain, mx: *.example.org
      • max_age:

        • Purpose: To specify the maximum lifetime of the MTA-STS policy, in seconds.
        • Accepted Values: Any positive integer up to 31557600.
        • Example: max_age: 604800 (1 week)

      You can also view the official specification for the key/value pairs in Section 3.2 of the MTA-STS RFC.

      Warning: Enabling MTA-STS in enforce mode could unexpectedly cause some email not to be delivered to you. Instead, it is recommended to use mode: testing and a low max_age: value at first, in order to ensure that everything is working correctly before turning on MTA-STS fully.

      Using the example file earlier in the step, as well as the preceding key/value pair examples, write your desired MTA-STS policy file and save it to the file that you created at the start of the step.

      The following example file is ideal for testing MTA-STS, as it will not cause any emails to be unexpectedly blocked, and has a max_age of only 1 day, meaning that if you decide to disable it, the configuration will expire quickly. Note that some email providers will only send TLSRPT reports if the max_age is greater than 1 day, which is why 86401 seconds is a good choice (1 day and 1 second).

      Example Test MTA-STS Configuration File

      version: STSv1
      mode: testing
      mx: mail1.your-domain
      mx: mail2.your-domain
      max_age: 86401
      

      In this step you created your desired MTA-STS configuration file and saved it to your home area. In the next step, you will configure an Apache web server to serve the file in the correct format.

      Step 2 — Configuring Apache to Serve Your MTA-STS Policy File

      In this step, you’ll configure an Apache virtual host to serve your MTA-STS configuration file, and then add a DNS record to allow the site to be accessed from a subdomain.

      In order for your MTA-STS configuration file to be automatically discovered by mail servers, it must be served at exactly the right path: https://mta-sts.your-domain/.well-known/mta-sts.txt. You must use the mta-sts subdomain over HTTPS and the /.well-known/mta-sts.txt path, otherwise your configuration will not work.

      This can be achieved by creating a new Apache virtual host for the mta-sts subdomain, which will serve the MTA-STS policy file. This step builds upon the base configuration that you’ll have set up in the prerequisite step How to Install the Apache Web Server on Ubuntu 18.04.

      Firstly, create a directory for your virtual host:

      • sudo mkdir /var/www/mta-sts

      If you’re hosting multiple different domains on your web server, it is recommended to use a different MTA-STS virtual host for each, for example /var/www/mta-sts-site1 and /var/www/mta-sts-site2.

      Next, you need to create the .well-known directory, which is where your MTA-STS configuration file will be stored. .well-known is a standardized directory for ‘well-known’ files, such as TLS certificate validation files, security.txt, and more.

      • sudo mkdir /var/www/mta-sts/.well-known

      Now you can move the MTA-STS policy file that you created in Step 1 into the web server directory that you just created:

      • sudo mv ~/mta-sts.txt /var/www/mta-sts/.well-known/mta-sts.txt

      You can check that the file was copied correctly if you wish:

      • cat /var/www/mta-sts/.well-known/mta-sts.txt

      This will output the contents of the file that you created in Step 1.

      In order for Apache to serve the file, you’ll need to configure the new virtual host and enable it. MTA-STS only works over HTTPS, so you’ll use port 443 (HTTPS) exclusively, rather than using port 80 (HTTP) as well.

      Firstly, create a new virtual host configuration file:

      • sudo nano /etc/apache2/sites-available/mta-sts.conf

      Like with the virtual host directory, if you are hosting multiple different domains on the same web server, it is recommended to use a different virtual host name for each.

      Then, copy the following sample configuration into the file, and populate the variables where required:

      ~/etc/apache2/sites-available/mta-sts.conf

      <IfModule mod_ssl.c>
      <VirtualHost your-server-ipv4-address:443 [your-server-ipv6-address]:443>
          ServerName mta-sts.your-domain
          DocumentRoot /var/www/mta-sts
      
          ErrorDocument 403 "403 Forbidden - This site is used to specify the MTA-STS policy for this domain, please see '/.well-known/mta-sts.txt'. If you were not expecting to see this, please use <a href="https://your-domain" rel="noopener">https://your-domain</a> instead."
      
          RewriteEngine On
          RewriteOptions IgnoreInherit
          RewriteRule !^/.well-known/mta-sts.txt - [L,R=403]
      
          SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
          SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
          Include /etc/letsencrypt/options-ssl-apache.conf
      </VirtualHost>
      </IfModule>
      

      This configuration will create the mta-sts virtual host, which will be served at mta-sts.your-domain. It will also redirect all requests, except for those to the mta-sts.txt file itself, to a custom 403 Forbidden error page, with a friendly explanation of what the subdomain site is for. This is to help ensure that any visitors who accidentally come across your MTA-STS site aren’t inadvertently confused.

      Currently, a self-signed TLS certificate is used. This is not ideal, as a fully valid/trusted certificate is required for MTA-STS to work correctly. In Step 3, you will acquire a TLS certificate using Let’s Encrypt.

      Next, ensure that the required Apache modules are enabled:

      After that, enable the new virtual host:

      Then, run a syntax check of the Apache configuration files, to ensure that there aren’t any unexpected errors:

      • sudo apachectl configtest

      When the test passes with no errors, you can restart Apache to fully enable the new virtual host:

      • sudo service apache2 restart

      Now that the Apache virtual host has been set up and configured, you need to create the required DNS record(s) to allow it to be accessed using the fully-qualified domain name mta-sts.your-domain.

      The way that this is done depends on the DNS hosting provider that you use. However, if you use DigitalOcean as your DNS provider, simply navigate to your project, followed by clicking on your domain.

      Finally, add the required DNS records for the mta-sts subdomain. If your Droplet only uses IPv4, create an A record for mta-sts, pointing to your-server-ipv4-address. If you use IPv6 as well, create an AAAA record pointing to your-server-ipv6-address.

      A screenshot of the DigitalOcean DNS control panel, showing an example DNS record for mta-sts pointing to an IPv4 address.

      In this step, you created and configured a new Apache virtual host for your MTA-STS subdomain, then added the required DNS record(s) to allow it to be accessed easily. In the next step, you will acquire a trusted Let’s Encrypt certificate for your MTA-STS subdomain.

      Step 3 — Acquiring a Let’s Encrypt Certificate for Your MTA-STS Subdomain

      In this step, you’ll acquire a TLS certificate from Let’s Encrypt, to allow your mta-sts.your-domain site to be served correctly over HTTPS.

      In order to do this, you’ll use certbot, which you set up as part of the prerequisite step How To Secure Apache with Let’s Encrypt on Ubuntu 18.04.

      Firstly, run certbot to issue a certificate for your mta-sts subdomain using the Apache plugin verification method:

      • sudo certbot --apache -d mta-sts.your-domain

      This will automatically issue a trusted certificate and install it on your Apache web server. When the Certbot wizard asks about configuring a HTTP -> HTTPS redirect, select 'No’, as this is not required for MTA-STS.

      To finish, test your new virtual host to ensure that it is working correctly. Use a web browser to visit https://mta-sts.your-domain/.well-known/mta-sts.txt, or use a command-line tool such as curl:

      • curl https://mta-sts.your-domain/.well-known/mta-sts.txt

      This will output the MTA-STS policy file that you created in Step 1:

      Output

      version: STSv1 mode: testing mx: mail1.your-domain mx: mail2.your-domain max_age: 86401

      If an error occurs, ensure that the virtual host configuration from Step 2 is correct, and that you have added a DNS record for the mta-sts subdomain.

      In this step, you issued a Let’s Encrypt TLS certificate for your mta-sts subdomain, and tested that it’s working. Next, you’ll set some DNS TXT records to fully enable MTA-STS and TLSRPT.

      Step 4 — Configuring the DNS Records Required to Enable MTA-STS and TLSRPT

      In this step, you’ll configure two DNS TXT records, which will fully enable the MTA-STS policy that you have already created, and also enable TLS Reporting (TLSRPT).

      These DNS records can be configured using any DNS hosting provider, but in this example, DigitalOcean is used as the provider.

      Firstly, log on to your DigitalOcean control panel and navigate to your project, followed by clicking on your domain.

      You then need to add the following two TXT records:

      _mta-sts.your-domain IN TXT "v=STSv1; id=id-value"
      _smtp._tls.your-domain IN TXT "v=TLSRPTv1; rua=reporting-address"
      

      id-value is a string used to identify the version of your MTA-STS policy in place. If you update your policy, you’ll need to also update the id value to ensure that the new version is detected by mail providers. It is recommended to use the current date stamp as the id, for example 20190811231231 (23:12:31 on 11th Aug 2019).

      reporting-address is the address where your TLS reports will be sent to. This can be either an email address prefixed with mailto:, or a web URI, for example for an API that collects reports. The reporting address doesn’t have to be an address on your-domain. You may use a completely different domain if you wish.

      For example, the following two sample records are both valid:

      _mta-sts.your-domain IN TXT "v=STSv1; id=20190811231231"
      _smtp._tls.your-domain IN TXT "v=TLSRPTv1; rua=mailto:tls-reports@your-domain"
      

      Adjust the variables as required, and set these DNS TXT records in your DigitalOcean control panel (or whichever DNS provider you’re using):

      A screenshot of the DigitalOcean control panel, showing the _mta-sts DNS TXT record being set.

      A screenshot of the DigitalOcean control panel, showing the _smtp._tls DNS TXT record being set.

      Once these DNS records have been set and have propagated, MTA-STS will be enabled with the policy that you created in Step 1, and will begin to receive TLSRPT reports at the address that you specified.

      In this step, you configured the DNS records required for MTA-STS to be enabled. Next, you will receive and then interpret your first TLSRPT report.

      Step 5 — Interpreting Your First TLSRPT Report

      Now that you’ve enabled MTA-STS and TLSRPT (TLS Reporting) for your domain, you will begin to receive reports from supported email providers. These reports will show the number of emails that were or were not successfully delivered over TLS, and the reasons for any errors.

      Different email providers send their reports at different times; for example, Google Mail sends their reports daily at around 10:00 UTC.

      Depending on how you configured the TLSRPT DNS record in Step 5, you will either receive your reports via email, or via a web API. This tutorial focuses on the email method, as that is the most common configuration.

      If you’ve just completed the rest of this tutorial, wait until you receive your first report, then you can resume.

      Your daily TLSRPT report via email will usually have a subject line similar to the following:

      Report Domain: your-domain Submitter: google.com Report-ID: <2019.08.10T00.00.00Z+your-domain@google.com>
      

      This email will have an attachment in .gz format, which is a Gzip compressed archive, with a file name similar to the following:

      google.com!your-domain!1565222400!1565308799!001.json.gz
      

      For the rest of this tutorial this file will be referred to as report.json.gz.

      Save this file to your local machine, and extract it using whichever tool you prefer.

      If you’re using a Debian-based Linux system, you will be able to run the gzip -d command to decompress the archive:

      This will result in a JSON file called report.json.

      Next, you can view the report either directly as the raw JSON string, or use your favorite JSON prettifier to put it into a more readable format. In this example, jq will be used, but you could also use Python’s json.tool if you wish.

      Note: If you don’t have jq installed, you can install it using apt install jq. Or, for other operating systems use the necessary installation instructions from jq.

      This will output something similar to the following:

      Prettified report.json

      { "organization-name": "Google Inc.", "date-range": { "start-datetime": "2019-08-10T00:00:00Z", "end-datetime": "2019-08-10T23:59:59Z" }, "contact-info": "[email protected]", "report-id": "2019-08-10T00:00:00Z_your-domain", "policies": [ { "policy": { "policy-type": "sts", "policy-string": [ "version: STSv1", "mode: testing", "mx: mail1.your-domain", "mx: mail2.your-domain", "max_age: 86401" ], "policy-domain": "your-domain" }, "summary": { "total-successful-session-count": 230, "total-failure-session-count": 0 } } ] }

      The report shows the provider that generated the report and the reporting period, as well as the MTA-STS policy that was applied. However, the main section that you’ll be interested in is summary, specifically the successful and failed session counts.

      This sample report shows that 230 emails were successfully delivered over TLS from the mail provider that generated the report, and 0 email deliveries failed to establish a proper TLS connection.

      In the event that there is a failure—for example, if a TLS certificate expires or there is an attacker on the network—the failure mode will be documented in the report. Some examples of failure modes are:

      • starttls-not-supported: If the receiving mail server doesn’t support STARTTLS.
      • certificate-expired: If a certificate has expired.
      • certificate-not-trusted: If a self-signed or other non-trusted certificate is used.

      In this final step, you received and then interpreted your first TLSRPT report.

      Conclusion

      In this article you set up and configured MTA-STS and TLS Reporting for your domain, and interpreted your first TLSRPT report.

      Once MTA-STS has been enabled and working stably for a while, it is recommended to adjust the policy, increasing the max_age value, and eventually switching it to enforce mode once you are sure that all email from supported providers is being delivered successfully over TLS.

      Finally, if you’d like to learn more about the MTA-STS and TLSRPT specifications, you can review the RFCs for both of them:



      Source link