martes, 28 de septiembre de 2010

Instalación de un servidor de correo (parte 4)

Hasta ahora, hemos completado la instalación de un servidor de correo que nos permite enviar y recibir mensajes de Internet utilizando un lector de correo desde nuestra estación de trabajo, este sirve muy bien si solo requerimos conectarnos a él desde una red local privada, pero si además de eso requerimos conectarnos desde cualquier nodo en Internet representa un riesgo de seguridad el iniciar sesión en el servidor desde cualquier sitio ya que es posible rastrear los datos y descubrir sin mucho esfuerzo cuentas y contraseñas, además de eso, si damos de alta IP’s externas para el relay, nada nos garantiza que estas mismas direcciones no puedan ser utilizadas con fines nocivos.

Es por todo esto que al extender del uso de nuestro servidor a direcciones fuera de nuestra organización, debemos adoptar un esquema de seguridad basado en la encriptación de datos y en la autentificación del usuario. Vamos a ver una forma muy sencilla para lograr esto que, aunque es sencilla, es suficientemente robusta para mantener un nivel de seguridad muy aceptable.

La forma en la que este esquema de seguridad trabaja consiste en dos partes:

  • La transmisión de datos entre el software cliente y el servidor será encriptada empleando el protocolo TLS/SSL.
  • Tanto para el servicio de envío como de recepción el cliente proporcionará un usuario y una contraseña.

El tipo de autentificación que utilizaremos será el llamado “plano” (plaintext), en algunos sitios mencionan que esto no es seguro, lo cual, no es del todo cierto, al estar cifrada la comunicación entre cliente y servidor, los datos de usuario y contraseña permanecen cifrados también, por lo que no presenta riesgo, siempre y cuando nuestros usuarios configuren correctamente su servicio de correo en su lector de mensajes.

Para poder activar estas funcionalidades es necesario tener instalado en nuestro servidor el OpenSSL y el Cyrus-SASL

En mi caso, en que estoy utilizando Ubuntu, por medio del apt, instalé los siguientes paquetes: libssl-dev, libssl0.9.8, openssl, libsasl2-2, libsasl2-dev, libsasl2-modules y sasl2-bin.

sudo aptitude install libssl-dev libssl0.9.8 openssl libsasl2-2 libsasl2-dev libsasl2-modules sasl2-bin

Nota: Para este tutorial me estoy basando por completo en SASL versión 2

Lo primero que vamos a hacer es activar el SSL en dovecot así que revisamos si fue compilado con el soporte a SSL por medio del parámetro –build-options

/usr/local/sbin/dovecot --build-options
Build options: ioloop=epoll notify=inotify ipv6 openssl io_block_size=8192
Mail storages: cydir maildir mbox mdbox raw sdbox shared
SQL drivers:
Passdb: checkpassword pam passwd passwd-file shadow
Userdb: checkpassword nss passwd prefetch passwd-file

En caso de que no presente openssl dentro de las opciones de compilación, vamos a recompilarlo, esta vez, asegurándonos que utilice el OpenSSL, desde el directorio con los archivos de instalación:

make clean
./configure --sysconfdir=/etc --with-ssl
make
sudo make install

Nota: Generalmente, la compilación la hago con un usuario sin privilegios y la instalación, al requerir la cuenta root, la hago con el comando sudo. Sin embargo es posible hacerlo todo con root.

Una vez instalado el dovecot con soporte para SSL, vamos a crear 2 certificados que vamos a necesitar para la encriptación.

Voy a explicar de forma muy breve cómo hacer certificados, en una entrada posterior, en la que explique como activar el SSL en Apache, explicaré de una forma más amplia como crear estos certificados.

Vamos crear un directorio de trabajo, podemos llamarle como nos guste, en mi caso, lo llamaré certs

mkdir certs
cd certs

Dentro de este directorio, vamos a crear los siguientes subdirectorios y archivos:

mkdir demoCA
mkdir demoCA/newcerts
mkdir demoCA/private
demoCA/index.txt
echo 01 > demoCA/serial

Creamos una llave RSA:

openssl genrsa -out demoCA/private/cakey.pem 1024
Generating RSA private key, 1024 bit long modulus
.++++++
................................++++++
e is 65537 (0x10001)

