---
# System prepended metadata

title: 'Configuración de Dovecot, SIEVE y ManageSIEVE'

---

[toc]
# Configuración de Dovecot, SIEVE y ManageSIEVE

## Configuración de Dovecot
<p style="text-align: justify;">
Vamos a configurar Dovecot para manejar correos de forma segura (IMAP, POP3) y trabajar con Postfix. Esto incluye configurar autenticación con MySQL, SSL, carpetas predeterminadas y Sieve para filtrado de correos.
    
### Crear Copias de Seguridad

    sudo cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf.orig
    sudo cp /etc/dovecot/conf.d/10-mail.conf /etc/dovecot/conf.d/10-mail.conf.orig
    sudo cp /etc/dovecot/conf.d/10-auth.conf /etc/dovecot/conf.d/10-auth.conf.orig
    sudo cp /etc/dovecot/dovecot-sql.conf.ext /etc/dovecot/dovecot-sql.conf.ext.orig
    sudo cp /etc/dovecot/conf.d/10-master.conf /etc/dovecot/conf.d/10-master.conf.orig
    sudo cp /etc/dovecot/conf.d/10-ssl.conf /etc/dovecot/conf.d/10-ssl.conf.ori
    
### Configurar dovecot.conf
    
    sudo vi /etc/dovecot/dovecot.conf
    
    protocols = imap pop3 lmtp sieve
    postmaster_address = postmaster@ccuellar.test

###  Configurar 10-mail.conf
    
    sudo vi /etc/dovecot/conf.d/10-mail.conf
<p style="text-align: justify;">
Este archivo define cómo Dovecot maneja los correos en el sistema de archivos.

Añade y comenta:

    #mail_location = mbox:~/mail:INBOX=/var/mail/%u
    mail_location = maildir:/var/mail/vhosts/%d/%n

%d: Representa el dominio del usuario.
%n: Representa el nombre del usuario sin el dominio.
    
### Crea los directorios necesarios y asigna permisos:
    
    sudo mkdir -p /var/mail/vhosts
    sudo groupadd -g 5000 vmail
    sudo useradd -g vmail -u 5000 vmail -d /var/mail
    sudo chown -R vmail:vmail /var/mail

### Configurar Autenticación (10-auth.conf)
    
    sudo vi /etc/dovecot/conf.d/10-auth.conf
    
Añade o edita:
    
    disable_plaintext_auth = yes
    ...
    auth_mechanisms = plain login
    ...
    !include auth-system.conf.ext
    !include auth-sql.conf.ext
    
### Configurar auth-sql.conf.ext
Este archivo es para configurar la autenticación con MySQL.
    
    sudo vi /etc/dovecot/conf.d/auth-sql.conf.ext

Añade o edita:
    
    passdb {
      driver = sql
      args = /etc/dovecot/dovecot-sql.conf.ext
    }

    userdb {
      driver = static
      args = uid=vmail gid=vmail home=/var/mail/vhosts/%d/%n
    }
    
### Configurar dovecot-sql.conf.ext
    
    sudo vi /etc/dovecot/dovecot-sql.conf.ext

Añade:
    
    driver = mysql
    connect = host=127.0.0.1 dbname=mailserver user=mailuser password=tu_contraseña
    default_pass_scheme = PLAIN-MD5
    password_query = SELECT email AS user, password FROM virtual_users WHERE email='%u' AND active='1';
    
### Configurar 10-master.conf
    
    sudo vi /etc/dovecot/conf.d/10-master.conf

