You are viewing the documentation for a prerelease version. View Latest

Servidores de Correo

Fedora ofrece muchas aplicaciones avanzadas para servir y acceder al correo electrónico. Este capítulo describe los protocolos de correo electrónico modernos en uso hoy y algunos programas diseñados para enviar y recibir correo electrónico.

Protocolos de Correo Electrónico

Hoy el correo electrónico es entregado usando una arquitectura cliente/servidor. Un mensaje de correo electrónico es creado usando un programa cliente de correo. Este programa después envía el mensaje al servidor. El servidor lo reenvía al servidor de correo electrónico del receptor, desde donde se sirve el mensaje al cliente de correo electrónico del receptor.

Para habilitar este proceso diversos protocolo estándar de red permiten a diferentes máquinas, con frecuencia corriendo sobre diferentes sistemas operativos, enviar y recibir correo electrónico.

Los siguientes protocolos sobre los que hablamos son los usados más comúnmente en la transferencia de correo electrónico.

Protocolos de Transporte de Correo

La entrega de correo desde una aplicación cliente al servidor y desde el servidor de origen al de destino es manejada por el Protocolo Sencillo de Transferencia de Correo (SMTP).

SMTP

El propósito principal de SMTP es transferir correo electrónico entre servidores de correo. Sin embargo, es también crítico para los clientes de correo electrónico. Para enviar correo electrónico, el cliente envía el mensaje a un servidor de correo saliente, que después contacta con el servidor de correo de destino para su entrega. Por esta razón es necesario especificar un servidor SMTP cuando se configura un cliente de correo electrónico.

Bajo Fedora, un usuario puede configurar un servidor SMTP en la máquina local para manejar la entrega de correo. Sin embargo, tabién es posible configurar servidores SMTP remotos para el correo saliente.

Un punto importante a saber sobre el protocolo SMTP es que no requiere autenticación. Esto permite a cualquiera en la Internet enviar correo electrónico a cualquier otro e incluso a grandes grupos de personas. Es esta característica de SMTP la que hace posible el correo basura o spam. La imposición de restricciones de retransmisión impide que los usuarios aleatorios de Internet envíen correos electrónicos a través de su servidor SMTP a otros servidores de Internet. Los servidores que no imponen estas restricciones son llamados servidores de retransmisión abierta.

Fedora proporciona los programas SMTP Postfix y Sendmail .

Protocolos de Acceso al Correo

Hay dos protocolos principales usados por las aplicaciones cliente de correo electrónico para recuperar correo electrónico de los servidores de correo: el Protocolo de Oficina de Correos (POP) y el Protocolo de Acceso al Mensaje de Internet (IMAP).

POP

El servidor POP predeterminado bajo Fedora es Dovecot y se proporciona por el paquete dovecot.

Instalar el paquete dovecot

Con el objetivo de usar Dovecot, asegúrese primero de que el paquete dovecot está instalado en su sistema corriendo como root:

~]# dnf install dovecot

Para más información sobre la instalación de paquetes con DNF, vea Instalando Paquetes.

Cuando se utiliza un servidor POP los mensajes de correo electrónico son descargados por las aplicaciones de clientes de correo electrónico. De modo predeterminado la mayoría de los clientes de correo electrónico `POP`están configurados para borrar automáticamente el mensaje del servidor de correo electrónico una vez que ha sido transferido con éxito, sin embargo este ajuste normalmente puede ser cambiado.

POP es totalmente compatible con los estándar de mensajería más importantes de Internet,como Multipurpose Internet Mail Extensions (MIME), que permite los adjuntos de correo electrónico.

POP trabaja mejor para los usuarios que tiene un sistema que permite leer correo electrónico. Trabaja también bien con los usuarios que no tiene una conexión continua a Internet o a la red en la que está el servidor de correo. Desafortunadamente para aquellos con conexiones de red lentas, POP requiere programas clientes después de la autenticación para descargar el contenido de cada mensaje. Esto puede llevar mucho tiempo si el mensaje tiene grandes adjuntos.

La versión más actual del protocolo estándar POP es POP3.

