Certbot

Da Guide@Debianizzati.Org.
Versione del 9 ago 2024 alle 13:10 di Wtf (discussione | contributi) (→‎delete)
(diff) ← Versione meno recente | Versione attuale (diff) | Versione più recente → (diff)
Vai alla navigazione Vai alla ricerca
Debian-swirl.png Versioni Compatibili

Tutte le versioni supportate di Debian

Introduzione

Certbot è un applicativo sviluppato dalla Electronic Frontier Foundation per automatizzare e rendere il più semplice possibile la procedura per abilitare il protocollo HTTPS all'interno di un webserver sfruttando certificati rilasciati da Let's Encrypt.
Questo strumento supporta svariati webserver come apache, ngix, ecc.

Installazione

Warning.png ATTENZIONE
EFF consiglia ora di installare certbot usando snapd (vedere la pagina dedicata di EFF).


Per prima cosa è necessario installare i seguenti pacchetti

# apt install certbot python-certbot-apache

quindi attivare i seguenti moduli:

# a2enmod headers ssl

Comandi

Attention.png Avvertimento
Per Certbot installare un certificato significa modificare i file di configurazione dei siti web che corrispondono ai domini specificati affinché usino https.


run

Questo è il comando predefinito che permette sia di scaricare che installare un certificato in unico passaggio. Ad esempio digitare

certbot --apache -d ind1.mio_dominio.abc

è del tutto equivalente a

certbot run --apache -d ind1.mio_dominio.abc

L'opzione --apache dice a Certbot che vogliamo attivare SSL per siti web serviti da Apache.

certificates

Per sapere quali certificati sono installati, dove si trovano e che domini copre ciascuno di essi digitare:

# certbot certificates

che stamperà a video qualcosa di simile a

Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Found the following certs:
  Certificate Name: mio_dominio.abc
    Serial Number: ...
    Key Type: ECDSA
    Domains: mio_dominio.abc ind1.mio_dominio.abc ind2.mio_dominio.abc ecc.
    Expiry Date: ...
    Certificate Path: /etc/letsencrypt/live/mio_dominio.abc/fullchain.pem
    Private Key Path: /etc/letsencrypt/live/mio_dominio.abc/privkey.pem
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

certonly

Questo comando di fatto fa tutto quello che fa run eccetto l'ultima parte, ovvero non modifica i file di configurazione dei siti web che pertanto andranno editati manualmente per includere i certificati appena scaricati.

certbot certonly -d ind1.mio_dominio.abc

Tolto il caso di utenti esperti che preferisco non sfruttare tutti gli automatismi di Certbot questo comando viene generalmente usato quando si vuole ampliare l'elenco dei domini inclusi in un certificato già esistente.

install

Questo comando viene solitamente usato solo dopo aver già usato il comando run ed essere stati notificati che per un qualche motivo certbot non è stato in grado di aggiornare i file di configurazione dei siti web. Ovviamente è necessario aver prima risolto il problema che ha impedito al comando run di apportare le modifiche ai suddetti file di configurazione.

certbot install --cert-name nome_certificato

revoke

Warning.png ATTENZIONE
Revocando un certificato potrebbero risultare INUTILIZZABILI tutti quei virtualhost che ne facevano uso, almeno fino a quando non venga fornito un nuovo certificato o la loro configurazione non venga modificata per non usare più SSL.


Annulla un certificato senza eliminarlo in modo predefinito (al termine della revoca viene chiesto se si desidera anche eliminarlo):

certbot revoke --cert-name nome_certificato

delete

Warning.png ATTENZIONE
  • Cancellando un certificato saranno resi INUTILIZZABILI tutti quei virtualhost che ne facevano uso, almeno fino a quando non venga fornito un nuovo certificato o la loro configurazione non venga modificata per non usare più SSL.
  • MAI eliminare un certificato cancellandolo manualmente dal disco, usare sempre il comando delete.


Cancella un certificato senza revocarlo (si continueranno quindi a ricevere eventuali avvisi di scadenza certificato):

certbot delete --cert-name nome_certificato
Bulb.png Suggerimento
Revocare sempre un certificato prima di cancellarlo.


Esempi

Apache, automatismo completo (run)

Ipotesi

Nel seguito si faranno le seguenti ipotesi:

  • l'utente ha le porte standard, ovvero 80 e 443, aperte anche in ingresso. In caso contrario molti degli automatismi dello strumento andrebbero persi e la procedura standard non sarebbe più applicabile. Da notare che i propri virtualhost possono usare qualsiasi porta, ovvero non sono obbligati ad usare le porte standard, è semplicemente certbot che richiede che dette porte siano aperte per funzionare correttamente;
  • l'utente ha già configurato il proprio eventuale firewall di rete in modo da reindirizzare correttamente le succitate porte.
  • l'utente ha già creato almeno un virtualhost normale (cioè senza ssl) avente servername corrispondente al dominio cui si vuole associare il certificato. Questo virtualhost inoltre deve essere attivo, ovvero deve essere dichiarato in un file .conf per cui esiste un collegamento simbolico in /etc/apache2/sites-enabled/
  • l'utente non è interessato ad ottenere wild certificates, cioè un certificato che copra tutti i possibili sottodomini (tipo *.mio_dominio.abc).

