Product SiteDocumentation Site

10.2. Certificats X.509

Els certificats són elements bàsics en la construcció de molts serveis de xarxa basats en protocols criptogràfics quan necessiten algun tipus d'autenticació central.
Entre aquests protocols, l'SSL (de «Secure Socket Layer» o Nivell de Sòcols Segurs) va ser inventat per Netscape per assegurar les connexions amb servidors web. Més tard va ser estandarditzat per l'IETF sota l'acrònim TLS («Transport Layer Security» o Seguretat del Nivell de Transport). Des de llavors, el TLS va continuar evolucionant, mentre que actualment l'SSL està obsolet a causa de múltiples defectes de disseny que s'han descobert.
El protocol TLS té com a objectiu principal el proporcionar privacitat i integritat de dades entre dues o més aplicacions informàtiques comunicants. El cas més comú a Internet és la comunicació entre un client (per exemple un navegador web) i un servidor.
A key pair is needed for the exchange of information, which involves a public key that includes information about the identity of the owner and matches a private key. The private key must be kept secret, otherwise the security is compromised. However, anyone can create a key pair, store any identity on it, and pretend to be the identity of their choice. One solution involves the concept of a Certification Authority (CA), formalized by the X.509 standard. This term covers an entity that holds a trusted key pair known as a root certificate. This certificate is only used to sign other certificates (key pairs), after proper steps have been undertaken to check the identity stored on the key pair. Applications using X.509 can then check the certificates presented to them, if they know about the trusted root certificates.
Es pot implementar una CA (com es descriu a Secció 10.2.2, «Infraestructura de clau pública: easy-rsa»), però si es pretén utilitzar el certificat per a un lloc web, cal confiar en una CA de confiança. Els preus varien considerablement, però és possible implementar una alta seguretat gastant poc o res de diners.

10.2.1. Creació de certificats de confiança de franc

Many programs create and use snakeoil certificates by default (see sidebar SEGURETAT Certificats SSL Snake oil). Fortunately the certbot package brings everything we need to create our own trusted certificates, provided by the "Lets Encrypt" initiative (see sidebar CULTURA La iniciativa Let's Encrypt), which can also be used for mail transport agents (Postfix), mail delivery agents (Dovecot, Cyrus, etc.), and other network services.
Els administradors de Falcot només volen crear un certificat per al seu lloc web, que funciona amb Apache. Hi ha un convenient connector Apache per a certbot que edita automàticament la configuració d'Apache per servir el certificat obtingut, de manera que l'utilitzen:
# apt install python3-certbot-apache
[...]
# certbot --apache
aving 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): admin@falcot.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. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, 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:  N

Account registered.

No names were found in your configuration files. Please enter in your domain
name(s) (comma and/or space separated)  (Enter 'c' to cancel): falcot.com

Requesting a certificate for falcot.com
Performing the following challenges:
http-01 challenge for falcot.com
Enabled Apache rewrite module
Waiting for verification...
Cleaning up challenges
Created an SSL vhost at /etc/apache2/sites-available/000-default-le-ssl.conf
Enabled Apache socache_shmcb module
Enabled Apache ssl module
Deploying Certificate to VirtualHost /etc/apache2/sites-available/000-default-le-ssl.conf
Enabling available site: /etc/apache2/sites-available/000-default-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/000-default.conf to ssl vhost in /etc/apache2/sites-available/000-default-le-ssl.conf

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://falcot.com

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

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/falcot.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/falcot.com/privkey.pem
   Your cert will expire on 2022-06-04. 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
Si preferiu mantenir el servidor en execució durant la creació del certificat, podeu utilitzar el connector webroot per obtenir el certificat amb els paràmetres certonly i --webroot. Hauríeu d'especificar un --webroot-path (abreujat com a -w), que hauria de contenir els fitxers utilitzats. L'ordre aniria així:
# certbot certonly --webroot -w /var/www/html -d www.DOMINI.com -d DOMINI.com
Cal reiniciar tots els serveis que usin els certificats que heu creat.
Els certificats creats s'anomenen certificats de curta vida, que són vàlids durant 90 dies i que s'han de renovar cada tres mesos utilitzant l'ordre certbot renew. No obstant això, no hauríem de renovar tots els certificats manualment, sinó automàticament. Una tasca cron bàsica és inclosa per certbot a /etc/cron.d/certbot. Per assegurar-vos que els certificats es poden renovar automàticament, podeu executar certbot renew --dry-run.