Desactiva IMAP y POP3 no seguros (puertos 143 y 110):
    
    service imap-login {
      inet_listener imap {
        port = 0
      }
      inet_listener imaps {
        port = 993
        ssl = yes
      }
    }

    service pop3-login {
      inet_listener pop3 {
        port = 0
      }
      inet_listener pop3s {
        port = 995
        ssl = yes
      }
    }
    
    service lmtp {
      unix_listener /var/spool/postfix/private/dovecot-lmtp {
        mode = 0666
        user = postfix
        group = postfix
      }
    
Configura LMTP y autenticación para trabajar con Postfix:
    
    service auth {
      # auth_socket_path points to this userdb socket by default. It's typically
      # used by dovecot-lda, doveadm, possibly imap process, etc. Users that have
      # full permissions to this socket are able to get a list of all usernames and
      # get the results of everyone's userdb lookups.
      #
      # The default 0666 mode allows anyone to connect to the socket, but the
      # userdb lookups will succeed only if the userdb returns an "uid" field that
      # matches the caller process's UID. Also if caller's uid or gid matches the
      # socket's uid or gid the lookup succeeds. Anything else causes a failure.
      #
      # To give the caller full permissions to lookup all users, set the mode to
      # something else than 0666 and Dovecot lets the kernel enforce the
      # permissions (e.g. 0777 allows everyone full permissions).
      unix_listener auth-userdb {
        mode = 0600
        user = vmail 
        #group = 
      }

      # Postfix smtp-auth
      unix_listener /var/spool/postfix/private/auth {
        mode = 0666
        user = postfix
        group = postfix
      }

      # Auth process is run as this user.
      user = dovecot
    }

    service auth-worker {
      # Auth worker process is run as root by default, so that it can access
      # /etc/shadow. If this isn't necessary, the user should be changed to
      # $default_internal_user.
      user = vmail
    }
    
### Configurar SSL (10-ssl.conf)
    
    sudo vi /etc/dovecot/conf.d/10-ssl.conf

Añade:
    
    ssl = required
    ssl_cert = </etc/ssl/certs/email.ccuellar.test.crt
    ssl_key = </etc/ssl/private/email.ccuellar.test.key

### Configurar Logs Personalizados

    sudo vi /etc/dovecot/conf.d/10-logging.conf


Añade:

    ##
    ## Log destination.
    ##

    # Log file to use for error messages. "syslog" logs to syslog,
    # /dev/stderr logs to stderr.
    #log_path = syslog
    log_path = /var/log/dovecot.log
    # Log file to use for informational messages. Defaults to log_path.
    #info_log_path = 
    # Log file to use for debug messages. Defaults to info_log_path.
    #debug_log_path = 

    # Syslog facility to use if you're logging to syslog. Usually if you don't
    # want to use "mail", you'll use local0..local7. Also other standard
    # facilities are supported.
    #syslog_facility = mail

    ##
    ## Logging verbosity and debugging.
    ##

    # Log filter is a space-separated list conditions. If any of the conditions
    # match, the log filter matches (i.e. they're ORed together). Parenthesis
    # are supported if multiple conditions need to be matched together.
    #
    # See https://doc.dovecot.org/configuration_manual/event_filter/ for details.
    #
    # For example: event=http_request_* AND category=error AND category=storage
    #
    # Filter to specify what debug logging to enable. This will eventually replace
    # mail_debug and auth_debug settings.
    #log_debug = 

    # Crash after logging a matching event. For example category=error will crash
    # any time an error is logged, which can be useful for debugging.
    #log_core_filter = 

    # Log unsuccessful authentication attempts and the reasons why they failed.
    #auth_verbose = no

    # In case of password mismatches, log the attempted password. Valid values are
    # no, plain and sha1. sha1 can be useful for detecting brute force password
    # attempts vs. user simply trying the same password over and over again.
    # You can also truncate the value to n chars by appending ":n" (e.g. sha1:6).
    #auth_verbose_passwords = no

    # Even more verbose logging for debugging purposes. Shows for example SQL
    # queries.
    #auth_debug = no

    # In case of password mismatches, log the passwords and used scheme so the
    # problem can be debugged. Enabling this also enables auth_debug.
    #auth_debug_passwords = no

    # Enable mail process debugging. This can help you figure out why Dovecot
    # isn't finding your mails.
    #mail_debug = no

    # Show protocol level SSL errors.
    #verbose_ssl = no

    # mail_log plugin provides more event logging for mail processes.
    plugin {
      # Events to log. Also available: flag_change append
      mail_log_events = delete undelete expunge copy mailbox_delete mailbox_rename
      # Available fields: uid, box, msgid, from, subject, size, vsize, flags
      # size and vsize are available only for expunge and copy events.
      mail_log_fields = uid box msgid size
    }

    ##
    ## Log formatting.
    ##

    # Prefix for each line written to log file. % codes are in strftime(3)
    # format.
    log_timestamp = "%b %d %H:%M:%S "

    # Space-separated list of elements we want to log. The elements which have
    # a non-empty variable value are joined together to form a comma-separated
    # string.
    login_log_format_elements = user=<%u> method=%m rip=%r lip=%l mpid=%e %c

    # Login log format. %s contains login_log_format_elements string, %$ contains
    # the data we want to log.
    login_log_format = %$: %s

    # Log prefix for mail processes. See doc/wiki/Variables.txt for list of
    # possible variables you can use.
    mail_log_prefix = "%s(%u)<%{pid}><%{session}>: "

    # Format to use for logging mail deliveries:
    #  %$ - Delivery status message (e.g. "saved to INBOX")
    #  %m / %{msgid} - Message-ID
    #  %s / %{subject} - Subject
    #  %f / %{from} - From address
    #  %p / %{size} - Physical size
    #  %w / %{vsize} - Virtual size
    #  %e / %{from_envelope} - MAIL FROM envelope
    #  %{to_envelope} - RCPT TO envelope
    #  %{delivery_time} - How many milliseconds it took to deliver the mail
    #  %{session_time} - How long LMTP session took, not including delivery_time
    #  %{storage_id} - Backend-specific ID for mail, e.g. Maildir filename
    #deliver_log_format = msgid=%m: %$
    deliver_log_format = Message-ID: %m - Subject: %s - From: %f - Size: %p - Status: %$
Ahora los eventos de Dovecot se escriben en el fichero /var/log/dovecot.log
### Configurar Carpetas Predeterminadas
<p style="text-align: justify;">
Ahora vamos a realizar algunas configuraciones adicionales en Dovecot para asegurarnos de que todo funcione correctamente. Estas configuraciones incluyen la gestión de carpetas predeterminadas (como Borradores, Spam, Papelera, etc.) y ajustes específicos para los protocolos IMAP y POP3.
    
#### Configurar Carpetas Predeterminadas (15-mailboxes.conf)
    
    sudo vi /etc/dovecot/conf.d/15-mailboxes.conf

Editamos y añadimos:
    
    namespace inbox {
      # These mailboxes are widely used and could perhaps be created automatically:
      mailbox Drafts {
        special_use = \Drafts
        auto = subscribe
      }
      #mailbox Junk {
       # special_use = \Junk
      #}
      mailbox Spam {
         special_use = \Junk
         auto = subscribe
      }
      mailbox Trash {
        special_use = \Trash
        auto = subscribe
      }

      # For \Sent mailboxes there are two widely used names. We'll mark both of
      # them as \Sent. User typically deletes one of them if duplicates are created.
      mailbox Sent {
        special_use = \Sent
        auto = subscribe
      }
      #mailbox "Sent Messages" {
        #special_use = \Sent
      #}
    
* special_use: Define el propósito de cada carpeta (por ejemplo, \Drafts para Borradores, \Junk para Spam, etc.).
* auto = subscribe: Asegura que estas carpetas estén suscritas automáticamente para todos los usuarios.
    
### Configurar IMAP (20-imap.conf)
<p style="text-align: justify;">
Ahora vamos a ajustar el archivo /etc/dovecot/conf.d/20-imap.conf para mejorar el rendimiento y la experiencia del usuario.
    
    sudo vi /etc/dovecot/conf.d/20-imap.conf

Añade:
    
    imap_logout_format = in=%i out=%o deleted=%{deleted} expunged=%{expunged} \

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

      # Maximum number of IMAP connections allowed for a user from each IP address.
      # NOTE: The username is compared case-sensitively.
      mail_max_userip_connections = 10
    }
    
* Esta línea registra información útil cuando un usuario cierra sesión, como cuántos bytes entraron (in=%i) y salieron (out=%o). protocol imap { mail_plugins = $mail_plugins mail_log notify mail_max_userip_connections = 10 }
* mail_plugins: Habilita plugins útiles como mail_log (para registrar eventos) y notify (para notificaciones en tiempo real).
* mail_max_userip_connections: Limita el número máximo de conexiones IMAP por usuario desde una misma IP a 10. Esto ayuda a prevenir abusos.

### Configurar POP3 (20-pop3.conf)
<p style="text-align: justify;">
Ajustaremos el archivo /etc/dovecot/conf.d/20-pop3.conf para mejorar la compatibilidad con el protocolo POP3.
    
    sudo vi /etc/dovecot/conf.d/20-pop3.conf
    
Añade:
    
pop3_logout_format = top=%t/%p, retr=%r/%b, del=%d/%m, size=%s

    # Workarounds for various client bugs:
    #   outlook-no-nuls:
    #     Outlook and Outlook Express hang if mails contain NUL characters.
    #     This setting replaces them with 0x80 character.
    #   oe-ns-eoh:
    #     Outlook Express and Netscape Mail breaks if end of headers-line is
    #     missing. This option simply sends it if it's missing.
    # The list is space-separated.
    #pop3_client_workarounds = 

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

      # Maximum number of POP3 connections allowed for a user from each IP address.
      # NOTE: The username is compared case-sensitively.
      mail_max_userip_connections = 10
    }
    