Scaricamento certificato e sua installazione

Dato il dominio mio_dominio.abc ed una lista di suoi sottodomini è possibile scaricare ed installare un certificato che li includa tutti digitando un comando del tipo

# certbot --apache -d ind1.mio_dominio.abc,ind2.mio_dominio.abc,ind3.mio_dominio.abc,ecc.
Warning.png ATTENZIONE
Tutti i domini specificati devono essere stati dichiarati ciascuno come ServerName di un diverso virtualhost.


Info.png Nome certificato
Certbot userà come nome del certificato il primo dominio dichiarato, pertanto se si vuole usare un nome diverso è necessario passare l'opzione --cert-name nome_desiderato

Nel caso di singolo dominio e riprendendo l'esempio fatto precedentemente il comando diviene

# certbot --apache -d ind1.mio_dominio.abc
Attention.png Avvertimento
La procedura guidata descritta di seguito potrebbe cambiare nel tempo.


Lo strumento proporrà innanzitutto tre domande

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator apache, Installer apache
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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-v02.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 our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: 

Dopo di che se la configurazione è andata a buon fine restituirà qualcosa di simile a

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 ind1.mio_dominio.abc
Enabled Apache rewrite module
Waiting for verification...
Cleaning up challenges
Created an SSL vhost at /etc/apache2/sites-available/mio_sito-le-ssl.conf
Deploying Certificate to VirtualHost /etc/apache2/sites-available/mio_sito-le-ssl.conf
Enabling available site: /etc/apache2/sites-available/mio_sito-le-ssl.conf

e quindi porrà la seguente domanda:

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

Se si risponde uno sarà onere dell'utente modificare opportunamente i file conf del proprio sito web, viceversa rispondendo "2" sarà visualizzato qualcosa di simile a quanto segue:

Enabled Apache rewrite module                                                                                                     
Redirecting vhost in /etc/apache2/sites-enabled/mio_sito.conf to ssl vhost in /etc/apache2/sites-available/mio_sito-le-ssl.conf

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://ind1.mio_dominio.abc

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

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/ind1.mio_dominio.abc/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/ind1.mio_dominio.abc/privkey.pem
   Your cert will expire on 2019-08-24. 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

Si supponga ora che il file conf di partenza fosse:

<VirtualHost *:80>
	ServerName ind1.ciao.abc
	DocumentRoot "/var/www/cartella_mio_sito/"
	DirectoryIndex pagina_principale.html
</VirtualHost>

Al termine delle operazione il file di partenza mio_sito.conf risulterà alterato come segue:

<VirtualHost *:80>
	ServerName ind1.ciao.abc
	DocumentRoot "/var/www/cartella_mio_sito/"
	DirectoryIndex pagina_principale.html
        RewriteEngine on
        RewriteCond %{SERVER_NAME} =ind1.ciao.abc
        RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

Contestualmente sarà stato creato un secondo file conf di nome mio_sito-le-ssl.conf:

<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerName ind1.ciao.abc
        DocumentRoot "/var/www/cartella_mio_sito/"
        DirectoryIndex pagina_principale.html
        SSLCertificateFile /etc/letsencrypt/live/ind1.ciao.abc/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/ind1.ciao.abc/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf
    </VirtualHost>
</IfModule>

In sintesi quello che succede è che il file di conf originale, cioè mio_sito.conf, viene modificato in modo da reindirizzare tutte le richieste dirette al virtualhost configurato sulla porta 80 a quello sulla porta 443, ovvero ogni richiesta http viene automaticamente convertita in una https.
Se non si avesse alcun interesse a mantenere il virtualhost sulla porta 80 si può disabilitare/eliminare il file mio_sito.conf senza problemi, tuttavia è bene sapere che tutte le richieste http non verranno più inoltrate automaticamente su https, quindi l'utente si vedrà restituire dal webserver un errore 403 Forbidden (è quindi fondamentale che chi già fruiva in precedenza del sito sia informato del cambio).

Rinnovo dei certificati

Certbot permette di rinnovare in automatico tutti i propri certificati con il comando certbot renew, tuttavia è molto probabile che durante lo scaricamento ed installazione dei certificati certbot stesso si sia già preoccupato di creare un'attività programmata per il rinnovo dei certificati.
Per verificare se detta attività è stata effettivamente pianificata digitare:

# systemctl list-timers

