Clicky

Genera certificados seguros con Let"™s Encrypt

SSL Labs vistaalmar.es

Certificados SSL/TLS gratis para todos

Ejemplos de configuración para un servidor Apache sobre CentOS 6.7

Para cualquier comunicación protegida TLS es un certificado de clave pública que demuestra que el servidor con el que estás hablando es en realidad el servidor con que tratabas de hablar. Es decir, tu conexión con el sitio web es privada.

Como hemos visto en anteriores artículos, Let"™s Encrypt es una nueva autoridad de certificación gratuita construida sobre una base de cooperación y apertura que permite a todos nuestros dominios estar en funcionamiento con certificados de servidor básicos a través de un sencillo proceso de un solo clic (cuando se lance públicamente este próximo jueves 3 de diciembre).

En este artículo vamos a ver como configurar los cerfificados SSL/TLS, mediante la Beta privada a través de invitación, en un servidor CentOS 6.7 (Community ENTerprise Operating System) con Apache 2.2.15 y PhP 5.4.45 para dos sitios corriendo con Joomla! alojados en el mismo servidor: https://www.vistaalmar.es y https://pirman.es (si os dais cuenta las URLs ya tienen la "s" final en https:// ya que los acabo de configurar estos últimos días).

El proceso, para no mentir, es algo engorroso hasta que el servidor esté configurado con los requisitos que requiere Let"™s Encrypt, pero la posterior generación de los certificados es bastante sencilla. Lee también: Eliminar las URLs no seguras en el contenido mixto HTTP/HTTPS

Instalando Phython 2.7

En primer lugar Let"™s Encrypt requiere para su funcionamiento que el servidor tenga instalada la versión 2.7 de Phython en lugar de Phython 2.6.6 que es la última versión estable para máquinas Red Hat/CentOS 6.7. Pero el sistema requiere para su correcto funcionamiento que también esté la versión más antigua, así que deberemos instalar Phython 2.7 de un un modo que podamos ejecutarlo independientemente.

NOTA: Doy por sentado que el servidor ya tiene instalado el mod_ssl para Apache (yum install mod_ssl) y OpenSSL (yum install openssl).

Para ver paso a paso la instalación de Phython 2.7 ir a este enlace: Python 2.7 en CentOS 6 con mod_wsgi

Es posible que al inciar Let"™s Encrypt se produzcan diversos errores con módulos de Phython necesarios y habrá que ir instalándolos uno a uno y luego importarlos.

Instalación de Let"™s Encrypt

NOTA: Para la instalación de Let"™s Encrypt debes tener habilitado en CentOS en repositorio de EPEL.

Para utilizar el cliente oficial de Let"™s Encrypt y obtener sus certificados reales, tendrás que proporcionar la dirección URL de la API de producción (https://acme-v01.api.letsencrypt.org/directory) en la línea de comandos.

En primer lugar, instala Git y ejecuta los siguientes comandos:

# git clone https://github.com/letsencrypt/letsencrypt
# cd letsencrypt

Para instalar y ejecutar el cliente Let"™s Encrypt sólo tienes que escribir:

./letsencrypt-auto

Cuando se ejecuta con el cliente Python (instrucciones de instalación ( https://letsencrypt.readthedocs.org/en/latest/using.html ), asegúrate de especificar el argumento --server como se muestra a continuación:

./letsencrypt-auto --server \

Cómo utilizar el cliente Let"™s Encrypt

El cliente Let"™s Encrypt soporta un número de diferentes "plugins" que se pueden utilizar para obtener y/o instalar certificados. Unos pocos ejemplos de las opciones se incluyen a continuación.

Si estás ejecutando Apache (sólo 2.4) en un sistema operativo basado en Debian reciente, puedes probar el plugin de Apache, que automatiza tanto obtener como instalar certificados:

 ./letsencrypt-auto --apache --server https://acme-v01.api.letsencrypt.org/directory --agree-dev-preview

Para obtener un certificado utilizando un servidor web "standalone", que es el que he utilizado yo (necesitarás parar tu servidor web Apache) para https://www.vistaalmar.es y https://pirman.es :

./letsencrypt-auto certonly -a standalone \
-d example.com -d www.example.com \
--server https://acme-v01.api.letsencrypt.org/directory --agree-dev-preview

Estas son algunas pantallas de ejemplo

Let

Let

Let

letsenLet

Y la salida de la consola:

Updating letsencrypt and virtual environment dependencies.......
Running with virtualenv: /root/.local/share/letsencrypt/bin/letsencrypt certonly -a standalone -d www.vistaalmar.es --server https://acme-v01.api.letsencrypt.org/directory --agree-dev-preview
Version: 1.1-20080819
Version: 1.1-20080819
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at
/etc/letsencrypt/live/www.vistaalmar.es/fullchain.pem. Your cert
will expire on 2016-02-29. To obtain a new version of the
certificate in the future, simply run Let's Encrypt again.

Para obtener un certificado utilizando el plugin "Webroot", que puede trabajar con el Webroot de cualquier software de servidor web:

./letsencrypt-auto certonly -a webroot --webroot-path /var/www/example \
-d example.com -d www.example.com \
--server https://acme-v01.api.letsencrypt.org/directory --agree-dev-preview

Nota: Actualmente el plugin Webroot sólo puede obtener certificados de varios dominios de forma simultánea si comparten un Webroot.

Para recibir instrucciones para el proceso (bastante complejo) de obtener un certificado Let"™s Encrypt proporcionando manualmente a prueba el control de un dominio:

./letsencrypt-auto certonly -a manual -d example.com \
--server https://acme-v01.api.letsencrypt.org/directory --agree-dev-preview

Si estás utilizando un cliente ACME diferente, asegúrate de configurarlo para que utilice la URL de producción con el fin de obtener certificados válidos. Muchos clientes tendrán por defecto la URL puesta en escena.

Uso de los certificados por Apache web server

Además de tener los certificados los debes colocar en tu sistema. En el caso de CentOS 6.7 hay dos archivos que debes configurar /etc/httpd/conf/httpd.conf y /etc/httpd/confd/ssl.conf

En el archivo httpd.conf debes añadir a tu servidor virtual uno nuevo en el puerto 443. Para el ejemplo real estos son los virtual server:

NameVirtualHost 46.105.123.120:443
<VirtualHost 46.105.123.120:443>
ServerName vistaalmar.es
ServerAlias www.vistaalmar.es
DocumentRoot /home/vistaalmar/public_html
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /home/vistaalmar/public_html>
Options -Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/www.vistaalmar.es/cert.pem
SSLCertificateChainFile /etc/letsencrypt/live/www.vistaalmar.es/chain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/www.vistaalmar.es/privkey.pem
SSLCACertificateFile /etc/letsencrypt/live/www.vistaalmar.es/fullchain.pem
SSLProtocol all -SSLv2 -SSLv3
SSLHonorCipherOrder on
</VirtualHost>
<VirtualHost 46.105.123.120:443>
ServerName pirman.es
ServerAlias www.pirman.es
DocumentRoot /home/videosvirales/public_html
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /home/videosvirales/public_html>
Options -Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/www.vistaalmar.es/cert.pem
SSLCertificateChainFile /etc/letsencrypt/live/www.vistaalmar.es/chain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/www.vistaalmar.es/privkey.pem
SSLCACertificateFile /etc/letsencrypt/live/www.vistaalmar.es/fullchain.pem
SSLProtocol all -SSLv2 -SSLv3
SSLHonorCipherOrder on
</VirtualHost>

Si quieres que se redirija automáticamente de http a https deberás colocar la siguiente línea en servidor virtual del puerto 80:

Redirect "/" "https://www.example.com/"

Este es archivo ssl.conf completo de configuración que tengo yo en este momento con los dos sitios funcionando sin problemas:

#
# This is the Apache server configuration file providing SSL support.
# It contains the configuration directives to instruct the server how to
# serve pages over an https connection. For detailing information about these
# directives see <URL:http://httpd.apache.org/docs/2.2/mod/mod_ssl.html>
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
LoadModule ssl_module modules/mod_ssl.so
#
# When we also provide SSL we have to listen to the
# the HTTPS port in addition.
#
Listen 443
##
## SSL Global Context
##
## All SSL configuration in this context applies both to
## the main server and all SSL-enabled virtual hosts.
##
# Pass Phrase Dialog:
# Configure the pass phrase gathering process.
# The filtering dialog program (`builtin' is a internal
# terminal dialog) has to provide the pass phrase on stdout.
SSLPassPhraseDialog builtin
SSLHonorCipherOrder on
# Inter-Process Session Cache:
# Configure the SSL Session Cache: First the mechanism
# to use and second the expiring timeout (in seconds).
SSLSessionCache shmcb:/var/cache/mod_ssl/scache(512000)
SSLSessionCacheTimeout 300
# Semaphore:
# Configure the path to the mutual exclusion semaphore the
# SSL engine uses internally for inter-process synchronization.
SSLMutex default
# Pseudo Random Number Generator (PRNG):
# Configure one or more sources to seed the PRNG of the
# SSL library. The seed data should be of good random quality.
# WARNING! On some platforms /dev/random blocks if not enough entropy
# is available. This means you then cannot use the /dev/random device
# because it would lead to very long connection times (as long as
# it requires to make more entropy available). But usually those
# platforms additionally provide a /dev/urandom device which doesn't
# block. So, if available, use this one instead. Read the mod_ssl User
# Manual for more details.
### SSLRandomSeed startup file:/dev/urandom 256
### SSLRandomSeed connect builtin
#SSLRandomSeed startup file:/dev/random 512
#SSLRandomSeed connect file:/dev/random 512
#SSLRandomSeed connect file:/dev/urandom 512
SSLRandomSeed startup builtin
SSLRandomSeed startup file:/dev/urandom 512
SSLRandomSeed connect builtin
SSLRandomSeed connect file:/dev/urandom 512
#
# Some MIME-types for downloading Certificates and CRLs
#
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl .crl
#
# Use "SSLCryptoDevice" to enable any supported hardware
# accelerators. Use "openssl engine -v" to list supported
# engine names. NOTE: If you enable an accelerator and the
# server does not start, consult the error logs and ensure
# your accelerator is functioning properly.
#
SSLCryptoDevice builtin
#SSLCryptoDevice ubsec
##
## SSL Virtual Host Context
##
<VirtualHost _default_:443>
# General setup for the virtual host, inherited from global configuration
#DocumentRoot "/var/www/html"
#ServerName www.example.com:443
#ServerName pirman.es:443
# Use separate log files for the SSL virtual host; note that LogLevel
# is not inherited from httpd.conf.
ErrorLog logs/ssl_error_log
TransferLog logs/ssl_access_log
LogLevel warn
# SSL Engine Switch:
# Enable/Disable SSL for this virtual host.
SSLEngine on
# SSL Protocol support:
# List the enable protocol levels with which clients will be able to
# connect. Disable SSLv2 access by default:
SSLProtocol all -SSLv2 -SSLv3 -TLSv1
# SSL Cipher Suite:
# List the ciphers that the client is permitted to negotiate.
# See the mod_ssl documentation for a complete list.
#### SSLCipherSuite DEFAULT:!EXP:!SSLv2:!DES:!IDEA:!SEED:+3DES
SSLCipherSuite HIGH:!aNULL
SSLCertificateFile /etc/letsencrypt/live/www.vistaalmar.es/cert.pem
SSLCertificateChainFile /etc/letsencrypt/live/www.vistaalmar.es/chain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/www.vistaalmar.es/privkey.pem
SSLCACertificateFile /etc/letsencrypt/live/www.vistaalmar.es/fullchain.pem
# Server Certificate:
# Point SSLCertificateFile at a PEM encoded certificate. If
# the certificate is encrypted, then you will be prompted for a
# pass phrase. Note that a kill -HUP will prompt again. A new
# certificate can be generated using the genkey(1) command.
### SSLCertificateFile /etc/pki/tls/certs/localhost.crt
# Server Private Key:
# If the key is not combined with the certificate, use this
# directive to point at the key file. Keep in mind that if
# you've both a RSA and a DSA private key you can configure
# both in parallel (to also allow the use of DSA ciphers, etc.)
### SSLCertificateKeyFile /etc/pki/tls/private/localhost.key
# Server Certificate Chain:
# Point SSLCertificateChainFile at a file containing the
# concatenation of PEM encoded CA certificates which form the
# certificate chain for the server certificate. Alternatively
# the referenced file can be the same as SSLCertificateFile
# when the CA certificates are directly appended to the server
# certificate for convinience.
#SSLCertificateChainFile /etc/pki/tls/certs/server-chain.crt
# Certificate Authority (CA):
# Set the CA certificate verification path where to find CA
# certificates for client authentication or alternatively one
# huge file containing all of them (file must be PEM encoded)
#SSLCACertificateFile /etc/pki/tls/certs/ca-bundle.crt
# Client Authentication (Type):
# Client certificate verification type and depth. Types are
# none, optional, require and optional_no_ca. Depth is a
# number which specifies how deeply to verify the certificate
# issuer chain before deciding the certificate is not valid.
#SSLVerifyClient require
#SSLVerifyDepth 10
# Access Control:
# With SSLRequire you can do per-directory access control based
# on arbitrary complex boolean expressions containing server
# variable checks and other lookup directives. The syntax is a
# mixture between C and Perl. See the mod_ssl documentation
# for more details.
#<Location />
#SSLRequire ( %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
# and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
# and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
# and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
# and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20 ) \
# or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
#</Location>
# SSL Engine Options:
# Set various options for the SSL engine.
# o FakeBasicAuth:
# Translate the client X.509 into a Basic Authorisation. This means that
# the standard Auth/DBMAuth methods can be used for access control. The
# user name is the `one line' version of the client's X.509 certificate.
# Note that no password is obtained from the user. Every entry in the user
# file needs this password: `xxj31ZMTZzkVA'.
# o ExportCertData:
# This exports two additional environment variables: SSL_CLIENT_CERT and
# SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
# server (always existing) and the client (only existing when client
# authentication is used). This can be used to import the certificates
# into CGI scripts.
# o StdEnvVars:
# This exports the standard SSL/TLS related `SSL_*' environment variables.
# Per default this exportation is switched off for performance reasons,
# because the extraction step is an expensive operation and is usually
# useless for serving static content. So one usually enables the
# exportation for CGI and SSI requests only.
# o StrictRequire:
# This denies access when "SSLRequireSSL" or "SSLRequire" applied even
# under a "Satisfy any" situation, i.e. when it applies access is denied
# and no other module can change it.
# o OptRenegotiate:
# This enables optimized SSL connection renegotiation handling when SSL
# directives are used in per-directory context.
#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
<Files ~ "\.(cgi|shtml|phtml|php3?)$">
SSLOptions +StdEnvVars
</Files>
<Directory "/var/www/cgi-bin">
SSLOptions +StdEnvVars
</Directory>
# SSL Protocol Adjustments:
# The safe and default but still SSL/TLS standard compliant shutdown
# approach is that mod_ssl sends the close notify alert but doesn't wait for
# the close notify alert from client. When you need a different shutdown
# approach you can use one of the following variables:
# o ssl-unclean-shutdown:
# This forces an unclean shutdown when the connection is closed, i.e. no
# SSL close notify alert is send or allowed to received. This violates
# the SSL/TLS standard but is needed for some brain-dead browsers. Use
# this when you receive I/O errors because of the standard approach where
# mod_ssl sends the close notify alert.
# o ssl-accurate-shutdown:
# This forces an accurate shutdown when the connection is closed, i.e. a
# SSL close notify alert is send and mod_ssl waits for the close notify
# alert of the client. This is 100% SSL/TLS standard compliant, but in
# practice often causes hanging connections with brain-dead browsers. Use
# this only for browsers where you know that their SSL implementation
# works correctly.
# Notice: Most problems of broken clients are also related to the HTTP
# keep-alive facility, so you usually additionally want to disable
# keep-alive for those clients, too. Use variable "nokeepalive" for this.
# Similarly, one has to force some clients to use HTTP/1.0 to workaround
# their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
# "force-response-1.0" for this.
SetEnvIf User-Agent ".*MSIE.*" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
# Per-Server Logging:
# The home of a custom SSL log file. Use this when you want a
# compact non-error SSL logfile on a virtual host basis.
CustomLog logs/ssl_request_log \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>

Ayuda y problemas conocidos

Puedes obtener ayuda con el cliente y Let"™s Encrypt en:

https://community.letsencrypt.org/

Problemas conocidos con el cliente Python pueden ser rastreados aquí:

https://github.com/letsencrypt/letsencrypt/issues

Renovaciones y validez

Los certificados de Let"™s Encrypt tienen una validez de 90 días. Recomiendan renovar cada 60 días para proporcionar un buen margen de error. Como participante beta, se debe estar preparado para renovar manualmente los certificados en ese momento. A medida que nos acercamos a la disponibilidad general, esperamos contar con la renovación automática probada y trabajando en más plataformas, pero por ahora, por favor, jugar a lo seguro y realiza un seguimiento.

Limitación de la velocidad

Durante esta prueba beta Let"™s Encrypt tiene limitada la velocidad muy ajustada en su lugar. Pero tienen la intención de aflojar estos límites a medida que avanza la beta.

Hay dos límites de la frecuencia en juego: Inscripciones/dirección IP, y Certificados/Dominio.

Inscripciones/dirección IP limita el número de registros que puede hacerse en un día determinado; Actualmente 10. Esto significa que se debes evitar la supresión de la carpeta /etc/letsencrypt/account, o puede que no seas capaz de volver a registrarte.

Certificados/Dominio podría llegar a través de la re-emisión repetida. Este límite mide los certificados emitidos por una determinada combinación de Dominio de Nivel Superior + Dominio. Esto significa que si emites los certificados para los siguientes dominios, al final tendrías lo que consideran 4 certificados para el dominio example.com.

1. www.example.com
2. example.com www.example.com
3. webmail.example.com ldap.example.com
4. example.com www.example.com

El límite en Certificados/Dominio tiene una ventana de 60 días, para dar 30 días para las renovaciones. Let"™s Encrypt sabe que en la actualidad es restrictiva, pero Let"™s Encrypt agradece la paciencia en ayudar a asegurar que está listo para el mundo entero.

Transparencia del certificado

Parte de la misión de Let"™s Encrypt incluye dar pubblicidad a la transparencia de los certificados que emiten a través de Certificado de Transparencia. La dirección de correo electrónico facilitada no se da a conocer públicamente.

Información útil

Eventos de Let"™s Encrypt se publican en https://letsencrypt.status.io/ y Twitter (letsencrypt_ops). Si necesitas ayuda comunitaria de Let"™s Encrypt https://community.letsencrypt.org/ y #letsencrypt en irc.freenode.org son excelentes fuentes de asistencia.

Si hay actualizaciones para los participantes del programa Beta, que se publicarán en el sitio de la comunidad en https://community.letsencrypt.org/t/beta-program-announcements/1631.

Jesus_Caceres