* Información detallada cuando un usuario cierra sesión usando POP3, como cuántos correos fueron recuperados (retr=%r/%b) o eliminados (del=%d/%m).
* Al igual que con IMAP, habilitamos plugins útiles y limitamos el número máximo de conexiones POP3 por usuario desde una misma IP a 10.

    sudo systemctl restart dovecot

### Error en los logs
<p style="text-align: justify;"> 
Si has notado errores repetitivos en el archivo de logs (/var/log/auth.log) relacionados con autenticaciones fallidas en Dovecot, como estos:
    
    Oct 1 09:58:01 servidor auth: pam_unix(dovecot:auth): authentication failure; logname= uid=5000 euid=5000 tty=doveco
    Oct 1 09:58:04 servidor auth: pam_unix(dovecot:auth): check pass; user unknown
<p style="text-align: justify;">     
Esto ocurre porque Dovecot está intentando usar el sistema de autenticación PAM (Pluggable Authentication Modules) por defecto, pero no está configurado correctamente para trabajar con nuestra base de datos MySQL. Para solucionarlo, vamos a desactivar la autenticación PAM y asegurarnos de que Dovecot use solo MySQL.
    
Crear una Copia de Seguridad:
    
    sudo cp /etc/dovecot/conf.d/auth-system.conf.ext /etc/dovecot/conf.d/auth-system.conf.ext.orig
    sudo vi /etc/dovecot/conf.d/auth-system.conf.ext
 