10.2.2. Infraestructura de clau pública: easy-rsa

També és possible crear la nostra pròpia CA, per a la qual utilitzarem l'algorisme RSA, àmpliament utilitzat en criptografia de clau pública. Es tracta d'un “parell de claus”, compost d'una clau privada i una de pública. Les dues claus estan estretament lligades entre si, i les seves propietats matemàtiques són tals que un missatge encriptat amb la clau pública només pot ser desencriptat per algú que coneix la clau privada, fet que garanteix la confidencialitat. En la direcció oposada, un missatge xifrat amb la clau privada pot ser desencriptat per qualsevol que conegui la clau pública, que permet autenticar l'origen d'un missatge, ja que només algú amb accés a la clau privada pot generar-lo. Quan s'associa amb una funció de suma («hash») digital (MD5, SHA1, o alguna altra variant més recent), això ens porta a un mecanisme de signatura que es pot aplicar a qualsevol missatge.
Com que les CA públiques emeten certificats només a canvi d'un pagament (no pas petit), també és possible crear una autoritat privada de certificació dins de l'empresa. El paquet easy-rsa proporciona eines per crear una infraestructura de certificació X.509, implementada com un conjunt de scripts utilitzant l'ordre openssl.
Els administradors de Falcot Corp utilitzen aquesta eina per crear els certificats necessaris, tant per al servidor com per als clients. Això permet que la configuració de tots els clients sigui similar, ja que només s'han de configurar per confiar en els certificats que provenen de la CA local de Falcot. Aquesta CA és el primer certificat a crear; per a això, els administradors estableixen un directori amb els arxius necessaris per a la CA en una ubicació apropiada, preferiblement en una màquina no connectada a la xarxa per tal de mitigar el risc que la clau privada de la CA sigui robada.
$ make-cadir pki-falcot
$ cd pki-falcot
Després s'emmagatzemen els paràmetres necessaris al fitxer vars que es pot descomentar i editar:
$ grep EASYRSA vars
if [ -z "$EASYRSA_CALLER" ]; then
# easyrsa.  More specific variables for specific files (e.g., EASYRSA_SSL_CONF)
#set_var EASYRSA	"${0%/*}"
#set_var EASYRSA_OPENSSL	"openssl"
#set_var EASYRSA_OPENSSL	"C:/Program Files/OpenSSL-Win32/bin/openssl.exe"
#set_var EASYRSA_PKI		"$PWD/pki"
#set_var EASYRSA_TEMP_DIR	"$EASYRSA_PKI"
#set_var EASYRSA_DN	"cn_only"
set_var EASYRSA_REQ_COUNTRY	"FR"
set_var EASYRSA_REQ_PROVINCE	"Loire"
set_var EASYRSA_REQ_CITY	"Saint-Étienne"
set_var EASYRSA_REQ_ORG	"Falcot Corp"
set_var EASYRSA_REQ_EMAIL	"admin@falcot.com"
set_var EASYRSA_REQ_OU		"Certificate authority"
#set_var EASYRSA_KEY_SIZE	2048
#set_var EASYRSA_ALGO		rsa
#set_var EASYRSA_CURVE		secp384r1
#set_var EASYRSA_CA_EXPIRE	3650
#set_var EASYRSA_CERT_EXPIRE	825
#set_var EASYRSA_CRL_DAYS	180
#set_var EASYRSA_CERT_RENEW	30
#set_var EASYRSA_RAND_SN	"yes"
#set_var EASYRSA_NS_SUPPORT	"no"
#set_var EASYRSA_NS_COMMENT	"Easy-RSA Generated Certificate"
#set_var EASYRSA_TEMP_FILE	"$EASYRSA_PKI/extensions.temp"
# when undefined here, default behaviour is to look in $EASYRSA_PKI first, then
# fallback to $EASYRSA for the 'x509-types' dir.  You may override this
#set_var EASYRSA_EXT_DIR	"$EASYRSA/x509-types"
#set_var EASYRSA_KDC_REALM      "CHANGEME.EXAMPLE.COM"
# EASYRSA_PKI or EASYRSA dir (in that order.) NOTE that this file is Easy-RSA
#set_var EASYRSA_SSL_CONF	"$EASYRSA/openssl-easyrsa.cnf"
#set_var EASYRSA_REQ_CN		"ChangeMe"
#set_var EASYRSA_DIGEST		"sha256"
#set_var EASYRSA_BATCH		""
$ vim vars
$ 
Ara preparem el directori d'infraestructura de claus públiques amb el següent comandament:
$ ./easyrsa init-pki