e verificare che sotto la colonna UNIT compaia una riga con scritto certbot.timer. Se presente non è necessario impostare manualmente alcuna attività di rinnovo, viceversa sarà possibile automatizzare il processo di rinnovo inserendo in crontab il comando certbot renew -q, dove l'opzione -q permette di sopprimere l'output del comando, fatta eccezione il caso di eventuali errori.

Info.png Nota
Il comando renew non innesca automaticamente il rinnovo dei certificati, infatti questi saranno effettivamente rinnovati solo quando prossimi alla scadenza


Per esempio volendo ripetere la verifica ogni 10 del mese alla 1:30 la riga da inserire in crontab sarebbe:

30 1 10 * * /usr/bin/certbot renew -q

È comunque caldamente consigliato testare subito che il comando renew funzioni specificando l'opzione --dry-run, ovvero:

# certbot renew --dry-run

che in caso di successo dovrebbe restituire qualcosa di simile a:

Saving debug log to /var/log/letsencrypt/letsencrypt.log

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Processing /etc/letsencrypt/renewal/ind1.mio_dominio.abc.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Cert not due for renewal, but simulating renewal for dry run
Plugins selected: Authenticator apache, Installer apache
Renewing an existing certificate
Performing the following challenges:
http-01 challenge for ind1.mio_dominio.abc
Waiting for verification...
Cleaning up challenges

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
new certificate deployed with reload of apache server; fullchain is
/etc/letsencrypt/live/ind1.mio_dominio.abc/fullchain.pem
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
** DRY RUN: simulating 'certbot renew' close to cert expiry
**          (The test certificates below have not been saved.)

Congratulations, all renewals succeeded. The following certs have been renewed:
  /etc/letsencrypt/live/ind1.mio_dominio.abc/fullchain.pem (success)
** DRY RUN: simulating 'certbot renew' close to cert expiry
**          (The test certificates above have not been saved.)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - 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.

Errori

Apache non raggiungibile

Se per una qualsiasi ragione il proprio webserver non risultasse raggiungibile dall'esterno la pocedurà fallirà mostrando qualcosa di simile a quanto segue:

Obtaining a new certificate
Performing the following challenges:
http-01 challenge for mio_dominio.abc
http-01 challenge for ind1.mio_dominio.abc
Enabled Apache rewrite module
Waiting for verification...
Cleaning up challenges
Failed authorization procedure. mio_dominio.abc (http-01): urn:ietf:params:acme:error:connection :: The server could not connect to the client to verify the domain :: Fetching http://mio_dominio.abc/.well-known/acme-challenge/stringa_di_vari_caratteri: Connection refused, ind1.mio_dominio.abc (http-01): urn:ietf:params:acme:error:connection :: The server could not connect to the client to verify the domain :: Fetching http://ind1.mio_dominio.abc/.well-known/acme-challenge/stringa_di_vari_caratteri: Connection refused

IMPORTANT NOTES:
 - The following errors were reported by the server:

   Domain: mio_dominio.abc
   Type:   connection
   Detail: Fetching
   http://mio_dominio.abc/.well-known/acme-challenge/stringa_di_vari_caratteri:
   Connection refused

   Domain: ind1.mio_dominio.abc
   Type:   connection
   Detail: Fetching
   http://ind1.mio_dominio.abc/.well-known/acme-challenge/stringa_di_vari_caratteri:
   Connection refused

   To fix these errors, please make sure that your domain name was
   entered correctly and the DNS A/AAAA record(s) for that domain
   contain(s) the right IP address. Additionally, please check that
   your computer has a publicly routable IP address and that no
   firewalls are preventing the server from communicating with the
   client. If you're using the webroot plugin, you should also verify
   that you are serving files from the webroot path you provided.
 - 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.

Ampliare lista domini di un certificato

Nel caso si abbia necessità di aggiungere uno o più domini ad un certificato esistente è possibile usare il seguente comando:

certbot --expand -d ind1.mio_dominio.abc,ind2.mio_dominio.abc,ind3.mio_dominio.abc,ind4.mio_dominio.abc

È importante sottolineare che è necessario dichiarare sia tutti i domini già coperti, sia quelli nuovi. L'opzione --expand infatti permette solo di aggiungere nuovi domini a quelli già coperti dal certificato, non permette di eliminare domini già associati allo stesso.

Modificare lista domini di un certificato

Qualora si richiesto di modificare l'elenco di domini supportati da un certificato (inclusa la cancellazione) digitare:

certbot certonly --cert-name mio_dominio.abc -d mio_dominio.abc,ind5.mio_dominio.abc

A seguito di questo comando il certificato mio_dominio.abc conterrà solo i domini mio_dominio.abc e ind5.mio_dominio.abc.

Approfondimenti

Manpages

  • man certbot

Sitografia




Guida scritta da: Wtf 19:03, 8 ago 2024 (CEST) Swirl-auth20.png Debianized 20%
Estesa da:
Verificata da:

Verificare ed estendere la guida | Cos'è una guida Debianized