Editamos o modificamos:
Buscamos las siguientes líneas y coméntamos añadiendo # al inicio de cada una:

    ###passdb {
    ###  driver = pam
      # [session=yes] [setcred=yes] [failure_show_msg=yes] [max_requests=<n>]
      # [cache_key=<key>] [<service name>]
      #args = dovecot
    ###}
    …
    ###userdb {
      # <doc/wiki/AuthDatabase.Passwd.txt>
    ###  driver = passwd
      # [blocking=no]
      #args =

      # Override fields from passwd
      #override_fields = home=/home/virtual/%u
    ###}
    
* Comentamos la sección passdb para desactivar la autenticación PAM.
* Comentamos la sección userdb para evitar que Dovecot intente usar el sistema de usuarios local (passwd).
    
## Configurar Sieve
Instala los paquetes necesarios:
    
    sudo apt update
    sudo apt install dovecot-sieve dovecot-managesieved
    
Habilita Sieve en LMTP:
    
    sudo vi /etc/dovecot/conf.d/20-lmtp.conf
    
Añade:
    
    protocol lmtp {
      mail_plugins = $mail_plugins sieve
    }
    
Habilitamos el plugin sieve para que Dovecot use reglas Sieve al entregar correos a través de LMTP.

### Configurar Sieve (90-sieve.conf)
    
    sudo vi /etc/dovecot/conf.d/90-sieve.conf

Añade:
    
    plugin {
      sieve = ~/.dovecot.sieve
      sieve_global_path = /var/lib/dovecot/sieve/default.sieve
      sieve_dir = ~/sieve
      sieve_global_dir = /var/lib/dovecot/sieve/
    }
    
* sieve: Define el archivo Sieve personal para cada usuario.
* sieve_global_path: Define un archivo Sieve global que afecta a todos los usuarios.
* sieve_dir y sieve_global_dir: Definen los directorios donde se almacenan las reglas Sieve.
    
### Habilitar ManageSIEVE (20-managesieve.conf)
    
    sudo vi /etc/dovecot/conf.d/20-managesieve.conf

Añade:
    
    service managesieve-login {
      inet_listener sieve {
        port = 4190
      }
    }

    service managesieve {
      process_limit = 1024
    }
    
* port = 4190: Define el puerto donde escuchará el servicio ManageSIEVE.
* process_limit: Limita el número máximo de conexiones simultáneas.
    
### Habilitar Protocolos en Dovecot
    
    sudo vi /etc/dovecot/dovecot.conf

Añade:
    
    protocols = imap pop3 lmtp sieve

    
### Crea un archivo global de reglas Sieve:
    
    sudo mkdir -p /var/lib/dovecot/sieve
    sudo vi /var/lib/dovecot/sieve/default.sieve
Añade:   
    
    require "fileinto";
    if header :contains "X-Spam-Flag" "YES" {
      fileinto "Junk";
    }

Compila el archivo Sieve:
    
    sudo sievec /var/lib/dovecot/sieve/default.sieve
    sudo chown -R vmail:vmail /var/lib/dovecot

Permisos postfix:
    
    sudo chmod -R 755 /etc/postfix

Verificar el Servicio ManageSIEVE:
<p style="text-align: justify;">
Usaremos telnet para verificar que el servicio ManageSIEVE está funcionando correctamente:
    
    telnet X.X.X.X 4190
    
Si todo está bien, verás una respuesta similar a esta:

    "IMPLEMENTATION" "Dovecot Pigeonhole"
    "SIEVE" "fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date index ihave duplicate mime foreverypart extracttext"
    "NOTIFY" "mailto"
    "SASL" ""
    "STARTTLS"
    "VERSION" "1.0"
    OK "Dovecot ready."
    
    
🤗
    
---
    
## [Índice de secciones aquí](https://hackmd.io/@ccuellar/BJJyhAYpye)

## [👈Anterior sección](https://hackmd.io/@ccuellar/SkKQiAY61g) 😄 [Siguiente sección 👉](https://hackmd.io/@ccuellar/Bk6H2CYTyx)