init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /home/debian/pki-falcot/pki

El següent pas és la creació del parell de claus de la CA (les dues parts del parell de claus s'emmagatzemaran sota pki/ca.crt i pki/private/ca.key durant aquest pas). Podem afegir l'opció nopass per evitar introduir una contrasenya cada vegada que s'utilitza la clau privada:
$ ./easyrsa build-ca nopass

Using SSL: openssl OpenSSL 1.1.1k  25 Mar 2021
Generating RSA private key, 2048 bit long modulus (2 primes)
..................+++++
...............................+++++
e is 65537 (0x010001)
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.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:

CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/home/debian/pki-falcot/pki/ca.crt

El certificat es pot ser creat ja, així com els paràmetres Diffie-Hellman necessaris per a la banda de servidor d'una connexió SSL/TLS. Es vol utilitzar per a un servidor VPN (vegeu la secció Secció 10.3, «Xarxa privada virtual») que s'identifica amb el nom DNS vpn.falcot.com; aquest nom es reutilitza per als fitxers de claus generats (keys/vpn.falcot.com.crt per al certificat públic,keys/vpn.falcot.com.key per a la clau privada):
$ ./easyrsa gen-req vpn.falcot.com nopass

Using SSL: openssl OpenSSL 1.1.1k  25 Mar 2021
Generating a RSA private key
......................................+++++
..........................................................................+++++
writing new private key to '/home/debian/pki-falcot/pki/easy-rsa-5515.0PwyXl/tmp.g1c6u6'
-----
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.
-----
Common Name (eg: your user, host, or server name) [vpn.falcot.com]:

Keypair and certificate request completed. Your files are:
req: /home/debian/pki-falcot/pki/reqs/vpn.falcot.com.req
key: /home/debian/pki-falcot/pki/private/vpn.falcot.com.key


$ ./easyrsa sign-req server vpn.falcot.com

Using SSL: openssl OpenSSL 1.1.1k  25 Mar 2021


You are about to sign the following certificate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.

Request subject, to be signed as a server certificate for 825 days:

subject=
    commonName                = vpn.falcot.com


Type the word 'yes' to continue, or any other input to abort.
  Confirm request details: yes
Using configuration from /home/debian/pki-falcot/pki/easy-rsa-5603.87iCIa/tmp.u8r8Fj
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'vpn.falcot.com'
Certificate is to be certified until May 27 15:26:29 2024 GMT (825 days)

Write out database with 1 new entries
Data Base Updated

Certificate created at: /home/debian/pki-falcot/pki/issued/vpn.falcot.com.crt


$ ./easyrsa gen-dh

Using SSL: openssl OpenSSL 1.1.1k  25 Mar 2021
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
[…]

DH parameters of size 2048 created at /home/debian/pki-falcot/pki/dh.pem

El pas següent crea certificats per als clients de VPN; es requereix un certificat per a cada ordinador o persona autoritzada per utilitzar la VPN:
$ ./easyrsa build-client-full JoeSmith nopass

Using SSL: openssl OpenSSL 1.1.1k  25 Mar 2021
Generating a RSA private key
...................................+++++
.........................................................................................+++++
writing new private key to '/home/debian/pki-falcot/pki/easy-rsa-5694.DOYwSn/tmp.RKlbOE'
-----
Using configuration from /home/debian/pki-falcot/pki/easy-rsa-5694.DOYwSn/tmp.d5QHAC
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'JoeSmith'
Certificate is to be certified until May 27 15:29:25 2024 GMT (825 days)

Write out database with 1 new entries
Data Base Updated