Generamos un certificado x509 para firmar certificados como CA.

openssl req -new -key demoCA/private/cakey.pem -x509 -out demoCA/cacert.pem
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
MX
State or Province Name (full name) [Some-State]:
Queretaro
Locality Name (eg, city) []:Queretaro
Organization Name (eg, company) [Internet Widgits Pty Ltd]:unixymas.com.mx
Organizational Unit Name (eg, section) []:
Common Name (eg, YOUR name) []:
unixymas.com.mx
Email Address []:webmaster@unixymas.com.mx

Generamos otra llave para el certificado para nuestro servidor:

openssl genrsa -out key.pem 1024
Generating RSA private key, 1024 bit long modulus
...++++++
......................................++++++
e is 65537 (0x10001)

Creamos una solicitud de certificado:

openssl req -new -key key.pem -out req.pem
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:MX
State or Province Name (full name) [Some-State]:Queretaro
Locality Name (eg, city) []:Queretaro
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
unixymas.com.mx
Organizational Unit Name (eg, section) []:
Common Name (eg, YOUR name) []:unixymas.com.mx
Email Address []:webmaster@unixymas.com.mx

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Y la firmamos:

openssl ca -in req.pem -key key.pem -out cert.pem
Using configuration from /usr/lib/ssl/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Sep 28 23:13:33 2010 GMT
            Not After : Sep 28 23:13:33 2011 GMT
        Subject:
            countryName               = MX
            stateOrProvinceName       = Queretaro
            organizationName          = unixymas.com.mx
            commonName                = unixymas.com.mx
            emailAddress              = webmaster@unixymas.com.mx
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                D3:EF:80:66:10:6C:37:61:0A:54:5B:17:47:15:CF:75:05:52:C0:9A
            X509v3 Authority Key Identifier:
                keyid:32:84:3B:C2:B8:44:2C:06:5D:40:10:7D:F4:CC:13:8E:2D:79:E7:6B

Certificate is to be certified until Sep 28 23:13:33 2011 GMT (365 days)
Sign the certificate? [y/n]:y

1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

Ahora con root copiamos los siguientes archivos:

cp cert.pem /etc/ssl/certs/dovecot.pem
cp key.pem /etc/ssl/private/dovecot.pem
cp demoCA/cacert.pem /etc/ssl/certs/cacert.pem

Y cambiamos los siguientes permisos:

chmod 600 /etc/ssl/private/dovecot.pem

En el directorio /etc/dovecot/conf.d creamos o modificamos el archivo 10-ssl.conf

##
## SSL settings
##

# SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt>
ssl = yes

# PEM encoded X.509 SSL/TLS certificate and private key. They're opened before
# dropping root privileges, so keep the key file unreadable by anyone but
# root. Included doc/mkcert.sh can be used to easily generate self-signed
# certificate, just make sure to update the domains in dovecot-openssl.cnf
ssl_cert = </etc/ssl/certs/dovecot.pem
ssl_key = </etc/ssl/private/dovecot.pem

# If key file is password protected, give the password here. Alternatively
# give it when starting dovecot with -p parameter. Since this file is often
# world-readable, you may want to place this setting instead to a different
# root owned 0600 file by using ssl_key_password = <path.
#ssl_key_password =

# PEM encoded trusted certificate authority. Set this only if you intend to use
# ssl_verify_client_cert=yes. The file should contain the CA certificate(s)
# followed by the matching CRL(s). (e.g. ssl_ca = </etc/ssl/certs/ca.pem)
ssl_ca = </etc/ssl/certs/cacert.pem

# Request client to send a certificate. If you also want to require it, set
# auth_ssl_require_client_cert=yes in auth section.
ssl_verify_client_cert = yes

# Which field from certificate to use for username. commonName and
# x500UniqueIdentifier are the usual choices. You'll also need to set
# auth_ssl_username_from_cert=yes.
#ssl_cert_username_field = commonName

# How often to regenerate the SSL parameters file. Generation is quite CPU
# intensive operation. The value is in hours, 0 disables regeneration
# entirely.
#ssl_parameters_regenerate = 168

