151. CA Autoridad de certificación¶
La primera parte de esta página presenta los conceptos generales de Autoridad de Ceritificación.
En la segunda parte se presenta EASY-RSA como solución de CA para una red de área local y privada.
Basado en: https://howtoforge.es/como-instalar-un-servidor-y-un-cliente-openvpn-con-easy-rsa-3-en-centos-8/
151.1 INTRODUCCIÓN¶
Una entidad certificadora CA es la encargada de emitir certificados digitales para verificar identidades, por ejemplo de servidores web locales
Con una CA privada, puede emitir certificados para usuarios, servidores o programas y servicios individuales dentro de su infraestructura.
Se requiere una cuenta cuenta no-root con privilegios sudo . Se va a modificar el firewall y se recomienda un servidor dedicado en exclusiva a CA desactivado por completo cuando no esté en uso.
151.2 Teoría sobre PKI (Public Key Infrastructure)¶
Terminos utilizados en PKI
- PKI: Infraestructura de Clave Pública. Esto describe la colección de archivos y asociaciones entre la CA (Autoridad de Certificación), pares de claves, solicitudes y certificados.
- CA: Autoridad de Certificación. Esta es la "certificación principal" en la raíz de una PKI.
- cert: Un certificado es una solicitud que ha sido firmada por una CA. El certificado contiene la clave públic**a, algunos **detalles que describen el propio certificado y una f**irma digital de la CA**.
- request: Solicitud de Certificado (opcionalmente 'req'). Esta es una solicitud de un certificado que luego se envía a una CA para su firma. Una solicitud contiene la información del certificado deseado junto con una firma digital de la clave privada.
- keypair: n par de claves es un par de claves criptográficas asimétricas. Estas claves se dividen en dos partes: las claves pública y privada. La clave pública se incluye en una solicitud y un certificado.
Siglas:
- CA
- RA Autoridad de registro
- VA Autoridad de validación
151.2.1 CA¶
Certificate Authority. La cla clave privada del CA se usa par emitir certificados y es crítica para mantener la seguridad de todo el PKI y por ese motivo se recomienda mantener la estructura PKI en un sistema dedicado y seguro.
Para crear un PKI, el primer paso es crear un entorno seguro, por ejemplo, cuentas protegidasa, sistemas dedicados y en medios extraibles off-line
Una vez creada la CA puede recibir peticiones de certificado (certificate requests) de las entidades finales. Estos certificados de entidad se emiten a los consumidores de certificados X509, como un cliente o servidor de una VPN, sistema web o de correo electrónico. Las solicitudes de certificados y los propios certificados no son sensibles desde el punto de vista de la seguridad y se pueden transferir de la manera más conveniente, como por correo electrónico o en una unidad flash, etc. Para una mayor seguridad, es una buena idea verificar que la solicitud recibida coincida con la copia del remitente, por ejemplo, verificando el valor hash esperado frente al original del remitente.
151.2.2 Pares de claves y solicitudes¶
Individual end-entities do not need a full CA set up and will only need to create a keypair and associated certificate request. The private key is not used anywhere except on this entity, and should never leave that system. It is wise to secure this private key with a strong passphrase, because if lost or stolen the holder of the private key can make connections appearing as the certificate holder.
Once a keypair is generated, the certificate request is created and digitally signed using the private key. This request will be sent to a CA for signing, and a signed certificate will be returned.
151.2.3 Como las peticiones se convierten en certificados¶
After a CA signs the certificate request, a signed certificate is produced. In this step, the CA's private key is used to digitally sign the entity's public key so that any system trusting the CA certificate can implicitly trust the newly issued certificate. This signed certificate is then sent back to the requesting entity. The issued certificate is not security-sensitive and can be sent over plaintext transmission methods
151.2.4 Comprobar un certificado emitido¶
After 2 entities have created keypairs, sent their requests to the CA, and received a copy of their signed certificates and the CA's own certificate, they can mutually authenticate with one-another. This process does not require the 2 entities to have previously exchanged any kind of security information directly.
During a TLS handshake each side of the connection presents their own cert chain to the remote end. Each side checks the validity of the cert received against their own copy of the CA cert. By trusting the CA root cert, the peer they are talking to can be authenticated.
The remote end proves it "really is" the entity identified by the cert by signing a bit of data using its own private key. Only the holder of the private key is able to do this, allowing the remote end to verify the authenticity of the system being connected to.
151.3 EASY-RSA 3¶
151.4 Paso 1. Instalar easy-rsa¶
sudo apt update
sudo apt install easy-rsa
151.5 Paso 2 . Crear directorio para la infraestructura de clave pública.¶
Sin usar sudo creamos por ejemplo mkdir ./easy-rsa
. En esta carpeeta creamos enlaces simbólicos a directorio de instalación de easy-rsa:
ln -s /usr/share/easy-rsa/* ~/easy-rsa/
Restringimos el acceso al propietario:
chmod 700 ./easy-rsa
cd ~/easy-rsa
./easyrsa init-pki
Output
init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /home/sammy/easy-rsa/pki
151.6 Paso 3 Crear una entidad CA¶
Primero creamos un fichero vars
cd ~/easy-rsa
nano vars
set_var EASYRSA_REQ_COUNTRY "ES"
set_var EASYRSA_REQ_PROVINCE "Madrid"
set_var EASYRSA_REQ_CITY "Madrid"
set_var EASYRSA_REQ_ORG "IES TIERNO GALVAN"
set_var EASYRSA_REQ_EMAIL "admin@info.etg"
set_var EASYRSA_REQ_OU "Community"
set_var EASYRSA_ALGO "ec"
set_var EASYRSA_DIGEST "sha512"
Con este fichero creamos el certificado
./easyrsa build-ca
También se le solicitará confirmar el nombre común (CN) de su CA. El nombre común es el que se usa para hacer referencia a esta máquina en el contexto de la entidad de certificación. Puede ingresar cualquier secuencia de caracteres para el nombre común de la CA; sin embargo, para hacerlo más simple presione ENTER para aceptar el nombre predeterminado.
Output
. . .
Enter New CA Key Passphrase:
Re-Enter New CA Key Passphrase:
. . .
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/sammy/easy-rsa/pki/ca.crt
Esto crea dos archivos: ~/easy-rsa/pki/ca.crt
y ~/easy-rsa/pki/private/ca.key
ca.crt
Es el archivo con el certificado público de la CA. Los usuarios, los servidores y los clientes utilizarán este certificado para verificar que sean parte de la misma red de confianza. Todos los usuarios y los servidores que usen su CA deberán tener una copia de este archivo.ca.key
Es la clave privada de la autoridad de certificación (CA) para firmar certificados para clientes y servidores. Si un atacante obtiene acceso a su CA y, a la vez, a su archivo ca.key, deberá destruir la CA. Esta es la razón por la cual su archivo ca.key deberá estar únicamente en su máquina de CA.
La CA está lista para emplearse.
151.7 Paso 4 Distribuir el certificado público de la CA¶
Esta CA es un root de confianza en los sistemas de la red privada.
Es el momento de agregar el certificado de la CA a los servidores, correo,web, openVPN, etc. Cualquier usuario o servidor que necesite verificar laidentidad de otro usuario o servidor de su red debe contar con una copia delarchivo ca.crt importada en el almacén de certificados de su sistemaoperativo.
151.8 Paso 5 Importar CA a cada sistema de la red privada.¶
Se utiliza una copía de ca.crt. Al ser un fichero de texto se puede copiar ypegar. O utiizar scp sftp o rsync
151.8.1 Importar CA en LINUX¶
En este otro ordenador importamos o copiamos ca.crt y ejecutamos loscomandos:
sudo cp /tmp/ca.crt /usr/local/share/ca-certificates/
sudo update-ca-certificates
awk -v cmd='openssl x509 -noout -subject' '/BEGIN/{close(cmd)};{print | cmd}' < /etc/ssl/certs/ca-certificates.crt | grep orion
Y este sistema confiará en cualquier certificado firmado por la CA privada.
151.8.2 Importar CA en Windows 10¶
- Open the “Microsoft Management Console” by using the Windows + R keyboard combination, typing mmc and clicking Open
- Go to File > Add/Remove Snap-in
- Click Certificates and Add
- Select Computer Account and click Next
- Select Local Computer then click Finish
- Click OK to go back to the MMC window
- Double-click Certificates (local computer) to expand the view
- Select Trusted Root Certification Authorities, right-click on 2. Certificates in the middle column under “Object Type” and select All 2 Tasks then Import
- Click Next then Browse. Change the certificate extension dropdown next 2. to the filename field to All Files (.) and locate the myCA.pem file, 2. click Open, then Next
- Select Place all certificates in the following store. “Trusted Root 2. Certification Authorities store” is the default. Click Next then click 2. Finish to complete the wizard.
El resultado final:
151.9 Creamos certificado firmados por nuestra CA para nuestro servidor web.¶
Previamente hemos instalado el certificado raíz de nuestra CA
151.9.1 Par de claves y request en el servidor web¶
Para ser usados en https
, en primer lugar creáremos una clave privada para el sitio web. Nombramos la clave privada como el dominio:
openssl genrsa -out orion.info.etg.key 2048
A continuación creamos un request CSR
para enviar a la autoridad CA
openssl req -new -key orion.info.etg.key -out orion.info.etg.csr
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]:US
State or Province Name (full name) [Some-State]:Springfield State
Locality Name (eg, city) []:Springfield
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Hellfish Media
Organizational Unit Name (eg, section) []:7G
Common Name (e.g. server FQDN or YOUR name) []:Hellfish Media
Email Address []:asimpson@hellfish.media
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Creamos un fichero de configuración de extensión de certificado X509 V3 :
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = orion.info.etg
Y ejecutamos:
openssl x509 -req -in hellfish.test.csr -CA myCA.pem -CAkey myCA.key \
-CAcreateserial -out hellfish.test.crt -days 825 -sha256 -extfile hellfish.test.ext