Hay, sin embargo, diversas variantes del protocolo POP menos usadas:

  • APOPPOP3 con autenticación MD5. Se envía un hash codificado de la contraseña del usuario desde el cliente de correo electrónico al servidor en lugar de enviar una contraseña desencriptada.

  • KPOPPOP3 con autenticación Kerberos.

  • RPOPPOP3 con autenticación RPOP. Esto usa una ID por usuario, similar a una contraseña, para autenticar las peticiones POP. Sin embargo esta ID no está encriptada, de modo que RPOP no es más seguro que el POP estándar.

Para añadir seguridad es posible usar encriptación Secure Socket Layer (SSL) para la autenticación del cliente y las sesiones de transferencia de datos. Esto se puede habilitar usando el servicio pop3s o usando la aplicación stunnel. Para más información sobre el aseguramiento de la comunicación de correo electrónico vea Asegurando la Comunicación.

IMAP

El servidor IMAP predeterminado bajo Fedora es Dovecot que es proporcionado por el paquete dovecot. Vea en POP información sobre como instalar Dovecot.

Cuando se utilizar un servidor de correo IMAP los mensajes de correo electrónico permanecen en el servidor donde los usuarios pueden leerlos o borrarlos. IMAP también permite a las aplicaciones cliente crear, renombrar o borrar directorios de correo en el servidor para organizar y almacenar el correo electrónico.

IMAP es particularmente útil para los usuarios que acceden a su correo electrónico desde múltiples máquinas. El protocolo es también conveniente para los usuarios que se conectan al servidor de correo por medio de una conexión lenta, puesto que solo se descarga la cabecera del mensaje hasta que se abre, ahorrando ancho de banda. El usuario tiene también la capacidad de borrar mensajes sin verlos o descargarlos.

Para mayor comodidad, las aplicaciones clientes IMAP son capaces de almacenar en caché copias de los mensajes localmente, de modo que el usuario puede navegar antes de leer los mensajes cuando no está conectado directamente al servidor IMAP.

IMAP, como POP, es totalmente compatible con importantes estándar de mensajería en Internet, como MIME, que permite los adjuntos para correo electrónico.

Para añadir seguridad, es posible utilizar encriptación SSL para la autenticación del cliente y las sesiones de transferencia de datos. Esto se puede habilitar utilizando el servicio imaps o usando el programa stunnel. Para más información sobre el aseguramiento de la comunicación de correo electrónico, vea Asegurando la Comunicación.

Hay otros servidores IMAP disponibles, tanto libres como comerciales, muchos de los cuales extiende el protocolo IMAP y proporcionan funcionalidades adicionales.

Dovecot

Los procesos imap-login y pop3-login que implementan los protocolos IMAP y POP3`son engendrados por el demonio maestro `dovecot incluido en el paquete dovecot. El uso de IMAP y POP se configura a través del archivo de configuración /etc/dovecot/dovecot.conf; de modo predeterminado dovecot ejecuta IMAP y POP3 juntos con sus versiones seguras utilizando SSL. Para configurar dovecot para usar POP, complete los siguientes pasos:

  1. Edite el archivo de configuración /etc/dovecot/dovecot.conf para estar seguro de que la variable protocols no está comentada (no tenga el signo almohadilla (#) al principio de la línea) y contiene el argumento pop3. Por ejemplo:

    protocols = imap pop3 lmtp

    Cuando la variable protocols se deja comentada, dovecot usará los valores predeterminados como se describe arriba.

  2. Haga el cambio operativo en la sesión actual ejecutando el siguiente comando como root:

    ~]# systemctl restart dovecot
  3. Hacer el cambio operativo después del siguiente reinicio ejecutando el comando:

    ~]# systemctl enable dovecot
    ln -s '/usr/lib/systemd/system/dovecot' '/etc/systemd/system/multi-user.target.wants/dovecot'
    El servicio dovecot inicia el servidor POP3

    Tenga en cuenta, por favor, que dovecot solo informa de que inicia el servidor IMAP, pero también inicia el servidor POP3.

A diferencia de SMTP, tanto IMAP como POP3 requieren que los clientes que se conecten se autentiquen con nombre de usuario y contraseña. De modo predeterminado las contraseñas para ambos protocolos se pasan por la red sin encriptar.

Para configurar SSL sobre dovecot:

  • Edite el archivo de configuración /etc/pki/dovecot/dovecot-openssl.cnf como prefiera. Sin embargo, en una instalación típica este archivo no necesita modificación.

  • Renombre, mueva o borre los archivos /etc/pki/dovecot/certs/dovecot.pem y /etc/pki/dovecot/private/dovecot.pem.

  • Ejecute el script /usr/libexec/dovecot/mkcert.sh que crea los certificados autofirmados dovecot. Estos certificados son copiados en los directorios /etc/pki/dovecot/certs y /etc/pki/dovecot/private. Para implementar los cambios reinicie dovecot enviando el siguiente comando como root:

    ~]# systemctl restart dovecot

Más detalles sobre dovecot se puede encontrar en línea en https://www.dovecot.org.

Clasificaciones de Programas de Correo Electrónico

En general, todas las aplicaciones de correo electrónico entran dentro de al menos una de las tres clasificaciones. Cada clasificación juega un papel específico en el proceso de mover y administrar mensajes de correo electrónico. Mientras que la mayoría de los usuarios solo están atentos al programa específico de correo electrónico que utiliza para enviar y recibir mensajes, cada uno es importante para asegurar que el correo electrónico llegue al destino correcto.

Agente de Transporte de Correo

Un Agente de Transporte de Correo (MTA) transporta mensajes de correo electrónico entre hosts utilizando SMTP. Un mensaje puede involucrar a varios MTAs según se mueve a su destino.

Si bien la entrega de mensajes entre máquinas puede parecer bastante sencilla, el proceso completo de decisión de sí un MTA concreto puede o debe aceptar un mensaje para su entrega es bastante complicado. Además, por problemas de spam, el uso de un MTA concreto está normalmente restringido por la configuración del MTA o la del acceso a la red en la que reside el MTA.

Muchos clientes de correo electrónico modernos pueden actuar como MTA cuando envían correo electrónico. Sin embargo, esta acción no se debería confundir con el papel de un verdadero MTA. La única razón por la que los programas clientes de correo electrónico son capaces de enviar correo electrónico como un MTA es porque el host que está corriendo la aplicación no tiene su propio MTA. Esto es particularmente verdad para los programas clientes de correo electrónico sobre sistemas operativos no basados en UNIX. Sin embargo, esto programas clientes solo envían mensajes salientes a un MTA que están autorizados a usar y no entregan directamente el mensaje al servidor de correo electrónico del receptor pretendido.

Como Fedora ofrece dos MTAs, Postfix y Sendmail, a los programas clientes de correo electrónico no se les requieren con frecuencia para que actúen como MTA. Fedora también incluye un MTA de propósito especial llamado Fetchmail.

Para más información sobre Postfix, Sendmail y Fetchmail, vea Agentes de Transporte de Correo.

Agente de Entrega de Correo

Un Agente de Entrega de Correo (MDA) es invocado por el MTA para archivar el correo electrónico entrante en el buzón de correo apropiado del usuario. En muchos casos, el MDA es en realidad un Agente de Entrega Local (LDA), como mail o Procmail.

Cualquier programa que realmente maneje un mensaje para su entrega al punto donde puede ser leído por una aplicación cliente de correo electrónico puede ser considerado un MDA. Por esta razón, algunos MTAs (como Sendmail y Postfix) puede cumplir la función de un MDA cuando agrega nuevos mensajes de correo electrónico al archivo de cola de correo de un usuario local. En general, los MDAs no transportan mensajes entre sistemas ni proporcionan una interfaz de usuario; los MDAs distribuyen y ordenan los mensajes en la máquina local para que aplicación cliente de correo electrónico puede acceder a ellos.

Agente de Usuario de Correo

Un Agente de Usuario de Correo (MUA) es sinónimo de una aplicación cliente de correo electrónico. Un MUA es un programa que, como mínimo, permite a un usuario leer y componer mensajes de correo electrónico. Muchos MUAs son capaces de recuperar mensajes por medio de los protocolos POP o IMAP, ajustando buzones de correo para almacenar mensajes y enviando mensajes salientes a un MTA.

Los MUAs pueden ser gráficos como Evolution o tener sencillos interfaces basados en texto como Mutt.

Agentes de Transporte de Correo