# SSL ciphers to use
#ssl_cipher_list = ALL:!LOW:!SSLv2:!EXP:!aNULL

En el archivo /etc/dovecot/dovecot.conf eliminamos la línea ssl = no y, por último, iniciamos el dovecot

/usr/local/sbin/dovecot

Ahora vamos a trabajar con el sendmail, verificamos si ya tiene activas las opciones STARTTLS y SASL

/usr/sbin/sendmail -d0 < /dev/null
Version 8.14.4
Compiled with: DNSMAP LOG MATCHGECOS MILTER MIME7TO8 MIME8TO7
                NAMED_BIND NETINET NETUNIX NEWDB PIPELINING SASLv2 SCANF
                STARTTLS USERDB XDEBUG

============ SYSTEM IDENTITY (after readcf) ============
      (short domain name) $w = ubuntu
  (canonical domain name) $j = ubuntu.unixymas.com.mx
         (subdomain name) $m = unixymas.com.mx
              (node name) $k = ubuntu
========================================================

Recipient names must be specified

En caso de que no, que es lo mas probable, vamos a activarlas y recompilar.

Nuevamente en nuestros archivos de instalación vamos a crear el archivo devtools/Site/site.config.m4 con el siguiente contenido:

APPENDDEF(`confENVDEF', `-DSASL=2')
APPENDDEF(`confLIBS', `-lsasl2')
APPENDDEF(`confENVDEF',`-DSTARTTLS')
APPENDDEF(`confLIBS', `-lssl -lcrypto')
APPENDDEF(`confLIBDIRS', `-L/usr/local/lib -L/usr/lib/sasl2')dnl
APPENDDEF(`confINCDIRS', `-I/usr/local/include')dnl

Recompilamos e instalamos:

sh ./Build clean
sh ./Build -c
sudo sh ./Build install

Nota: La opción –c en Build indica que hubo cambio en la configuración, si olvidamos incluirla compilará nuevamente con la configuración anterior.

En el subdirectorio cf/cf dejamos el archivo sendmail.mc con el siguiente contenido:

divert(-1)
#
# Copyright (c) 1998, 1999 Sendmail, Inc. and its suppliers.
#       All rights reserved.
# Copyright (c) 1983 Eric P. Allman.  All rights reserved.
# Copyright (c) 1988, 1993
#       The Regents of the University of California.  All rights reserved.
#
# By using this file, you agree to the terms and conditions set
# forth in the LICENSE file which can be found at the top level of
# the sendmail distribution.
#
#

#
#  This is a generic configuration file for Linux.
#  It has support for local and SMTP mail only.  If you want to
#  customize it, copy it to a name appropriate for your environment
#  and do the modifications there.
#

divert(0)dnl
VERSIONID(`$Id: generic-linux.mc,v 8.1 1999/09/24 22:48:05 gshapiro Exp $')
OSTYPE(linux)dnl
DOMAIN(generic)dnl
MASQUERADE_AS(`unixymas.com.mx')dnl
FEATURE(`allmasquerade')dnl
FEATURE(`masquerade_envelope')dnl
FEATURE(`access_db')dnl
define(`confCACERT_PATH', `/etc/mail/certs')dnl
define(`confCACERT', `/etc/mail/certs/cacert.pem')dnl
define(`confSERVER_CERT', `/etc/mail/certs/cert.pem')dnl
define(`confSERVER_KEY', `/etc/mail/certs/key.pem')dnl
define(`confCLIENT_CERT', `/etc/mail/certs/cert.pem')dnl
define(`confCLIENT_KEY', `/etc/mail/certs/key.pem')dnl
define(`confAUTH_OPTIONS', `A')dnl
define(`confAUTH_MECHANISMS', `PLAIN LOGIN')dnl
TRUST_AUTH_MECH(`PLAIN LOGIN')dnl
MAILER(local)dnl
MAILER(smtp)dnl

Nota: La característica (feature) confAUTH_OPTIONS es muy importante y curiosamente en pocos sitios en Internet se menciona, sin esta característica, el sendmail, simplemente no hace la validación de la cuenta para permitir el relay.

Compilamos el archivo y lo copiamos a /etc/mail

cd cf/cf
sh ./Build sendmail.cf
sudo cp sendmail.cf /etc/mail/sendmail.cf

Con root, creamos el subdirectorio /etc/mail/certs y copiamos los certificados cacert.pem y cert.pem y la llave key.pem con permisos solo para root, podemos usar los mismos certificados para el dovecot u otros.

cp cert.pem /etc/mail/certs/cert.pem
cp key.pem /etc/mail/certs/key.pem
cp demoCA/cacert.pem /etc/mail/certs/cacert.pem
chmod 600 /etc/mail/certs/key.pem

Antes de iniciar el sendmail, necesitamos configurar el SASL, el archivo /etc/default/saslauthd principalmente modificaremos a START=yes y nos aseguraremos que MECHANISM sea igual a “pam”, quedará así:

#
# Settings for saslauthd daemon
# Please read /usr/share/doc/sasl2-bin/README.Debian for details.
#

# Should saslauthd run automatically on startup? (default: no)
START=yes

# Description of this saslauthd instance. Recommended.
# (suggestion: SASL Authentication Daemon)
DESC="SASL Authentication Daemon"

# Short name of this saslauthd instance. Strongly recommended.
# (suggestion: saslauthd)
NAME="saslauthd"

# Which authentication mechanisms should saslauthd use? (default: pam)
#
# Available options in this Debian package:
# getpwent  -- use the getpwent() library function
# kerberos5 -- use Kerberos 5
# pam       -- use PAM
# rimap     -- use a remote IMAP server
# shadow    -- use the local shadow password file
# sasldb    -- use the local sasldb database file
# ldap      -- use LDAP (configuration is in /etc/saslauthd.conf)
#
# Only one option may be used at a time. See the saslauthd man page
# for more information.
#
# Example: MECHANISMS="pam"
MECHANISMS="pam"

# Additional options for this mechanism. (default: none)
# See the saslauthd man page for information about mech-specific options.
MECH_OPTIONS=""

# How many saslauthd processes should we run? (default: 5)
# A value of 0 will fork a new process for each connection.
THREADS=5

# Other options (default: -c -m /var/run/saslauthd)
# Note: You MUST specify the -m option or saslauthd won't run!
#
# WARNING: DO NOT SPECIFY THE -d OPTION.
# The -d option will cause saslauthd to run in the foreground instead of as
# a daemon. This will PREVENT YOUR SYSTEM FROM BOOTING PROPERLY. If you wish
# to run saslauthd in debug mode, please run it by hand to be safe.
#
# See /usr/share/doc/sasl2-bin/README.Debian for Debian-specific information.
# See the saslauthd man page and the output of 'saslauthd -h' for general
# information about these options.
#
# Example for postfix users: "-c -m /var/spool/postfix/var/run/saslauthd"
OPTIONS="-c -m /var/run/saslauthd"

Creamos el archivo /usr/lib/sasl2/Sendmail.conf (nótese la “S” mayúscula) con el siguiente contenido:

pwcheck_method: saslauthd
mech_list: login plain

Iniciamos al saslauthd:

/etc/init.d/saslauthd start

Y por último el sendmail:

/usr/sbin/sendmail –bd –q15m

Finalmente probamos, dándole un telnet al puerto 25, darle un EHLO y esperar que en su respuesta aparezca una línea que indique la capacidad STARTTLS y otra para la autentificación por contraseña plana (AUTH PLAIN LOGIN).

telnet localhost 25
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 ubuntu.unixymas.com.mx ESMTP Sendmail 8.14.4/8.14.4; Tue, 28 Sep 2010 19:51:09 -0500
ehlo unixymas.com.mx
250-ubuntu.unixymas.com.mx Hello localhost [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-EXPN
250-VERB
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-AUTH PLAIN LOGIN
250-STARTTLS
250-DELIVERBY
250 HELP

Para la configuración del lector de correo, deben activarse las características de seguridad, para el POP3 y el IMAP conexión TLS/SSL autentificación con usuario y contraseña normal y para el SMTP conexión STARTTLS y autentificación por usuario y contraseña.

No hay comentarios.: