LINUX

Cómo instalar certificados SSL Let’s Encrypt en Ubuntu 18.04

Obtener certificados SSL LetsEncrypt

Certbot es un cliente automático fácil de usar que obtiene e implementa certificados SSL / TLS para su servidor web. Es una herramienta de EFF que se utiliza para obtener certificados de Let’s Encrypt y habilitar automáticamente HTTPS en su servidor. En resumen, actúa como un «cliente Let’s Encrypt» oficial o «el cliente Let’s Encrypt Python». Utiliza el entorno de gestión de certificados automatizado (ACME) para implementar automáticamente certificados SSL gratuitos en los que confía la mayoría de los navegadores. Por lo tanto, funciona para cualquier otra CA que admita el protocolo ACME.

En este artículo, explicaré cómo obtener e instalar certificados SSL gratuitos Let’s encriptar usando Certbot para Apache y Nginx en servidores Ubuntu 18.04.

Prerrequisitos

  • Un servidor Ubuntu Bionic Beaver (18.04) con privilegios de root para instalar los paquetes necesarios según los requisitos.
  • Un dominio totalmente calificado que está registrado y tiene registros DNS adecuados. Aquí, en este artículo, estoy usando el dominio fosscloudy.com en todo momento.

Instalar Certbot

Inicialmente, para obtener los certificados SSL de Letsencrypt, necesitaremos instalar el software Certbot. Aunque Certbot está disponible en Ubuntu últimamente, los paquetes tienden a estar desactualizados allí. Por lo tanto, es recomendable utilizar los repositorios de software de Ubuntu con el software más reciente para la instalación. Puede instalar Certbot usando los siguientes comandos a continuación:

#add-apt-repository ppa:certbot/certbot
#apt update
#apt install certbot

Puede confirmar la versión de Certbot instalada con este comando a continuación:

# certbot --version
certbot 0.23.0

Además, podemos usar este comando «complementos de certbot» para conocer los complementos de Certbot disponibles instalados en su servidor.

# certbot plugins
Saving debug log to /var/log/letsencrypt/letsencrypt.log

* standalone
Description: Spin up a temporary webserver
Interfaces: IAuthenticator, IPlugin
Entry point: standalone = certbot.plugins.standalone:Authenticator

* webroot
Description: Place files in webroot directory
Interfaces: IAuthenticator, IPlugin
Entry point: webroot = certbot.plugins.webroot:Authenticator
-------------------------------------------------------------------------------

De forma predeterminada, en este paquete solo se incluirán los complementos Standalone y webroot. Según nuestro propósito, podemos habilitar todos los complementos necesarios uno por uno.

Configuración del certificado SSL Let’s Encrypt en Apache

Certbot proporciona un complemento de Apache para emitir los certificados SSL más fácilmente con esta herramienta. Podemos instalar este complemento ejecutando este comando a continuación:

#apt install python-certbot-apache

Ahora estamos listos para usar esta herramienta, pero para configurar SSL para los dominios, necesitaremos verificar algunos de los archivos de configuración de Apache. Para emitir el certificado SSL para un dominio, Certbot intentará buscar el host virtual del dominio exacto en la configuración de Apache de su servidor. Puede consultar mi artículo anterior que le ayudará a configurar un host virtual de dominio. Suponiendo, la presencia de un host virtual adecuado para nuestro dominio, podemos ejecutar este comando para instalar SSL para nuestro dominio fosscloudy.com.

# certbot --apache -d fosscloudy.com -d www.fosscloudy.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator apache, Installer apache
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for fosscloudy.com
http-01 challenge for www.fosscloudy.com
Enabled Apache rewrite module
Waiting for verification...
Cleaning up challenges
Created an SSL vhost at /etc/apache2/sites-available/fosscloudy.com-le-ssl.conf
Deploying Certificate to VirtualHost /etc/apache2/sites-available/fosscloudy.com-le-ssl.conf
Enabling available site: /etc/apache2/sites-available/fosscloudy.com-le-ssl.conf
Deploying Certificate to VirtualHost /etc/apache2/sites-available/fosscloudy.com-le-ssl.conf

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
Enabled Apache rewrite module
Redirecting vhost in /etc/apache2/sites-enabled/fosscloudy.com.conf to ssl vhost in /etc/apache2/sites-available/fosscloudy.com-le-ssl.conf

-------------------------------------------------------------------------------
Congratulations! You have successfully enabled https://fosscloudy.com and
https://www.fosscloudy.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=fosscloudy.com
https://www.ssllabs.com/ssltest/analyze.html?d=www.fosscloudy.com
-------------------------------------------------------------------------------

IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/fosscloudy.com-0002/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/fosscloudy.com-0002/privkey.pem
Your cert will expire on 2018-09-03. To obtain a new or tweaked
version of this certificate in the future, simply run certbot again
with the "certonly" option. To non-interactively renew *all* of
your certificates, run "certbot renew"
- If you like Certbot, please consider supporting our work by:

Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
Donating to EFF: https://eff.org/donate-le

El procedimiento interactivo anterior lo guiará a través de toda la información necesaria para firmar / instalar el certificado para su dominio seleccionado. Su dominio SSL se descargará, instalará y configurará correctamente en su dominio Virtual host automáticamente con la ejecución de este comando. Ahora puede acceder a su dominio con HTTPS y confirmar que funciona o verificar el estado de SSL en el verificador de SSL.

Opcionalmente, si tiene varios dominios / hosts virtuales configurados, puede usar el siguiente comando para instalar certificados SSL para ellos.

#certbot --apache

Certbot le pedirá que seleccione los dominios incluidos en el nuevo certificado.

Además, si no desea que Certbot instale / configure automáticamente su host virtual de dominio con el nuevo certificado SSL, puede usar el siguiente comando para generar el certificado SSL. Puede configurarlo manualmente más tarde.

#certbot --apache certonly

Configuración del certificado SSL Let’s Encrypt en Nginx

Para sus servidores que ejecutan el servidor web Nginx, podemos usar el complemento Certbot Nginx para obtener e instalar automáticamente los certificados SSL. Puede instalar este complemento emitiendo este comando a continuación:

#apt install python-certbot-nginx

Ahora estamos listos para usar esta herramienta, pero para configurar SSL para los dominios, necesitaremos verificar algunos de los archivos de configuración de Nginx para el mismo. Para emitir el certificado SSL para un dominio, Certbot intentará buscar el host virtual del dominio exacto en la configuración de su servidor Nginx. Suponiendo, la presencia de un host virtual adecuado para nuestro dominio, podemos ejecutar este comando para instalar SSL para nuestro dominio fosscloudy.com.

# certbot --nginx -d fosscloudy.com -d www.fosscloudy.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): admin_linoxide@gmail.com

-------------------------------------------------------------------------------
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v01.api.letsencrypt.org/directory
-------------------------------------------------------------------------------
(A)gree/(C)ancel: A

-------------------------------------------------------------------------------
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about EFF and
our work to encrypt the web, protect its users and defend digital rights.
-------------------------------------------------------------------------------
(Y)es/(N)o: N
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for fosscloudy.com
http-01 challenge for www.fosscloudy.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/fosscloudy.com.conf
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/fosscloudy.com.conf

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/fosscloudy.com.conf
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/fosscloudy.com.conf

-------------------------------------------------------------------------------
Congratulations! You have successfully enabled https://fosscloudy.com and
https://www.fosscloudy.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=fosscloudy.com
https://www.ssllabs.com/ssltest/analyze.html?d=www.fosscloudy.com
-------------------------------------------------------------------------------

IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/fosscloudy.com/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/fosscloudy.com/privkey.pem
Your cert will expire on 2018-09-03. To obtain a new or tweaked
version of this certificate in the future, simply run certbot again
with the "certonly" option. To non-interactively renew *all* of
your certificates, run "certbot renew"
- Your account credentials have been saved in your Certbot
configuration directory at /etc/letsencrypt. You should make a
secure backup of this folder now. This configuration directory will
also contain certificates and private keys obtained by Certbot so
making regular backups of this folder is ideal.
- If you like Certbot, please consider supporting our work by:

Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
Donating to EFF: https://eff.org/donate-le

Este procedimiento interactivo autoexplicativo le ayudará a generar / instalar / configurar automáticamente un certificado SSL para su dominio. Su dominio SSL se descargará, instalará y configurará correctamente en su dominio Virtual host automáticamente con la ejecución de este comando. Ahora puede acceder a su dominio con HTTPS y confirmar que funciona o verificar el estado de SSL en el verificador de SSL. Puede reemplazar mi dominio fosscloudy.com con el suyo y ejecutar el mismo comando para generar su certificado SSL.

SSL_nginx

De manera similar al complemento de Apache, si tiene varios hosts / dominios virtuales configurados, puede usar el siguiente comando para instalar certificados SSL para todos ellos.

#certbot --nginx

Certbot le pedirá que seleccione los dominios incluidos en el nuevo certificado.

Además, si no desea que Certbot instale / configure automáticamente su host virtual de dominio con el nuevo certificado SSL, puede usar el siguiente comando para generar el certificado SSL que luego puede configurar manualmente.

#certbot --nginx certonly

Configuración de certificados Let’s Encrypt Wildcard con Certbot

Let’s Encrypt ha comenzado recientemente a admitir certificados comodín utilizando su nuevo protocolo ACME2. Esto significa que puede tener un solo certificado comodín como * .fosscloudy.com y usarlo en todos los demás subdominios de dominio como docs.fosscloudy.com, blog.fosscloudy.com, mail.fosscloudy.com, etc. muy fácil de administrar certificados para los numerosos subdominios de dominio de manera eficiente. Puede generar este certificado SSL comodín para fosscloudy.com ejecutando este comando a continuación. Puede modificar este comando con su dominio preferido reemplazando fosscloudy.com.

# certbot certonly --manual -d *.fosscloudy.com --agree-tos --no-bootstrap --manual-public-ip-logging-ok --preferred-challenges dns-01 --server https://acme-v02.api.letsencrypt.org/directory
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator manual, Installer None
Obtaining a new certificate
Performing the following challenges:
dns-01 challenge for fosscloudy.com

-------------------------------------------------------------------------------
Please deploy a DNS TXT record under the name
_acme-challenge.fosscloudy.com with the following value:

z25SzIfe37x5va0ynh6KdmEYVjjuSvdUOGM_t_twsVk

Before continuing, verify the record is deployed.
-------------------------------------------------------------------------------
Press Enter to Continue
Waiting for verification...
Cleaning up challenges

IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/fosscloudy.com-0001/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/fosscloudy.com-0001/privkey.pem
Your cert will expire on 2018-09-03. To obtain a new or tweaked
version of this certificate in the future, simply run certbot
again. To non-interactively renew *all* of your certificates, run
"certbot renew"
- If you like Certbot, please consider supporting our work by:

Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
Donating to EFF: https://eff.org/donate-le

Como se menciona en este procedimiento interactivo, le pedirá que agregue un registro TXT específico a sus registros DNS. En mi caso, informó configurar el TXT de la siguiente manera:

-------------------------------------------------------------------------------
Please deploy a DNS TXT record under the name
_acme-challenge.fosscloudy.com with the following value:

z25SzIfe37x5va0ynh6KdmEYVjjuSvdUOGM_t_twsVk

Before continuing, verify the record is deployed.
-------------------------------------------------------------------------------
Press Enter to Continue

En su proveedor de DNS, creará un nuevo registro TXT de DNS con:

Record Name: _acme-challenge (you may or may not need the .fosscloudy.com suffix depending on your DNS provider.
Record Value: z25SzIfe37x5va0ynh6KdmEYVjjuSvdUOGM_t_twsVk (replace this with the value provided by Certbot)

Save your DNS settings and hit Enter in the Certbot window to trigger the check and complete the verification. You will have to wait for some time for the new DNS record to propagate over the internet. I waited for 30 minutes and pressed enter. You can even set a lower TTL value to make this process faster.

Congratulations!! The wildcard certificate for your domain fosscloudy.com is generated. Now you can use this wildcard certificate with any sub-domain you create for your domain name. For example, I’ve created a sub-domain for this domain namely docs.fosscloudy.com.  It will use this wildcard SSL certificates installed for the main domain. You can access your sub-domain with HTTPS in the browser and confirm its working.

Documentos SSL comodín

Renovación automática de los certificados SSL

Puede utilizar cualquiera de estos métodos mencionados anteriormente para obtener sus certificados SSL. Pero todos estos certificados de Let’s Encrypt son de corta duración y solo serán válidos durante 90 días. Por lo tanto, es obligatorio renovar estos certificados antes de que caduquen para facilitar el funcionamiento normal de sus sitios web. Puede hacer esto manualmente si lo necesita o puede automatizar este proceso usando cronjobs o el cliente Certbot.

Cuando un certificado se instala correctamente mediante la ejecución de los métodos anteriores, recibirá un mensaje similar a este:

NOTAS IMPORTANTES: - ¡Felicitaciones!  Su certificado y cadena se han guardado en: /etc/letsencrypt/live/fosscloudy.com/fullchain.pem Su archivo de claves se ha guardado en: /etc/letsencrypt/live/fosscloudy.com/privkey.pem Su certificado vencerá el 2018-09-03.  Para obtener una versión nueva o modificada de este certificado en el futuro, simplemente ejecute certbot nuevamente con la opción "certonly".  Para renovar * todos * sus certificados de forma no interactiva, ejecute "certbot renew"

Este mensaje indica claramente cómo renovar su certificado en el futuro con el "certbot renew" mando.

Probemos el proceso de renovación automática con el siguiente comando:

#certbot renew

Este comando verificará si los SSL de dominio deben renovarse y renovará los SSL de dominio que necesitan renovación.

La buena noticia es que los paquetes de Certbot en nuestro servidor vienen con un cronjob que renovará nuestros certificados SSL automáticamente antes de que caduquen. Dado que los certificados Let’s Encrypt duran 90 días, es muy recomendable aprovechar esta función.

# cat /etc/cron.d/certbot
# /etc/cron.d/certbot: crontab entries for the certbot package
#
# Upstream recommends attempting renewal twice a day
#
# Eventually, this will be an opportunity to validate certificates
# haven't been revoked, etc. Renewal will only occur if expiration
# is within 30 days.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

0 */12 * * * root test -x /usr/bin/certbot -a ! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q renew

Este cron se ejecutará dos veces al día, pero no renovará los certificados a menos que estén a punto de caducar.

Leer también:

Let’s Encrypt ha cambiado literalmente la forma en que generamos, instalamos y usamos certificados SSL. Con sus procedimientos automatizados utilizando la herramienta Certbot, puede ver con qué facilidad puede obtener sus certificados SSL gratuitos en solo unos segundos, desde Let’s Encrypt e instalarlos en cuestión de minutos, automáticamente. Espero que este artículo sea informativo y útil para ti. Publique sus valiosos comentarios y sugerencias al respecto.

Publicaciones relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Botón volver arriba
Cerrar