Fedora ofrece dos MTAs principales: Postfix y Sendmail. Postfix está configurado como el MTA predeterminado y Sendmail se considera obsoleto. Si es preciso cambiar el MTA predeterminado a Sendmail, usted puede o desinstalar Postfix o utilizar el siguiente comando como root para cambiar a Sendmail:

~]# alternatives --config mta

También puede utilizar el siguiente comando para habilitar el servicio deseado:

~]# systemctl enable service

Del mismo modo, para deshabilitar el servicio, teclee lo siguiente en un indicador de shell:

~]# systemctl disable service

Para más información sobre como administrar los servicios del sistema en Fedora Rawhide, vea Servicios y Demonios.

Postfix

Desarrollado originalmente en IBM por el experto en seguridad y programador Wietse Venema, Postfix es un MTA compatible con Sendmail que está diseñado para ser seguro, rápido y fácil de configurar.

Para mejorar la seguridad, Postfix utiliza un diseño modular, donde pequeños procesos con privilegios limitados se lanzan por un demonio maestro daemon. Los procesos más pequeños, con menos privilegios, llevan a cabo tareas muy específicas relacionadas con diversos escenarios de las entrega de correo y corren en un entorno de root modificado para limitar los efectos de los ataques.

Configurar Postfix para aceptar conexiones de red desde otros host distintos al ordenador local solo necesita unos cambios menos en su archivo de configuración. Sin embargo, para aquellos con necesidades más complejas, Postfix proporciona diversas opciones de configuración, así como complementos de terceros para hacerlo un MTA muy versátil y con todas las funciones.

Los archivos de configuración de Postfix son legibles y soportan más de 250 directivas. A diferencia de Sendmail, no se requiere procesamiento de macros para que los cambios surtan efecto y la mayoría de las opciones más utilizadas se describen en los muchos comentarios de los archivos.

La Instalación Predeterminada de Postfix

El ejecutable de Postfix es postfix. Este demonio lanza todos los procesos relacionados necesarios para manejar la entrega de correo.

Postfix almacena sus ficheros de configuración en el directorio /etc/postfix/. Lo siguiente es una lista de los archivos usados más comúnmente:

  • access — Usado para control de acceso, este archivo especifica que hosts tienen permitido conectar con Postfix.

  • main.cf — El archivo de configuración global de Postfix. La mayoría de las opciones de configuración están especificadas en este archivo.

  • master.cf — Especifica como interactúa Postfix con diversos procesos para cumplir con la entrega de correo.

  • transport — Asigna direcciones de correo electrónico a hosts de retransmisión.

El archivo aliases se puede encontrar en el directorio /etc/. Este archivo es compartido entre Postfix y Sendmail. Es una lista configurable requerida por el protocolo de correo que describe los alias de ID de usuario.

Configurar Postfix como servidor para otros clientes

El archivo predeterminado /etc/postfix/main.cf no permite a Postfix aceptar conexiones de red desde un host distinto al ordenador local. Vea instrucciones sobre la configuración de Postfix como servidor para otros clientes en Configuración Básica de Postfix.

Reinicie el servicio postfix después de cambiar cualquier opción en los archivos de configuración del directorio /etc/postfix con el objetivo de que los cambuios tengan efecto. Para hacerlo, ejecute el siguiente comando como root:

~]# systemctl restart postfix

Configuración Básica de Postfix

De modo predeterminado, Postfix no acepta conexiones de red que vengan de cualquier otro host que no sea el host lolcal. Lleve a cabo los siguientes pasos, como root para habilitar la entrega de correo a otros hosts en la red:

  • Edite el archivo /etc/postfix/main.cf con un editor de texto como vi.

  • Quite el comentario de la línea mydomain borrando el signo almohadilla (#) y reemplace domain.tld con el dominio del servidor de correo en servicio, como example.com.

  • Quite el comentario de la línea myorigin = $mydomain.

  • Quite el comentario de la línea myhostname y reemplace host.domain.tld con el nombre de host de la máquina.

  • Quite el comentario de la línea mydestination = $myhostname, localhost.$mydomain.

  • Quite el comentario de la l´linea mynetworks y reemplace 168.100.189.0/28 con una configuración de red válida para los hosts que pueden conectar al servidor.

  • Quite el comentario de la línea inet_interfaces = all.

  • Comente la línea inet_interfaces = localhost.

  • Reinicie el servicio postfix.

Una vez que se han completado estos pasos, el host acepta correo electrónico de fuera para su entrega.

Postfix tiene una gran variedad de opciones de configuración. Una de las mejores maneras de aprender a configurar Postfix es leer los comentarios dentro del archivo de configuración /etc/postfix/main.cf. Recursos adicionales incluyendo información sobre la configuración Postfix, integración de SpamAssassin o descripciones de los parámetros de /etc/postfix/main.cf están disponibles en línea en el enlace http://www.postfix.org/.

Usar Postfix con LDAP

Postfix puede usar un directorio LDAP como fuente de diversas tablas de búsqueda (p.ej.: aliases, virtual, canonical, etc.). Esto permite a LDAP almacenar información jerárquica de usuario y a Postfix solo se da el resultado de las consultas LDAP cuando las necesita. Al almacenar esta información localmente los administradores pueden mantenerlo fácilmente.

Ejemplo de búsqueda de /etc/aliases

Lo que sigue es un ejemplo básico del uso de LDAP para buscar en el archivo /etc/aliases. Compruebe que su archivo /etc/postfix/main.cf contiene lo siguiente:

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

Crear un archivo a /etc/postfix/ldap-aliases.cf si no tiene uno ya y compruebe que tiene lo siguiente:

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

donde ldap.example.com, example y com son parámetros que necesitan ser reemplazados con la especificación de un servidor LDAP existente disponible.

El archivo /etc/postfix/ldap-aliases.cf

El archivo /etc/postfix/ldap-aliases.cf puede especificar diversos parámetros, incluyendo parámetros que habilitan LDAP SSL y STARTTLS. Para mas información vea la página de manual ldap_table(5).

Para más información sobre LDAP,vea OpenLDAP.

Sendmail

El propósito central de Sendmail, como otros MTAs, es transferir con seguridad correo electrónico entre hosts, normalmente usando el protocolo SMTP. Tenga en cuenta que Sendmail se considera obsoleto y se anima a los usuarios o utilizar Postfix cuando sea posible. Vea Postfix para más información.

Propósito y Limitaciones

Es importante tener en cuenta lo que Sendmail es y lo que hace, como oposición a lo que no. En esto días de aplicaciones monolíticas que cumplen múltiples papeles, Sendmail puede parecer la única aplicación necesaria para correr un servidor de correo electrónico en una organización. Técnicamente, esto es verdad, puesto que Sendmail puede poner en cola el correo en el directorio de cada usuario y entregar correo saliente para los usuarios. Sin embargo, la mayoría de los usuarios requieren actualmente mucho más que una sencilla entrega de correo electrónico. Los usuarios normalmente desean interactuar con su correo electrónico usando una MUA, que usa POP o IMAP, para descargar sus mensajes a su máquina local. O, pueden preferir una interfaz Web para tener acceso a su buzón de correo. Estas otras aplicaciones pueden trabajar en colaboración con Sendmail, pero actualmente existen por diferentes razones y pueden trabajar separadamente unos de otros.

Está más allá del alcance de esta sección ir hacia todo lo que Sendmail debería o podría estar configurado para hacer. Con, literalmente, cientos de diferentes opciones y conjuntos de reglas, se han dedicado volúmenes enteros a ayudar a explicar todo lo que se puede hacer y como corregir las cosas que van mal. Vea en Recursos Adicionales funa lista de los recursos de Sendmail.

Esta sección revisa los archivos instalados con Sendmail de forma predeterminada y revisa los cambios básicos de configuración, incluyendo como para correo electrónico no deseado (spam) y como e4xtender Sendmail con Lightweight Directory Access Protocol (LDAP).

La Instalación Predeterminada Sendmail

Con el objetivo de usar Sendmail, compruebe primero que el paquete sendmail está instalado en su sistema ejecutando como root:

~]# dnf install sendmail

Con el objetivo de configurar Sendmail, compruebe que el paquete sendmail-cf está instalado en su sistema ejecutando como root:

~]# dnf install sendmail-cf

Para más información sobre la instalación de paquetes con DNF, vea Instalando Paquetes.

Antes de usar Sendmail, se debe conmutar el MTA predeterminado desde Postfix. Para más información sobre conmutar el MTA predeterminado vea Agentes de Transporte de Correo.

El ejecutable de Sendmail es sendmail.

El archivo de configuración largo y detallado de Sendmail es /etc/mail/sendmail.cf. Evite editar el archivo sendmail.cf directamente. Para hacer cambios en la configuración de Sendmail, edite el archivo /etc/mail/sendmail.mc, copia de seguridad del archivo /etc/mail/sendmail.cf original y utilice las siguientes alternativas para generar un nuevo archivo de configuración:

  • Use el makefile incluido en /etc/mail/ para crear un nuevo archivo de configuración /etc/mail/sendmail.cf:

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

    Todos los archivos generados en /etc/mail (archivos db) serán regenerados si es necesario. Los antiguos comandos makemap son todavía utilizables. El comando make se usa automáticamente siempre que inicie o reinicie el servicio sendmail.

Más información sobre la configuración de Sendmail se puede encontrar en Cambios de Configuración Comunes en Sendmail.

Diversos archivos de configuración de Sendmail están instalados en el directorio /etc/mail/ incluyendo:

  • access — Especifica que sistemas pueden usar Sendmail para correo electrónico saliente.

  • domaintable — Especifica la asignación de nombres de dominio.

  • local-host-names — Especifica los alias para el equipo.

  • mailertable — Especifica instrucciones que anulan el enrutamiento para dominios concretos.

  • virtusertable — Especifica una forma de alias específica del dominio, lo que permite que múltiples dominios virtuales se alojen en una máquina.

Varios de los archivos de configuración en el directorio /etc/mail/, como access, domaintable, mailertable y virtusertable, deben actualmente almacenar su información en archivos de base de datos antes de que Sendmail pueda usar cualquier cambio de configuración. Para incluir cualquier cambio hecho en estas configuraciones en su archivo de base de datos, ejecute los siguiente comandos como root:

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

Esto actualizará virtusertable.db, access.db, domaintable.db, mailertable.db, sendmail.cf y submit.cf.

Para actualizar todos los archivos de base de datos listados arriba y para actualizar un archivo de base de datos personal, use un comando con el siguiente formato:

make name.db all

donde name representa el nombre del archivo de base de datos personal a ser actualizado.

Para actualizar una única base de datos, use un comando con el siguiente formato:

make name.db

donde name.db representa el nombre del archivo de base de datos a ser actualizado.

También puede reiniciar el servicio sendmail para que los cambios tengan efecto ejecutando:

~]# systemctl restart sendmail

Por ejemplo para tener todos los correos electrónicos dirigidos al dominio example.com entregados a bob@other-example.com, añada la siguiente línea al archivo virtusertable:

@example.com bob@other-example.com

Para finalizar el cambio, el archivo virtusertable.db debe ser actualizado:

~]# make virtusertable.db all

Al usar la opción all conseguirá que virtusertable.db y access.db sean actualizados a la vez.

Cambios Comunes de Configuración en Sendmail

Cuando se altera el archivo de configuración de Sendmail, es mejor no editar un archivo existente sino generar jun archivo `/etc/mail/sendmail.cf`enteramente nuevo.

Haga copia de seguridad del archivo sendmail.cf antes de cambiar su contenido

Antes de reemplazar o hacer cualquier cambio en el archivo sendmail.cf, cree una copia de respaldo.

Para añadir la funcionalidad deseada a Sendmail, edite el archivo /etc/mail/sendmail.mc como root. Una vez haya terminado. reinicie el servicio sendmail y si está instalado el paquete m4, el procesador de macro m4 generará automáticamente un nuevo archivo de configuración sendmail.cf:

~]# systemctl restart sendmail
Configurar Sendmail como servidor para otros clientes

El archivo predeterminado sendmail.cf`no permite a Sendmail aceptar conexiones de red de cualquier otro equipo que no sea el ordenador local. Para configurar Sendmail como servidor para otros clientes, edite el archivo `/etc/mail/sendmail.mc y cambie la dirección especificada en la opción Addr= de la directiva DAEMON_OPTIONS de 127.0.0.1 a la dirección IP de un dispositivo de red activo o comente la directiva DAEMON_OPTIONS toda entera para situar dnl al principio de la línea. Cuando termina regenere /etc/mail/sendmail.cf reiniciando el servicio:

~]# systemctl restart sendmail

La configuración predeterminada en Fedora trabaja con la mayoría de los sitios solo SMTP. Sin embargo, no trabaja para los sitios UUCP (UNIX-to-UNIX Copy Protocol). Si está usando transferencias de correo UUCP, se debe volver a configurar el archivo /etc/mail/sendmail.mc y se debe generar un nuevo archivo /etc/mail/sendmail.cf.

Consulte el archivo /usr/share/sendmail-cf/README antes de editar cualquier archivo en los directorios bajo el directorio i`/usr/share/sendmail-cf/` ya que puede afectar a la futura configuración del archivo /etc/mail/sendmail.cf.

Enmascarar

Un configuración común de Sendmail es tener una única máquina actuando como pasarela de correo para todas las máquinas en la red. Por ejemplo, una compañía puede desear tener una máquina llamada mail.example.com que maneja todo su correo electrónico y asigna una dirección de devolución consistente a todo el correo saliente.

En esta situación, el servidor Sendmail debe enmascarar los nombres de las máquinas en la red de la compañía de manera que su dirección de retorno es user@example.com en lugar de user@host.example.com.

Para hacer esto añada las siguientes líneas a /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

Después genere un nuevo archivo sendmail.cf usando el procesador de macro m4, esta configuración hace que todo el correo de dentro de la red aparezca como si fuera enviado desde example.com.

Detener el Correo no Deseado (Spam)

El correo spam puede ser definido como correo electrónico innecesario y no deseado recibido por un usuario que nunca ha pedido la comunicación. Es un abuso disruptivo, costoso y generalizado de los estándares de comunicación de Internet.

Sendmail hace relativamente fácil bloquear las nuevas técnicas de spam que están siendo empleadas para enviar correo electrónico no deseado. Incluso bloquea muchos de los métodos más usuales de spam de forma predeterminada. Las principales funciones antispam disponibles en sendmail son header checks, relaying denial (predeterminado desde la versión 8.9), access database y sender information checks.

Por ejemplo, el reenvío de mensajes SMTP, también llamado retransmisión, ha sido deshabilitado de forma predeterminada desde Sendmail versión 8.9. Antes de que sucediera este cambio, Sendmail dirigia todo el correo del host (x.edu) a aceptar mensajes de una parte (y.com) y enviarlo a una parte diferente (z.net). Ahora, sin embargo, Sendmail debe ser configurado para permitir que cualquier dominio retransmita correo a través del servidor. Para configurar dominios de retransmisión edite el archivo /etc/mail/relay-domains y reinicie Sendmail

~]# systemctl restart sendmail

Sin embargo los usuarios pueden también enviar spam desde los servidores en Internet. En estos casos, las funciones de control de acceso de Sendmail disponibles a través del archivo /etc/mail/access se pueden usar para evitar conexiones desde equipos no deseados. El siguiente ejemplo ilustra como este archivo puede ser usado para bloquear y permitir específicamente el acceso al servidor Sendmail:

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

Este ejemplo muestra que cualquier correo electrónico enviado desde badspammer.com es bloqueado con un error 550 compatible con el RFC-821, con un mensaje enviado de vuelta. El correo electrónico enviado desde el subdominio tux.badspammer.com es aceptado. La última línea muestra que cualquier correo electrónico enviado desde la red 10.0.. se puede retransmitir a través del servidor de correo.

Ya que el archivo /etc/mail/access.db es una base de datos, use el comando makemap para actualizar cualquier cambio. Haga esto usando el siguiente comando como 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 Spam Filters 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 Common Sendmail Configuration Changes for instructions.

Para más información sobre LDAP,vea 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

Para más información sobre la instalación de paquetes con DNF, vea Instalando Paquetes.

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

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

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

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

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

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 Rawhide 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 Recipe 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 Special Conditions and Actions 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

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

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 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

Para más información sobre la instalación de paquetes con DNF, vea Instalando Paquetes.

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

Para más información sobre la instalación de paquetes con DNF, vea Instalando Paquetes.

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.