Construyendo su propio servidor de correo con FreeBSD 11

Ejecutar su propio servidor de correo electrónico puede ser muy gratificante. Usted está a cargo de sus datos. También le permite una mayor flexibilidad con sus opciones de entrega. Sin embargo, hay algunos desafíos. Corre el riesgo de abrir su servidor a vulnerabilidades, así como de convertir su servidor en un posible retransmisor para que lo utilicen los spammers.

Con eso fuera del camino, pasemos a ejecutar nuestro propio servidor de correo.

Visión de conjunto

Hay tres piezas de software necesarias para instalar que no están incluidas en el sistema base de FreeBSD:

  • OpenSMTPd
  • Palomar
  • spam

OpenSMTPd es un agente de transferencia de correo (MTA) y un agente de entrega de correo (MDA). Esto significa que puede comunicarse con otros servidores de correo a través del SMTPprotocolo, y también maneja la entrega de correo a los buzones de los usuarios individuales. Configuraremos OpenSMTPd para que pueda comunicarse con servidores externos (filtrados a través de spam) y entregar correo a usuarios locales, así como entregar correo local de usuario a usuario.

Dovecot es una MDA que lee los buzones locales y los sirve a través de IMAP o POP3 a los usuarios. Utilizará los buzones de los usuarios locales para servir este contenido.

Spamd es un servicio de filtrado de correo. Podemos reenviar el correo a través de spam, y filtrará el correo en función de una variedad de listas negras, listas blancas y una lista gris.

La idea general para este servidor de correo requiere algunas rutas diferentes:

Outside world -> Firewall -> spamd -> OpenSMTPD -> User mail boxes
Outside world -> Firewall (spamd-whitelist) -> OpenSMTPD -> User mailboxes
Outside world -> Firewall (IMAP/POP3) -> Dovecot
Outside world -> Firewall (SMTPD submission)

Para este tutorial, utilizaremos la versión FreeBSD del PF de OpenBSD para nuestro firewall. También puede usar ipfw, donde la configuración es muy similar.

Nota: Vultr, de forma predeterminada, bloquea el puerto 25, que utilizan los servidores SMTP en todas partes. Si desea ejecutar un servidor de correo electrónico completamente funcional, tendrá que abrir ese puerto.

Configuración inicial

Primero, necesitamos instalar los programas requeridos.

Suponiendo que se está ejecutando como un usuario con la configuración de acceso sudo, podemos ejecutar los siguientes comandos. Variarán dependiendo de si está utilizando puertos o paquetes.

Paquetes (recomendado)

A menos que necesite una funcionalidad específica integrada en estas utilidades, se recomienda instalar a través de paquetes. Es más fácil, requiere menos tiempo y recursos del servidor, y proporciona una interfaz intuitiva y fácil de usar.

sudo pkg install opensmtpd dovecot spamd

Los siguientes makecomandos le darán muchas opciones de compilación, los valores predeterminados funcionarán bien. No los cambie a menos que sepa exactamente lo que está haciendo.

sudo portsnap fetch update   # or run portsnap fetch extract if using ports for the first time
cd /usr/ports/mail/opensmtpd  
make install  # Installs openSMTPd
make clean
cd /usr/ports/mail/dovecot
make install  # Installs dovecot
make clean
cd /usr/ports/mail/spamd
make install  # Installs spamd
make clean

Necesitaremos agregar las siguientes líneas a /etc/rc.conf:

pf_enable="YES"
pf_rules="/usr/local/etc/pf.conf"
pflog_enable="YES"
pflog_logfile="/var/log/pflog"

obspamd_enable="YES"
obspamd_flags="-v"
obspamlogd_enable="YES"

dovecot_enable="YES"

Configuración de cortafuegos

Para configurar PF, podemos crear nuestro /usr/local/etc/pf.conf:

## Set public interface ##
ext_if="vtnet0"

## set and drop IP ranges on the public interface ##
martians = "{ 127.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, \
          10.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24, \
          0.0.0.0/8, 240.0.0.0/4 }"

table <spamd> persist
table <spamd-white> persist

# Whitelisted webmail services
table <webmail> persist file "/usr/local/etc/pf.webmail.ip.conf"

## Skip loop back interface - Skip all PF processing on interface ##
set skip on lo

## Sets the interface for which PF should gather statistics such as bytes in/out and packets passed/blocked ##
set loginterface $ext_if

# Deal with attacks based on incorrect handling of packet fragments 
scrub in all


# Pass spamd whitelist
pass quick log on $ext_if inet proto tcp from <spamd-white> to $ext_if port smtp \
    -> 127.0.0.1 port 25
# Pass webmail servers
rdr pass quick log on $ext_if inet proto tcp from <gmail> to $ext_if port smtp \
    -> 127.0.0.1 port 25
# pass submission messages.
pass quick log on $ext_if inet proto tcp from any to $ext_if port submission modulate state
# Pass unknown mail to spamd
rdr pass log on $ext_if inet proto tcp from {!<spamd-white> <spamd>} to $ext_if port smtp \
    -> 127.0.0.1 port 8025 

## Blocking spoofed packets
antispoof quick for $ext_if

## Set default policy ##
block return in log all
block out all

# Drop all Non-Routable Addresses 
block drop in quick on $ext_if from $martians to any
block drop out quick on $ext_if from any to $martians

pass in inet proto tcp to $ext_if port ssh

# Allow Ping-Pong stuff. Be a good sysadmin 
pass inet proto icmp icmp-type echoreq

# Open up imap/pop3 support
pass quick on $ext_if proto tcp from any to any port {imap, imaps, pop3, pop3s} modulate state


# Allow outgoing traffic
pass out on $ext_if proto tcp from any to any modulate state
pass out on $ext_if proto udp from any to any keep state

Esta es una configuración PF que funciona. Es relativamente simple, pero también hay algunas peculiaridades que explicar.

En primer lugar, definimos nuestra $ext_ifvariable para que nuestro vtnet0dispositivo la use más adelante. También definimos direcciones IP no válidas que deberían descartarse en la interfaz externa.

We also define two tables, spamd and spamd-white - these two tables are created by spamd in it's default configuration. As well, we define a table named webmail which we will use to allow some major webmail providers through.

To view a table, you can use the command pfctl -t tablename -T show to list the elements in a table.

We set a few PF rules: skip processing on the local interface, enable statistics on the external interface and scrub incoming packets.

Next is one of the more important parts, where we manage sending our traffic through to spamd or OpenSMTPd.

First up is a redirect rule (note the syntax here, FreeBSD 11 uses the older style PF syntax (pre-OpenBSD 4.6) so the syntax may seem odd. If we receive anything on smtp from a host listed in the spamd table or not listed in the spamd-white table, we redirect the connection through to the spamd daemon, which deals with these connections. The next three rules are passthrough rules so that we can actually receive mail. We pass through messages from the IPs listed in the spamd-white and the webmail tables straight through to OpenSMTPd. Also, we accept messages on the submission port (587).

Then there's a few housekeeping rules to set our default policy, and accept SSH and ICMP messages.

We then pass IMAP and POP3 on our external interface in order to access Dovecot.

Lastly we allow all outgoing traffic. If you wanted to add extra security, you could limit the ports you pass, but for a single-use server it's not a problem to pass everything.

Start PF:

sudo service pf start

Now that we have our firewall setup, we can move on to our mail server configuration.

OpenSMTPd

OpenSMTPd has a very simple, and easy-to-read configuration syntax. An entire working configuration can fit into 14 lines, as you can see below:

#This is the smtpd server system-wide configuration file.
# See smtpd.conf(5) for more information.

ext_if=vtnet0

# If you edit the file, you have to run "smtpctl update table aliases"
table aliases   file:/etc/mail/aliases
table domains   file:/etc/mail/domains

# Keys
pki mail.example.com key "/usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem"
pki mail.example.com certificate "/usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem"
# If you want to listen on multiple subdomains (e.g. mail.davidlenfesty) you have to add more lines
# of keys, and more lines of listeners

# Listen for local SMTP connections
listen on localhost hostname mail.example.com

# listen for filtered spamd connections
listen on lo0 port 10026

# Listen for submissions
listen on $ext_if port 587 tls-require auth pki mail.example.com tag SUBMITTED

# Accept mail from external sources.
accept from any for domain <domains> alias <aliases> deliver to maildir "~/mail"

accept for local alias <aliases> deliver to maildir "~/mail"
accept from local for any relay tls
accept tagged SUBMITTED for any relay tls

Firstly, we again define our external interface, as well as a few tables, aliases and domains. Then we move on to the SSL key and certificate for any domains we want to handle mail under.

In the next section, we define the interfaces and ports we want to listen on. Firstly, we listen on localhost for our mail.example.com domain, for any local connections. Then we listen for our spamd-filtered messages and submitted messages on the external interface. Lastly, we listen for submissions, these happen on port 587 and we are requiring them to authenticate, for security reasons.

Lastly are our accept settings. We accept any message for any of our domains defined in our domains table for aliases in our aliases table, to deliver to their home directory in the maildir format. Then we accept all local connections for local mailboxes and relay out our messages, so we can send email. Lastly, we accept our submitted messages to relay. If we didn't require authentication for our submissions port, this would be a big security hazard. This would let anyone use our server as a spam relay.

Aliases

FreeBSD ships with a default alias file /etc/mail/aliases in the following format:

vuser1:  user1
vuser2:  user1
vuser3:  user1
vuser4:  user2

This defines the different mail boxes, and where we want to forward messages sent to these defined mailboxes. We can either define our users as local system users or external mailboxes to forward to. The default FreeBSD file is quite descriptive so you can refer to that for reference.

Domains

FreeBSD does not supply a default domains file, but this is incredibly simple:

# Domains
example.com
mail.example.com
smtp.example.com

This is just a plain text file with each domain you want to listen to on a new line. You can make a comment using the # symbol. This file exists simply so that you can use fewer lines of configuration.

SSL Certificates

There are two ways to be able to secure your communications with your mail server, self-signed and signed certificates. It is certainly possible to self-sign your certificates, however services like Let's Encrypt provide free and incredibly easy to use signing.

First we have to install the certbot program.

sudo pkg install py-certbot

Alternatively, it can be installed with ports:

cd /usr/ports/security/py-certbot
make install
make clean

Then, to get your certificate, you need to make sure you have opened up port 80 on your external interface. Add the following lines somewhere in your filtering rules in /usr/local/etc/pf.conf:

pass quick on $ext_if from any to any port http

Then run pfctl -f /usr/local/etc/pf.conf to reload the ruleset.

Then you can run the command for any domains you want to get a certificate for:

certbot certonly --standalone -d mail.example.com

It is recommended to set up a crontab entry to run certbot renew once every 6 months to ensure your certificates don't expire.

Then for every relevant domain, you can modify the lines to point to the correct key file:

pki mail.example.com key "/usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem"
pki mail.example.com certificate "/usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem"

Edit the securities:

sudo chmod 700 /usr/local/etc/letsencrypt/archive/mail.example.com/*

Note: You will have to do this for each original keyfile or else OpenSMTPd won't open them.

Now we can start the service:

sudo service smtpd start

Configuring spamd

Here we are using OpenBSD's spamd daemon to reduce the amount of spam we get from the internet. Essentially, this filters out messages from IPs that are known as bad from various spam sources, as well as (by default) "greylisting" incoming connections. Spamd also tries to waste spammer's timme by "stuttering" blacklisted and greylisted connections, which means it spreads out it's response over several seconds which forces the client to stay open for longer than usual.

Greylisting a connection is done when any new IP address connects that isn't on any blacklist or whitelist. Once the new address connects, spamd drops the message with an inocuous error message, then it adds it to a temporary list. Because spammers get paid for delivered messages, they will not retry on an error, whereas a legitimate service will retry relatively soon.

You will have to run the following to mount fdescfs:

mount -t fdescfs null /dev/fd

Then you will have to add this line to /etc/fstab:

fdescfs     /dev/fd     fdescfs rw      0       0

The default config file (found in /usr/local/etc/spamd/spamd.conf.sample) will work fine. You can edit it to add new sources or change the sources you use:

sudo cp /usr/local/etc/spamd/spamd.conf.sample /usr/local/etc/spamd/spamd.conf

We can start the service with the following:

sudo service obspamd start

At this point spamd is set up.

Enabling Webmail Services

One problem with the greylisting approach is that large mail services will often send mail out through one of many different spools, and you aren't guaranteed to get the same server sending the message every time. One solution to this is to whitelist the IP ranges used by various webmail services. This is what the webmail table is used for in the PF configuration. This strategy can backfire if you include an IP address a spammer uses, but as long as you are careful with what ranges you put in the table you will be fine.

To add an email range to the webmail table, you can run the following command:

pfctl -t webmail -T add 192.0.2.0/24

Dovecot

If you want users to access their mail without logging in via SSH, you'll need an MDA that supports IMAP and/or POP3. A very popular program is Dovecot, with a fairly simple configuration and powerful features.

We can copy over the default configuration:

cd /usr/local/etc/dovecot
cp -R example-config/* ./

The configuration is made up of quite a few different files. To see the differences between your configuration and the dovecot defaults, run the command below:

sudo doveconf -n

The following is a simple, working configuration:

# 2.3.2.1 (0719df592): /usr/local/etc/dovecot/dovecot.conf
# OS: FreeBSD 11.2-RELEASE amd64  
# Hostname: mail.example.com
hostname = mail.example.com
mail_location = maildir:~/mail
namespace inbox {
  inbox = yes
  location = 
  mailbox Archive {
    auto = create
    special_use = \Archive
  }
  mailbox Archives {
    auto = create
    special_use = \Archive
  }
  mailbox Drafts {
    auto = subscribe
    special_use = \Drafts
  }
  mailbox Junk {
    auto = create
    autoexpunge = 60 days
    special_use = \Junk
  }
  mailbox Sent {
    auto = subscribe
    special_use = \Sent
  }
  mailbox "Sent Mail" {
    auto = no
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    auto = no
    special_use = \Sent
  }
  mailbox Spam {
    auto = no
    special_use = \Junk
  }
  mailbox Trash {
    auto = no
    autoexpunge = 90 days
    special_use = \Trash
  }
  prefix = 
  separator = /
}
passdb {
  args = imap
  driver = pam
}
ssl = required
ssl_cert = </usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem
ssl_dh = </usr/local/etc/dovecot/dh.pem
ssl_key = </usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem
userdb {
  driver = passwd
}

Most config files will be in conf.d

The important ones are 10-auth.conf, 10-mail.conf, and 10-ssl.conf.

You can configure the different mailboxes you use in 15-mailboxes.conf. What you see above is a good configuration for many systems, but your mileage may vary. It's recommended you play around with this with as many different clients as you can.

Authentication

Most default settings will be correct. If you want to use the system users to authenticate, you will have to edit 10-auth.conf.

Uncomment the following line:

!include auth-system.conf.ext

Encryption

We have to generate Diffie-Hellman parameters:

sudo nohup openssl dhparam -out /usr/local/etc/dovecot/dh.pem

Note: This will take a long time to run. Much longer than you might expect.

We can now start Dovecot:

sudo service dovecot start

Conclusion

At this point, we have a functional, secure and relatively spam-free mail server.

Some more things to look into from here are using SpamAssassin to heuristically get rid of spam, as well as finding more spamd blacklists put out by sources you trust.


Tags: #BSD #Email

Leave a Comment

Cómo instalar Blacklistd en FreeBSD 11.1

Cómo instalar Blacklistd en FreeBSD 11.1

Introducción Cualquier servicio que esté conectado a Internet es un objetivo potencial para ataques de fuerza bruta o acceso injustificado. Hay herramientas como fail2ba

How To Install Apache, MySQL and PHP (FAMP) Stack on FreeBSD 12.0

How To Install Apache, MySQL and PHP (FAMP) Stack on FreeBSD 12.0

Introduction A FAMP stack, which is comparable to a LAMP stack on Linux, is a collection of open-source software that is typically installed together t

Configurar OpenBSD 5.6 con cifrado de disco completo

Configurar OpenBSD 5.6 con cifrado de disco completo

Este tutorial le mostrará cómo configurar OpenBSD 5.6 con un disco completamente encriptado en su Vultr VPS. Una nota sobre la parte de cifrado: la mayoría de los centros de datos alrededor de

Cómo usar Sudo en Debian, CentOS y FreeBSD

Cómo usar Sudo en Debian, CentOS y FreeBSD

Usar un usuario sudo para acceder a un servidor y ejecutar comandos a nivel raíz es una práctica muy común entre Linux y Unix Systems Administrator. El uso de un sud

Cómo instalar osTicket en FreeBSD 12

Cómo instalar osTicket en FreeBSD 12

¿Usando un sistema diferente? osTicket es un sistema de tickets de soporte al cliente de código abierto. El código fuente de osTicket está alojado públicamente en Github. En este tutorial

How to Install Osclass on FreeBSD 12

How to Install Osclass on FreeBSD 12

Using a Different System? Osclass is an open source project that allows you to easily create a classified site without any technical knowledge. Its sourc

How to Install Wiki.js on FreeBSD 11

How to Install Wiki.js on FreeBSD 11

Using a Different System? Wiki.js is a free and open source, modern wiki app built on Node.js, MongoDB, Git and Markdown. Wiki.js source code is publicl

How to Install Lychee 3.1 Photo Album on a FreeBSD 11 FAMP VPS

How to Install Lychee 3.1 Photo Album on a FreeBSD 11 FAMP VPS

Using a Different System? Lychee 3.1 Photo Album is a simple and flexible, free and open source photo-management tool which runs on a VPS server. It install

Installing Fork CMS on FreeBSD 12

Installing Fork CMS on FreeBSD 12

Using a Different System? Fork is an open source CMS written in PHP. Forks source code is hosted on GitHub. This guide will show you how to install Fork CM

Crear archivo de intercambio en FreeBSD 10

Crear archivo de intercambio en FreeBSD 10

Fuera de la caja, los servidores Vultr FreeBSD no están configurados para incluir espacio de intercambio. Si su intención es una instancia de nube desechable, probablemente no necesite

Cómo cambiar el tamaño de un disco en FreeBSD

Cómo cambiar el tamaño de un disco en FreeBSD

El sistema operativo FreeBSD utiliza UFS (Sistema de archivos Unix) para su sistema de archivos de particiones raíz; también conocido como freebsd-ufs en caso de una actualización

How to Install Selfoss RSS Reader on a FreeBSD 11 FAMP VPS

How to Install Selfoss RSS Reader on a FreeBSD 11 FAMP VPS

Using a Different System? Selfoss RSS Reader is a free and open source self-hosted web-based multipurpose, live stream, mashup, news feed (RSS/Atom) reade

How to Install Matomo Analytics on FreeBSD 11

How to Install Matomo Analytics on FreeBSD 11

Using a Different System? Matomo (formerly Piwik) is an open source analytics platform, an open alternative to Google Analytics. Matomo source is hosted o

How to Enable TLS 1.3 in Nginx on FreeBSD 12

How to Enable TLS 1.3 in Nginx on FreeBSD 12

Using a Different System? TLS 1.3 is a version of the Transport Layer Security (TLS) protocol that was published in 2018 as a proposed standard in RFC 8446

How to Install Craft CMS on FreeBSD 12

How to Install Craft CMS on FreeBSD 12

Using a Different System? Introduction Craft CMS is an open source CMS written in PHP. Craft CMS source code is hosted on GitHub. This guide will show yo

Cómo instalar Backdrop CMS en un FreeBSD 11 FAMP VPS

Cómo instalar Backdrop CMS en un FreeBSD 11 FAMP VPS

¿Usando un sistema diferente? Backdrop CMS 1.8.0 es un sistema de administración de contenido (CMS) simple y flexible, amigable para dispositivos móviles, gratuito y de código abierto que nos permite

Cómo instalar ImpressPages CMS 5.0 en un FreeBSD 11 FAMP VPS

Cómo instalar ImpressPages CMS 5.0 en un FreeBSD 11 FAMP VPS

¿Usando un sistema diferente? ImpressPages CMS 5.0 es un sistema de gestión de contenido (CMS) simple y efectivo, gratuito y de código abierto, fácil de usar y basado en MVC

How to Install NodeBB forum on FreeBSD 12

How to Install NodeBB forum on FreeBSD 12

Using a Different System? NodeBB is a Node.js based forum software. It utilizes web sockets for instant interactions and real-time notifications. The NodeB

Install eSpeak on FreeBSD 12

Install eSpeak on FreeBSD 12

Using a Different System? ESpeak can generate text-to-speech (TTS) audio files. These can be useful for many reasons, such as creating your own Turin

Instalar TaskServer (taskd) en FreeBSD 11

Instalar TaskServer (taskd) en FreeBSD 11

¿Usando un sistema diferente? TaskWarrior es una herramienta de gestión de tiempo de código abierto que es una mejora en la aplicación Todo.txt y sus clones. Debido a th

ZPanel y Sentora en CentOS 6 x64

ZPanel y Sentora en CentOS 6 x64

ZPanel, un panel de control de alojamiento web popular, se bifurcó en 2014 a un nuevo proyecto llamado Sentora. Aprende a instalar Sentora en tu servidor con este tutorial.

Cómo instalar Vtiger CRM Open Source Edition en CentOS 7

Cómo instalar Vtiger CRM Open Source Edition en CentOS 7

Aprende cómo instalar Vtiger CRM, una aplicación de gestión de relaciones con el cliente, en CentOS 7 para aumentar tus ventas y mejorar el servicio al cliente.

Cómo instalar el servidor Counter-Strike 1.6 en Linux

Cómo instalar el servidor Counter-Strike 1.6 en Linux

Esta guía completa le mostrará cómo configurar un servidor Counter-Strike 1.6 en Linux, optimizando el rendimiento y la seguridad para el mejor juego. Aprende los pasos más recientes aquí.

¿Puede la IA luchar con un número cada vez mayor de ataques de ransomware?

¿Puede la IA luchar con un número cada vez mayor de ataques de ransomware?

Los ataques de ransomware van en aumento, pero ¿puede la IA ayudar a lidiar con el último virus informático? ¿Es la IA la respuesta? Lea aquí, sepa que la IA es una bendición o una perdición

ReactOS: ¿Es este el futuro de Windows?

ReactOS: ¿Es este el futuro de Windows?

ReactOS, un sistema operativo de código abierto y gratuito, está aquí con la última versión. ¿Puede satisfacer las necesidades de los usuarios de Windows de hoy en día y acabar con Microsoft? Averigüemos más sobre este estilo antiguo, pero una experiencia de sistema operativo más nueva.

Manténgase conectado a través de la aplicación de escritorio WhatsApp 24 * 7

Manténgase conectado a través de la aplicación de escritorio WhatsApp 24 * 7

Whatsapp finalmente lanzó la aplicación de escritorio para usuarios de Mac y Windows. Ahora puede acceder a Whatsapp desde Windows o Mac fácilmente. Disponible para Windows 8+ y Mac OS 10.9+

¿Cómo puede la IA llevar la automatización de procesos al siguiente nivel?

¿Cómo puede la IA llevar la automatización de procesos al siguiente nivel?

Lea esto para saber cómo la Inteligencia Artificial se está volviendo popular entre las empresas de pequeña escala y cómo está aumentando las probabilidades de hacerlas crecer y dar ventaja a sus competidores.

La actualización complementaria de macOS Catalina 10.15.4 está causando más problemas que resolver

La actualización complementaria de macOS Catalina 10.15.4 está causando más problemas que resolver

Recientemente, Apple lanzó macOS Catalina 10.15.4, una actualización complementaria para solucionar problemas, pero parece que la actualización está causando más problemas que conducen al bloqueo de las máquinas Mac. Lee este artículo para obtener más información

13 Herramientas comerciales de extracción de datos de Big Data

13 Herramientas comerciales de extracción de datos de Big Data

13 Herramientas comerciales de extracción de datos de Big Data

¿Qué es un sistema de archivos de diario y cómo funciona?

¿Qué es un sistema de archivos de diario y cómo funciona?

Nuestra computadora almacena todos los datos de una manera organizada conocida como sistema de archivos de diario. Es un método eficiente que permite a la computadora buscar y mostrar archivos tan pronto como presiona buscar.