TLS
Seccions d'aquesta pàgina 4
01General#
02Estàndards / Standards#
- Comunicació / Communication
- TLS (wp)
-
version RFC published deprecated server client ...
nginx (SNI): ssl_protocols ...;openssl s_client
SSL 1.0 (unpublished)
SSL 2.0
1995 2011
SSL 3.0
1996 2015
TLSv1.0 RFC 2246 1999 2021 TLSv1 -tls1
TLSv1.1 RFC 4346 2006 2021 TLSv1.1
TLSv1.2 RFC 5246 2008 - TLSv1.2 -tls1_2
TLSv1.3 RFC 8446 2018 -
Aquesta taula continua cap a la dreta — desplaça-la o gira el mòbil.
-
- DTLS
- DTLS and OpenSSL: quick setup for server and client
- Exemple / Example
- server
openssl s_server -cert cert.pem -key pk.pem -dtls1 -accept 4444
- client
openssl s_client -dtls1 -connect xx.xx.xx.xx:4444 -debug
- server
- Ús / Usage
- Janus gateway (WebRTC)
- TLS (wp)
- Certificats / Certificates
- Certificate structure: X.509 (RFC
5280) (wp)
(RFC 4523)
-
SN
LN
description
notes
NID
crypto/objects/objects.h
C
countryName
Country name
ST
stateOrProvinceName
State or province name
L
localityName
Locality name
O
organizationName
Organization name
OU
organizationalUnitName
Organization unit name
CN
commonName
Common name
- Server certificate: must exactly match "ServerName" in Apache config
- Must be different in CA and a server certificate signed by the CA
NID_commonName
Email
emailAddress
Email address
Aquesta taula continua cap a la dreta — desplaça-la o gira el mòbil.
- OpenSSL X.509 config
-
- PKCS
- PKCS#10: Certificate request
- PKCS#12: Certificate encapsulation
- Format (conversió/conversion)
- DER
- binary
- PEM
-----BEGIN CERTIFICATE-----
base64
-----END CERTIFICATE-----
- DER
- Encapsulació / Encapsulation
- Certificate structure: X.509 (RFC
5280) (wp)
(RFC 4523)
03Programari / Software#
- OpenSSL
- gnutls
- Instal·lació / Installation
- Mageia
dnf install gnutls
- Mageia
certtool- inspection
certtool -i <fullchain.pem
- inspection
- Instal·lació / Installation
04OpenSSL#
- OpenSSL / LibreSSL
- openssl (1) (command)
- x509v3_config(5)
- Arbitrary extensions
- crypto (library)
- Instal·lació / Installation:
urpmi openssl
- OpenSSL CVS web interface
- Howto
- Most used OpenSSL commands
- Cryptography tutorials
- Creating and using SSL certificates (Eclectica): minimal openssl.cnf
- SSL Certificates HOWTO (Franck Martin): CA.pl / command line equivalent
- Network Security with OpenSSL (O'Reilly)
- The
Open-source
PKI book
- Desenvolupament / Development
- Signatura de paquets Linux / Linux package signature
- Protecció de
programari / Software protection (license keys)
- server
- public/private key generation:
openssl genrsa -out private.pem 248- alternative
- ssh-keygen -t rsa -f cloud.key
- cloud.key
- cloud.key.pub ()
- ssh-keygen -t rsa -f cloud.key
- digest, encrypt with private key, encode in base64:
echo -n "User Name|user@example.com|ProductName" \
| openssl dgst -sha1 -binary \
| openssl rsautl -sign -inkey private.pem \
| openssl enc -base64
- (alternative) digest, encrypt with private key, encode
in base32:
echo -n "User Name|user@example.com|ProductName" \
| openssl dgst -sha1 -binary \
| openssl rsautl -sign -inkey private.pem \| sf_base32enc
- get the public key to give to the client:
- RFC4716
openssl rsa -in private.pem \
-out public.pem -outform PEM -pubout-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
- conversion from ... to ...:
- ...
ssh-rsa ...
- Converting ssh(1) RSA public keys to PKCS8 format
- RFC4716
- public/private key generation:
- client:
- must compare the following two strings:
echo -n "User Name|user@example.com|ProductName" \
| openssl dgst -sha1
echo KzB+R8NIYaJK1Sea8Poq8MkDg27I+JfUkntZ6QQATg== \
| openssl enc -base64-d \
| openssl rsautl -verify -inkey public.pem -pubin -hexdump
- must compare the following two strings:
- server
- Usage of OpenSSL for Apache HTTPS
- General openssl configuration
file:
/etc/pki/tls/openssl.cnf- or any other file (e.g. /tmp/openssl.cnf):
- if using script misc/CA.pl:
- export SSLEAY_CONFIG="-config /tmp/openssl.cnf"
- if using script misc/CA.pl:
- Generació de contrasenyes /
Keyword generation
- zxcvbn tests (online test of keyword strength)
- 10 hexadecimal bytes
openssl rand -hex 10
- integer
valor=$(openssl rand -hex 4)
echo $((16#$valor))
- 12 ASCII characters
openssl rand -base64 9
- Generació de parell de claus / Key
pair generation
-
Note: option "
generated file(s)
default name
file
format
content
openssl genrsa [-out private_public.key] 2048
(stdout)
PEM RSA private key PEM
-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----opensslrsa-inprivate_public.key-pubout[-outform PEM] [-out public.key](stdout) ASCII text
PEM -----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
ssh-keygen [-f output_filename] [-C "my comment"] [-b 2048] -m PEM- ~/.ssh/id_rsa
- output_flename
PEM RSA private key
PEM -----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----
- ~/.ssh/id_rsa.pub
- output_filename.pub
OpenSSH RSA public key
PKCS8
ssh-rsa ... user@localhostssh-rsa ... my comment
ssh-keygen [-f output_filename] [-C "my comment"] [-b 2048] [-m RFC4716]- ~/.ssh/id_rsa
- output_filename
OpenSSH private key
RFC4716
-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----
- ~/.ssh/id_rsa.pub
- output_filename.pub
OpenSSH RSA public key PKCS8 ssh-rsa ... my_comment
ssh-keygen [-f input_filename] -y(stdout) OpenSSH RSA public key PKCS8 ssh-rsa ...
Aquesta taula continua cap a la dreta — desplaça-la o gira el mòbil.
-m PEM" is needed byMacOS in order to generate a "BEGIN RSA PRIVATE KEY" instead of "BEGIN OPENSSH PRIVATE KEY" (created with option-o). - Generació / Generation
- parell de claus pública/privada dins d'un fitxer
xifrat (triple DES) com a sortida / inside an encrypted
(DES-3) file as output:
opensslgenrsa-des3 -out toto.des3.key 4096
- parell de claus pública/privada dins d'un fitxer no
xifrat (no segur!!) com a fitxer de sortida / inside a
non-encrypted (insecure!!) file as output
opensslgenrsa-out toto.clar.key 4096
- alternativa / alternative to create a pair of
private/public keys (e.g. recommended by Bitbucket):
ssh-keygen [-f toto] [-b 2048]- ssh-keygen -t ed25519 -C my_comment -f my_file
- Choosing
an Algorithm and Key Size
-
type bit size generated private key generated public key info
[-m rfc4716] -m pem -m pkcs8
[-t rsa] -b 2048
-b 4096-----BEGIN OPENSSH PRIVATE KEY-----
-----BEGIN RSA PRIVATE KEY----------BEGIN PRIVATE KEY-----ssh-rsa ...- default, when -t is not specified
- not recommended
-t dsa -b 1024
-----BEGIN OPENSSH PRIVATE KEY-----
-----BEGIN DSA PRIVATE KEY----------BEGIN PRIVATE KEY-----ssh-dss ...
-t ecdsa -b 256
-b 384
-b 521
-----BEGIN OPENSSH PRIVATE KEY-----
-----BEGIN EC PRIVATE KEY----------BEGIN PRIVATE KEY-----ecdsa-sha2-nistp256 ...
ecdsa-sha2-nistp384 ...
ecdsa-sha2-nistp521 ...
-t ed25519
-----BEGIN OPENSSH PRIVATE KEY-----
-----BEGIN OPENSSH PRIVATE KEY----------BEGIN OPENSSH PRIVATE KEY-----ssh-ed25519 ...- not supported by openssl dgst
Aquesta taula continua cap a la dreta — desplaça-la o gira el mòbil.
-
- ús / usage
- parell de claus pública/privada dins d'un fitxer
xifrat (triple DES) com a sortida / inside an encrypted
(DES-3) file as output:
- Extracció / Extraction
- extracció de
la clau pública / extraction of public key:
opensslrsa-in toto.key -out public.pem -outform PEM -pubout
- extracció de
la clau pública a partir d'un certificat / extraction of
public key from a certificate:
opensslrsa-in certificat.pem -out public.pem -outform PEM -pubout
- extracció de
la clau privada (cap a un fitxer opcionalment xifrat amb
triple DES [-des3]) / extraction of private key (to a
file, optionally encrypted with triple DES [-des3]):
opensslrsa-in toto.key -out private.pem -outform PEM [-des3]
- extracció (-e) de la clau pública a partir del parell
de claus (generat per openssl o per ssh-keygen)
ssh-keygen -e [-f id_rsa] -y
ssh-keygen -e [-f private_public.key] -y- by default, the generated output is in format
RFC4716 (BEGIN SSH2 PUBLIC KEY), but can be
specified with -m option
-
options
output -f toto -y ssh-... xxx my_comment-f toto -e -y [-m RFC4716] ---- BEGIN SSH2 PUBLIC KEY ----
...
---- END SSH2 PUBLIC KEY -----f toto -e -y -m PEM -----BEGIN RSA PUBLIC KEY-----
...
-----END RSA PUBLIC KEY------f toto -e -y -m PKCS8 -----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----Aquesta taula continua cap a la dreta — desplaça-la o gira el mòbil.
-
- extracció de
la clau pública / extraction of public key:
- Conversió / Conversion
- conversió des d'un fitxer xifrat cap a un fitxer no xifrat (no segur!!) / to convert from an encrypted to a clear file (insecure!!):
openssl rsa -in toto.des3.key -out toto.clar.key- conversió d'una clau pública en format PEM (extreta
amb openssl) cap a una clau pública en format PKCS8
ssh-keygen -i -f public.key -m PKCS8
- conversió d'una clau pública en format PKCS8 (generada
per ssh-keygen) cap a una clau pública en format PEM
(-----BEGIN RSA PUBLIC KEY-----)
ssh-keygen -f id_rsa.pub -e -m pem
-
- Digest
- Xifratge,
desxifratge
i signatura de fitxers / File encryption, decryption and
signature (exemples/examples)
(rsautl,
pkeyutl)
# genera el parell de claus pública / privada (en un fitxer en obert)
openssl genrsa -out public_private.pem 1024
# extreu la clau pública
opensslrsa -inpublic_private.pem-out public.pem -outform PEM -pubout
# extreu la clau privada
opensslrsa -inpublic_private.pem-outprivate.pem -outform PEM -des3# fitxer que xifrarem o signarem
echo "toto" > toto.txt# xifra (un document petit) amb la clau pública
openssl pkeyutl -encrypt -inkey public_private.pem -pubin -in toto.txt -out toto_publica.ssl
# desxifra amb la clau privada
opensslpkeyutl-decrypt -inkey public_private.pem -in toto_publica.ssl -out toto_publica.txt[openssl pkeyutl -decrypt -inkey private.pem -in toto_publica.ssl -out toto_publica.txt]# (potser el que cal és fer una signatura)
# xifra(un document petit)amb la clau privada
opensslpkeyutl-encrypt -inkey public_private.pem -in toto.txt -out toto_privada.ssl
# desxifra amb la clau pública
opensslpkeyutl-decrypt -inkey public_private.pem -pubin -in toto_privada.ssl -out toto_privada.txt
#(no funciona amb public.pem, perquè -decrypt espera una clau privada):
openssl pkeyutl -decrypt -inkey public.pem -pubin -in toto_privada.ssl -out toto_privada.txt# xifra(un document petit)amb la clau pública (continguda en un certificat)
opensslpkeyutl-encrypt -certin -inkey certificate.crt -in toto.txt -out toto_publica.ssl
# desxifra amb la clau privada
opensslpkeyutl-decrypt -inkey public_private.pem -in toto_publica.ssl -out toto_publica.txt- # en lloc de fer això cal fer una
signatura digital
# xifra amb la clau privada
openssl pkeyutl -encrypt -inkey public_private.pem -in toto.txt -out toto_privada.ssl
# desxifra amb la clau pública (continguda en un certificat)
openssl pkeyutl -decrypt -certin -inkey cetificate.crt -in file_privada.ssl -out toto_privada.txt # xifra un fitxer gran amb una clau simètrica i xifra la clau simètrica amb la clau pública del receptor
opensslsmime-encrypt -aes128 -in big_toto.txt -out big_toto.msg user.pem
# desxifra
opensslsmime-decrypt -in big_toto.msg -recip mymit.pem -inkey mymit.pem -out big_toto.original.txt# fa un digest d'un fitxer
echo -n "toto" |openssl dgst -sha1 -binary# xifra un fitxer petit (amb la clau privada) (si el fitxer petit és un digest, això es coneix com a signatura)
openssl pkeyutl -sign -inkeypublic_private.pem-in toto.txt -out toto_signed.txt
# desxifra el fitxer petit (amb la clau pública) (si això era una signatura, vol dir que recupera el digest)
openssl rsautl-verify -inkey public.pem -pubin -in toto_signed.txt
openssl pkeyutl -verifyrecover -inkey public_private.pem -in toto_signed.txt
openssl pkeyutl -verifyrecover -inkey public.pem -pubin -intoto_signed.txt
#desxifra el fitxer petit (amb la clau pública continguda en un certificat) (si això era una signatura, vol dir que recupera el digest)
opensslpkeyutl-verifyrecover -certin -inkey certificate.crt -intoto_signed.txt# desxifra el fitxer petit amb la clau pública (per tant obté el digest) i el compara amb el digest original (-sigfile)
opensslpkeyutl-verify -inkey public_private.pem -in toto.txt -sigfile toto_signed.txt
opensslpkeyutl-verify -inkey public.pem -pubin -in toto.txt -sigfile toto_signed.txt
#desxifra el fitxer petit amb la clau pública continguda en un certificat (per tant obté el digest) i el compara amb el digest original (-sigfile)
opensslpkeyutl-verify -certin -inkey certificate.crt -in toto.txt -sigfile toto_signed.txt# obté el digest d'un fitxer openssl dgst -sha256 -binary -out toto.sha256 toto.txt
# xifra el digest (amb la clau privada): això és la signatura
openssl pkeyutl -sign -inkey public_private.pem -in toto.sha256 -out toto.sha256.encrypted
# desxifra la signatura amb la clau pública
openssl rsautl -verify -inkey public.pem -pubin -in toto.sha256.encrypted --out toto.sha256.decrypted
# comprova que coincideixen
diff toto.sha256 toto.sha256.decrypted# signa un fitxer gran (en fa un digest i el xifra amb la clau privada)
# Per què no dóna el mateix que fer un digest i després xifrar-lo amb la clau privada?: (M2Crypto signature algorithm: algorithmIdentifier in PKCS#1)
# Perquè toto.sha256.encrypted té 32 bytes i big_toto.signature en té 51 bytes (19 (què són?) + els mateixos 32 que toto.sha256.encrypted)
openssl dgst -sign public_private.pem -out big_toto.signature big_toto.txt
# verifica (amb la clau pública, aïllada)
openssl dgst-verifypublic.pem-signaturebig_toto.signature big_toto.txt# signa un fitxer gran i encapsula el fitxer original i la signatura (PKCS#7: application/x-pkcs7-mime)
openssl smime -sign -in big_toto.txt -out big_toto.msg -signer mycert.pem ...
# verifica
openssl smime -verify -in big_toto.msg -CAfile my_ca.pem -out toto_big.extracted.txt
- Codificació / Encoding
- Certification
Authority
(CA) (root, autosigned)
- Single commands (in any directory) (Creating
and using SSL certificates):
[mkdir CA; cd CA;] mkdir newcerts private; echo '01' >serial; touch index.txtopenssl.cnf#### begin of general configuration for "req" ####
[ req ]
default_bits = 2048 # Size of keys
default_md = sha1 # message digest algorithm
string_mask = nombstr # permitted characters
distinguished_name = req_distinguished_name
#req_extensions = v3_req
[ req_distinguished_name ]
# Variable name Prompt string
#---------------------- ----------------------------------
0.organizationName = Organization Name (company)
organizationalUnitName = Organizational Unit Name (department, division)
emailAddress = Email Address
emailAddress_max = 40
localityName = Locality Name (city, district)
stateOrProvinceName = State or Province Name (full name)
countryName = Country Name (2 letter code)
countryName_min = 2
countryName_max = 2
commonName = Common Name (hostname, IP, or your name)
commonName_max = 64
# Default values for the above, for consistency and less typing.
# Variable name Value
#------------------------------ ------------------------------
0.organizationName_default = My Company
localityName_default = Metropolis
stateOrProvinceName_default = New York
countryName_default = AD
#### end of general configuration for "req" ######## extensions for "ca" ####
[ v3_ca_root ]
basicConstraints = critical,CA:TRUE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
- Crea unes claus (-keyout), crea un nou (-new) CSR
(req), l'autosigna i crea un certificat (-x509) amb els
paràmetres definits dins de la secció [req] del fitxer
de configuració (-config) i les extensions especificades
(-extensions), també definides dins del fitxer de
configuració:
openssl req -new -x509 -extensions v3_ca_root -keyout private/rootcakey.pem -out rootcacert.pem -days 365 -config ./openssl.cnf
-subj /O=Empresa1/C=UK/CN=Empresa1\ Root\ CA/-passout "pass:contrasenya"
- copy generated files:
cp private/rootcakey.pem /etc/pki/tls/private/rootcakey.pemcp rootcacert.pem /etc/pki/tls/rootcacert.pem
- Script:
cd /etc/pki/tlsmisc/CA.pl -newca- Common Name (eg, your name or your server's hostname) []: authority CA
- Problem:
- misc/CA no
funciona! Workaround to avoid bugs in
misc/CA:
mkdir /etc/pki/tls/newcerts
touch /etc/pki/tls/index.txt
...
- misc/CA no
funciona! Workaround to avoid bugs in
misc/CA:
- Renovació / Renewal
Resignar amb x509 i -signkey
openssl x509 -in ORIGINAL_CACERT -signkey ORIGINAL_PRIVATE_KEY -days 3650 -out new_cert.crt- Problemes:
- amb 23725 dies (65 anys) funciona; amb 25550 (70 anys) no funciona
- no es poden especificar -startdate i -enddate (són per a extreure aquesta informació, i per tant no accepten paràmetres)
- Re:
Renewing
a CA root certificate
- Prepareu un directori:
mkdir tests; cd tests
- Creeu un fitxer amb el mateix número de sèrie del
certificat actual:
echo "00" > serial- si no és "00", per a obtenir el número de
sèrie del certificat actual:
openssl x509 -in ORIGINAL_CACERT -noout -serial
- Creeu una base de dades de certificats buida:
touch index.txt
- Obtingueu un CSR a partir del certificat actual,
signat amb les claus actuals (-signkey):
openssl x509 -x509toreq -in ORIGINAL_CACERT -signkey ORIGINAL_PRIVATE_KEY -out certreq.csr
- Signeu (ca) aquest csr (-in) amb el certificat
(-cert) de la CA actual, amb dates d'inici
(-startdate) i final (-enddate) especificades, amb
paràmetres definits dins de la secció [ca] del
fitxer de configuració (-conf) i les extensions
especificades (-extensions), també definides dins
del fitxer de configuració:
openssl ca -config CONF_FILE.cnf -startdate STARTDATE -enddate ENDDATE -in certreq.csr -out cacert_renewed.pem -keyfile ORIGINAL_PRIVATE_KEY -certORIGINAL_CACERT -extensions ca_ext- per a obtenir les dates del certificat actual:
openssl x509 -in ORIGINAL_CACERT -noout -dates
- i les haureu d'expressar en format
[YY]YYMMDDhhmmssZ([YY]només s'ha d'especificar si indiqueu un segle diferent a l'actual)
- Prepareu un directori:
- own Certificate Authority: Renewal of CA cert
- Single commands (in any directory) (Creating
and using SSL certificates):
- Certification
Authority
(CA) (non-root)
- Single commands (in any directory) (Multi-level
CAs: openssl.cnf)
cd CAopenssl.cnf(el mateix que més amunt / same as above)#### begin of general configuration for "req" ####
[req]
...
#### end of general configuration for "req" ####
- Crea unes noves claus (-keyout) i crea un nou (-new)
CSR (req), amb els paràmetres especificats dins de la
secció [req] del fitxer de configuració (-config):
openssl req -new -keyout private/cakey.pem -out cacsr.pem -days 365 -config ./openssl.cnf
-subj /O=Empresa2/C=UK/CN=Empresa2\ CA/
openssl.cnf#### extensions for "ca" ####
[ v3_ca ]
basicConstraints = critical,CA:TRUE
subjectKeyIdentifier = hash#authorityKeyIdentifier = keyid:always,issuer:alwaysauthorityKeyIdentifier = keyid,issuer:always
- Signa (ca) un CSR (-infiles) amb el certificat (-cert)
de la CA root i les claus (-keyfile) de la CA arrel, i
crea un certificat (-out) amb els paràmetres
especificats dins de la secció [ca] del fitxer de
configuració (-config) i les extensions (-extensions)
corresponents, també especificades al fitxer de
configuració (-config):
openssl ca -name ca_root -cert rootcacert.pem -keyfile private/rootcakey.pem -extensions v3_ca -out cacert.pem -config ../openssl.cnf -infiles cacsr.pem
- Copia els fitxers generats / Copy generated files:
cp private/cakey.pem /etc/pki/tls/private/cakey.pemcp cacert.pem /etc/pki/tls/cacert.pem
- Single commands (in any directory) (Multi-level
CAs: openssl.cnf)
- Certificat
digital
/ Digital certificate
- Estructura / Structure (X509)
- Allowing
non-unique
subjects (
"TXT_DB error number 2")index.txt.attr
- subjectAltName
- Expedició de certificat
de servidor / Server certificate expedition:
- Single commands:
cd CA- Crea unes noves claus (-keyout) i crea un nou
(-new) CSR (req) de nom especificat (-out), amb els
paràmetres definits dins de la secció [req] del
fitxer de configuració (-config):
openssl req -new -keyout private/hostname_server.key -out newcerts/hostname_server.csr -days 365 -config ./openssl.cnf
-passout "pass:contrasenya"-subj /O=Organitzacio/C=AD/CN=El\ meu\ nom/
openssl.cnfdir = .#### begin of general configuration for "ca" ####
[ ca ]
default_ca = ca_default
[ ca_default ]
serial = $dir/serial
database = $dir/index.txt
new_certs_dir = $dir/newcerts
#certificate = $dir/cacert.pem
#private_key = $dir/private/cakey.pem
default_days = 365
default_md = sha256
preserve = no
email_in_dn = no
name_opt = ca_default
cert_opt = ca_default
policy = policy_match
[ policy_match ]
countryName = match
stateOrProvinceName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
#### end of general configuration for "ca" ######## begin of general configuration for "req" ####
[ req ]
...
#### end of general configuration for "req" ######## extensions for "ca" ####
[ v3_ca_server ]
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = critical, serverAuth
- Signa (ca) un CSR (-infiles) amb el certificat
(-cert) de la CA i les claus (-keyfile) de la CA, i
crea un certificat de nom especificat (-out) amb els
paràmetres definits dins de la secció [ca] del
fitxer de configuració (-config) i les extensions
(-extensions) corresponents, també especificades al
fitxer de configuració (-config):
openssl ca -cert cacert.pem -keyfile private/cakey.pem -extensions v3_ca_server -out newcerts/hostname_server.crt -config ./openssl.cnf ... -infiles newcerts/hostname_server.csr
-passin pass:contrasenya_ca-batch
- Copia els fitxers generats / Copy generated files:
cp newcerts/hostname_server.crt /etc/pki/tls/certs/hostname_server.crt
- Script:
cd /etc/pki/tls
misc/CA.pl -newreq- Common Name (eg, your name or your server's hostname) []: hostname
- "hostname" must match "ServerName" in Apache configuration
misc/CA.pl-sign- move the generated files:
mv newkey.pem private/hostname_server.keymv newreq.pem certs/hostname_server.csrmv newcert.pem certs/hostname_server.crt
- Single commands:
- Expedició de certificat de
client / Client certificate expedition:
- Single commands:
cd CA- Crea unes noves claus (-keyout) i crea un nou
(-new) CSR (req) de nom especificat (-out), amb els
paràmetres definits dins de la secció [req] del
fitxer de configuració (-config):
openssl req -new -keyout private/client1.key -out newcerts/client1.csr -days 365 -config ./openssl.cnf
-passout "pass:contrasenya"
- openssl.cnf
#### extensions for "ca" ####
[ v3_ca_client ]
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = critical, clientAuth
- Signa (ca) un CSR (-infiles) amb el certificat
(-cert) de la CA i les claus (-keyfile) de la CA, i
crea un certificat (-out) amb els paràmetres
definits dins de la secció [ca] del fitxer de
configuració (-config) i les extensions
(-extensions) corresponents, també especificades al
fitxer de configuració (-config):
openssl ca-cert cacert.pem -keyfile private/cakey.pem-extensions v3_ca_client -out newcerts/client1.crt -config ./openssl.cnf ... -infiles newcerts/client1.csr
-passin pass:contrasenya_ca-batch
- Problemes / Problems:
entry xx: invalid expiry date- l'entrada xx-èsima del fitxer index.txt està corrompuda perquè la data d'expiració no és correcta (probablement buida) / the xx-th entry in file index.txt is corrupted because the expiration date is not correct (probably empty)
- Solució / Solution
- esborreu la xx-èsima línia del fitxer
index.txt i decrementeu una unitat el
valor hexadecimal contingut al fitxer
serial/ delete the xx-th line in index.txt and decrement the hexadecimal value inserialfile
- esborreu la xx-èsima línia del fitxer
index.txt i decrementeu una unitat el
valor hexadecimal contingut al fitxer
- encapsulate the resulting files into a pkcs12 file
- Script:
cd /etc/pki/tls
misc/CA.pl-newreq- Common Name (eg, your name or your server's hostname) []: clientname
misc/CA.pl-sign- encapsulate the resulting files into a pkcs12 file
- move the generated files:
mv newkey.pem private/client1.keymv newreq.pem certs/client1.csrmv newcert.pem certs/client1.crt
- Single commands:
- Encapsulació /
Encapsulation
-
PKCS12
JKS
file extension
.p12
.jks
general password for file
Import password
Key store password
password for key
PEM pass phrase
Key password
certificate #1
friendlyName
alias
certificate #2 friendlyName alias ...
Aquesta taula continua cap a la dreta — desplaça-la o gira el mòbil.
- Encapsulació
/
Encapsulation PKCS
#12
- How to Use OpenSSL to Create PKCS#12 Certificate Files
- pkcs12 = [client_pem.crt] + [client_pem.key] + [root_ca_pem.crt]
- Single commands:
- Si els fitxers no han estat generats amb
openssl, caldrà una conversió
prèvia (si els fitxers .crt i .key generats amb
openssl, ja són, per omissió, en format PEM):
openssl x509 -in root_ca.crt -inform DER -out root_ca_pem.crt -outform PEMopenssl x509 -in client.crt -inform DER -out client_pem.crt -outform PEMopenssl rsa -in client.key -inform DER -out client_pem.key -outform PEM
openssl pkcs12 -name "Nom client" -export -in client_pem.crt -inkey client_pem.key [-certfile root_ca_pem.crt] -out bundle.p12- si no es vol incloure la clau privada:
openssl pkcs12 -name "Nom client" -export -in client_pem.crt [-certfile root_ca_pem.crt] -nokeys -out bundle.p12
- Si els fitxers no han estat generats amb
openssl, caldrà una conversió
prèvia (si els fitxers .crt i .key generats amb
openssl, ja són, per omissió, en format PEM):
- Script:
cd /etc/pki/tls
- bug
into misc/CA: (use miscCA.pl instead!)
- $PKCS12 -in newcert.pem -inkey newcert.pem -certfile ${CATOP}/$CACERT\
- $PKCS12 -in newcert.pem -inkey newkey.pem -certfile ${CATOP}/$CACERT\
- argument will be the friendlyName ("Client 1"
in the following example)
misc/CA.pl-pkcs12 "Client 1"- move the generated files:
mv newcert.p12 certs/client1.p12
- Inspecció d'un fitxer PKCS12 / Inspection of a
PKCS12 file:
openssl pkcs12 -in client1.p12
- Encapsulació JKS / JKS encapsulation
- Extracció de certificat cap a format PEM (-rfc).
Caldrà especificar la «Key store password».
keytool -keystore all_my_domains_keystore.jks -alias my_domain -exportcert -rfc -file mydomain.pem
- Extracció de clau privada cap a format PKCS12.
Caldrà especificar la «destination keystore
password» (2 vegades si es crea, 1 si ja existia) i
«source keystore password».
keytool -importkeystore -srckeystoreall_my_domains_keystore.jks -deststoretype PKCS12 -destkeystoremydomain.p12
- Extracció de certificat cap a format PEM (-rfc).
Caldrà especificar la «Key store password».
-
- Inspecció
/ Inspection:
file extensions
content (BEGIN/END)
openssl command
ENCRYPTED/RSA PRIVATE KEY
CERTIFICATE REQUEST
CERTIFICATE
- key
- pem
x
openssl rsa -noout -text -in toto.key
- csr
x
openssl req -noout -text -in toto.csr
- crt
- pem
x
openssl x509 -noout -text -in toto.crt- codi C:
openssl x509 -noout -C -in toto.crt
opensslx509-noout -subject -in toto.crt-
openssl x509 -subject -noout -nameopt sep_multiline -in toto.crt | awk '/CN/ {split($1,elements,"=") ; print elements[2] ;}' not_after_date=$(date '+%Y-%m-%dT%H%M%SZ' --utc -d "$(openssl x509 -dates -noout -nameopt sep_multiline -in toto.pem | awk -F= '/notAfter/ {print $2;}')")
- cer
x
openssl x509 -inform der -noout -text -in toto.cer
- p7
x
openssl pkcs7 -inform DER -in toto.p7 -print_certs -noout
- pk12
- p12
x
x
opensslpkcs12-in toto.p12- print keys without DES encryption:
... -nodes ...
- print only client certificates and key:
... -clcerts ...
- print only CA certificates and key:
... -cacerts ...
- print certificate chain: client certificates
and CA certificates
... -nokeys ...
Aquesta taula continua cap a la dreta — desplaça-la o gira el mòbil.
ssh-keygen -lf toto.pemssh-keygen -lf toto.pem.pub
- Verificació / Verification
- Verifica un certificat utilitzant el certificat de la
CA que l'ha emès directament (-CAfile) i els certificats
de les CA superiors en la cadena PKI (-CApath):
openssl verify -CAfile ca.crt -CApath /path/to/ca_dir/ -verbose server.crt
- Per a PKI amb més d'un nivell de CA / For PKI with
more than one level of CA, cal reanomenar (o enllaçar)
els certificats amb el seu hash:
cd /path/to/ca_dir/ln -s root_ca.crt `openssl x509 -hash -noout -in root_ca.crt`.0
- Check
whether
your private key matches your SSL certificate:
- Comproveu que les tres respostes següent
coincideixen / Check that the following are the same
(you can add "| openssl md5" to facilitate the
comparison)
openssl x509 -noout -modulus -in certificate.crtopenssl rsa -noout -modulus -in privateKey.keyopenssl req -noout -modulus -in CSR.csr
- Comproveu que les tres respostes següent
coincideixen / Check that the following are the same
(you can add "| openssl md5" to facilitate the
comparison)
- Verifica un certificat utilitzant el certificat de la
CA que l'ha emès directament (-CAfile) i els certificats
de les CA superiors en la cadena PKI (-CApath):
- Convert
certificate format from DER to PEM (not needed if crt file
has been generated by openssl):
openssl x509 -in ACRAIZ-SHA1.crt -inform DER -out ACRAIZ-SHA1.crt -outform PEM
- Revocació
de certificats / Certificate revocation
- CRL options
- How to generate certificate revocation list (CRL)
- Configuring mod_ssl with CRLs (crontab)
- Certificate management
- Single commands:
cd CA
echo "01" > crlnumber_filemkdir crl- openssl.cnf
- [crl_ext]
crlnumber=crlnumber_file
- [crl_ext]
openssl ca[-cert cacert.pem -keyfile private/cakey.pem]-revoke newcerts/client2.crtopenssl ca[-cert cacert.pem -keyfile private/cakey.pem]-crlexts crl_ext -gencrl -keyfile private/cakey.pem -cert cacert.pem -out crl/cacrl.pem -crldays 30
- CRL Apache server configuration:
SSLCARevocationFile /etc/pki/tls/crl/cacrl.pem
- Client SSL
openssls_client -connect www.yourserver.com:443 </dev/nullopenssls_client -connect imap.yourserver.com:993</dev/nullopenssls_client -connect smtp.yourserver.com:465</dev/null- AWS CloudFront
- openssl tool cannot get certificate from CloudFront, does anyone know why?
openssls_client -servername www.yourserver.com -connect www.yourserver.com:443
- Força/Force TLSv1:
-tls1- Disable TLS 1.0 in NGINX
- Força/Force TLSv1.2:
-tls1_2
- Recupera el certificat de la CA d'un servidor www:
echo | openssl s_client -connect remote_server:8443 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > mycert.pem
- Eines relacionades / Related tools
- Resum / Summary (default config file:
/etc/pki/tls/openssl.cnf, default newcerts directory:
/etc/pki/tls/newcerts):
option 1 option 2 option 3 option 4
command
notes
command
notes
command
notes
command
self signed certificate (e.g. CA)
key generation
openssl genrsa -des3 -out ca.key 2048
openssl genrsa -des3 -out ca.key 2048
openssl req -new [-nodes] [-newkey rsa:1024] -keyout ca_nova.key -sha256 -x509 [-days 365] -out ca.crt
- for https server:
- openssl req -new -nodes -keyout mycert.key -sha256 -x509 -out mycert.pem
cd /etc/pki/tls/certs; make ...
request generation
openssl req -new -key ca.key -out ca.csr
openssl req -new -x509 -key ca.key -out ca.crt
certificate generation
openssl x509 -req -in ca.csr -signkey ca.key -out ca.crt
Version: 1 (0x0)
Version: 3 (0x2)
X509v3 Subject Key Identifier
X509v3 Authority Key Identifier
X509v3 Basic Constraints:
CA:TRUEVersion: 3 (0x2)
X509v3 Subject Key Identifier
X509v3 Authority Key Identifier
X509v3 Basic Constraints:
CA:TRUEcertificate signed by a CA
key generation openssl genrsa -des3 -out toto.key 2048
request generation openssl req -new -key toto.key -out toto.csr
certificate generation openssl x509 -req -in toto.csr -CA ca.crt -CAkey ca.key -set_serial 01 [-days 365] -out toto.crt
no database is created
mkdir newcerts
echo '01' > serial
touch index.txt index.txt.attr
ca.cnf:
[ca]
default_ca = ca_omissio
[ca_omissio]
dir=.
serial = $dir/serial
database = $dir/index.txt
new_certs_dir = $dir/newcerts
default_days = 365
default_md = sha256
policy = politica_omissio
[politica_omissio]
openssl ca -config ./ca.cnf -in toto.csr -cert ca.crt -keyfile ca.key -out toto.crt
Aquesta taula continua cap a la dreta — desplaça-la o gira el mòbil.
key, request and certificate generation generated file
referenced into Apache config file (*.conf)
method
function
step
openssl (command line) extensions
(x509v3_config)
/etc/pki/tls/ misc/CA (script) name
BEGIN directive
value
self signed
server
server key
openssl genrsa -des3 -out hostname_server.key 4096
hostname_server.key
RSA PRIVATE KEY
SSLCertificateKeyFile
/etc/pki/tls/private/server.key
server request for signing
openssl req -new -key hostname_server.key -out hostname_server.csr
hostname_server.csr
CERTIFICATE REQUEST
server certificate (self signed)
openssl x509 -req -days 365 -in hostname_server.csr -signkey hostname_server.key -out hostname_server.crt
hostname_server.crt
CERTIFICATE SSLCertificateFile/etc/pki/tls/certs/server.crt
CA + signed
CA
CA key
openssl genrsa -des3 -out ca.key 4096
ca.key RSA PRIVATE KEY
misc/CA.pl -newca /etc/pki/tls/private/cakey.pem
CA request for signing
/etc/pki/tls/careq.pem CERTIFICATE REQUEST
CA certificate
/etc/pki/tls/cacert.pem
(must be moved to /etc/pki/tls/certs/ca.crt)CERTIFICATE (only for client certificate request)
SSLCACertificateFile/etc/pki/tls/certs/ca.crt openssl req -new -x509 -days 365 -key ca.key -out ca.crt basicConstraints = critical,CA:TRUE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
ca.crt
server
server key openssl genrsa -des3 -out hostname_server.key 4096
hostname_server.key RSA PRIVATE KEY SSLCertificateKeyFile
/etc/pki/tls/private/hostname_server.key
misc/CA.pl -newreq /etc/pki/tls/newkey.pem
(must be moved to private/hostname_server.key)server request for signing
/etc/pki/tls/newreq.pem CERTIFICATE REQUEST (CN in the certifcate must be exactly the same as "ServerName" in Apache configuration)
openssl req -new -key hostname_server.key -out hostname_server.csr
hostname_server.csr
server certificate (signed by CA)
openssl x509 -req -days 365 -in hostname_server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out hostname_server.crt
hostname_server.crt CERTIFICATE SSLCertificateFile
/etc/pki/tls/certs/hostname_server.crt
openssl ca ...
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = critical, serverAuthmisc/CA.pl -sign /etc/pki/tls/newcert.pem
(must be moved to certs/hostname_server.crt)
client
client key
misc/CA.pl -newreq /etc/pki/tls/newkey.pem
client request for signing
/etc/pki/tls/newreq.pem
client certificate (signed by CA)
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = critical, clientAuthmisc/CA.pl -sign /etc/pki/tls/newcert.pem
client certificate in PKCS12 file format
misc/CA.pl -pkcs12 /etc/pki/tls/newcert.p12
(to be imported by the client www browser)
CA root + CA
CA root
CA root key
openssl genrsa -des3 -out ca_root.key 4096 -
CA root certificate (autosigned)
...
basicConstraints = critical,CA:TRUE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
CA
CA key
CA request for signing
CA certificate (signed by CA root)
basicConstraints = critical,CA:TRUE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
Aquesta taula continua cap a la dreta — desplaça-la o gira el mòbil.
- for https server:
- Desenvolupament / Development
- Prerequisits
urpmi libopenssl-develapt-get install ...
- Documentació
/ Documentation (docs/crypto/)
(SSLeay
documentation)
- Symmetric cyphers
- Public key cryptography and key agreement
- Certificates
- x509
(certificates) (SSLeay:
X.509
Routines, Index
of X.509 Routines)
- Functions
- d2i_X509(3) - DER to internal
- d2i_X509_NAME
- X509_get_subject_name
- X509_NAME_cmp
- X509_NAME_get_text_by_NID (NID)
- X509_STORE - General configuration for
certificate validation
- X509_STORE_add_cert
- X509_STORE_add_lookup
- X509_LOOKUP_load_file
- X509_STORE_load_locations
- ...
- X509_STORE_CTX - Just to perform one
validation
- X509_STORE_CTX_init
- X509_verify_cert
- Examples
- Overview of X.509 certificate verification (SSLeay)
- what is the difference between X509_STORE and X509_STORE_CTX .?
- OpenSSL + c++: How do you verify a public key was issued by your private CA?
- x509 certificate verification in C
- How to check in opensll c++ if a string is a certificate, and if so, if that string is root certificate (detection of root certificates) (X509_get_subject_name, X509_NAME, X509_NAME_cmp)
- faled to read serial number(ASN1_INTEGER) from x509 certiticate using openssl (X509_NAME_get_text_by_NID, NID_commonName)
- Functions
- x509
(certificates) (SSLeay:
X.509
Routines, Index
of X.509 Routines)
- Authentication codes, hash
functions
- SHA
- Functions
- SHA1_Init(), SHA1_Update() and SHA1_Final()
- Functions
- ...
- SHA
- Auxiliary functions
- Input/Output, data encoding (SSLeay:
Cryptographic
Support Routines)
- BIO
(SSLeay:
BIO Routines)
- Funcions
- BIO_f_base64 (examples)
- Examples
- Funcions
- EVP
(Envelope encryption)
- Functions
- EVP_SignInit, EVP_SignUpdate, EVP_SignFinal - EVP signing functions
- EVP_VerifyInit, EVP_VerifyUpdate, EVP_VerifyFinal - EVP signature verification functions
- EVP_DigestInit - Message digests
- EVP_PKEY_verify_recover
- ...
- Examples
- Create signature (of hash) with openssl c api (openssl_sign.c: PEM_read_RSAPrivateKey, EVP_SignInit_ex, EVP_SignUpdate, EVP_SignFinal)
- Simple way to implement public-key cryptography in C++? (license signature)
- Can you help me get my head around openssl public key encryption with rsa.h in c++? (EVP)
- Functions
- PEM
- Functions
- PEM_read_RSAPrivateKey
- PEM_read_RSA_PUBKEY
- ...
- Examples
- ...
- Functions
- PKCS12
- Functions
- d2i_PKCS12_fp
- d2i_PKCS12_bio
- PKCS12_verify_mac
- PKCS12_parse
- Examples
- apps/pkcs12.c
- get_cert_chain /* Given a single certificate return a verified chain or NULL if error */
- demos/pkcs12/pkread.c
- How to load a PKCS#12 file in OpenSSL programmatically? (d2i_PKCS12_fp(), d2i_PKCS12_bio(), PKCS12_verify_mac, PKCS12_parse())
- apps/pkcs12.c
- Functions
- BIO
(SSLeay:
BIO Routines)
- Internal functions
- Exemples /
Examples:
- OpenSSL demos
- How to generate RSA private key using openssl in C? NOT using Terminal
- openssl.net rsa encryption working example needed
-
script C
Python Android
API
example
M2Crypto API example
clau
acció
clau
acció
hash
# hash
SHA1
SHA1_Init
SHA1_Update
SHA1_Final
const char *orig = "Original String"; unsigned char hash[20];
SHA1(orig, strlen(orig), hash);
signature
# fa un digest i el signaecho -n "toto" | openssl dgst -sha1 -sign pub_priv.key | openssl enc -base64openssl dgst -sha1 -sign private.key -out toto.sha1.signed toto.txt
# comprova la signatura
openssl dgst -sha1 -verify public.key -signature toto.sha1.signed toto.txt
# signa (fa servir la clau privada)
openssl pkeyutl -sign -inkeypublic_private.pem-in toto.txt -out toto_signed.txtPEM_read_RSAPrivateKey EVP_SignInit_ex
EVP_SignUpdate
EVP_SignFinal
- openssl_sign.c
- demos/sign/sign.c
# recupera el document signat (fa servir la clau pública)openssl pkeyutl -verifyrecover -inkey public_private.pem -intoto_signed.txtPEM_read_PUBKEY EVP_PKEY_verify_recover
- apps/pkeyutl.c
# recupera el document signat (fa servir la clau pública del certificat)
openssl pkeyutl -verifyrecover -certin -inkey certificate.crt -intoto_signed.txtx509 = PEM_read_X509(fp, NULL, NULL, NULL);
pkey=X509_get_pubkey(x509);
# comprova la signatura (fa servir la clau pública)i el compara amb el fitxer original
openssl pkeyutl -verify -inkey public_private.pem -in toto.txt -sigfile toto_signed.txtPEM_read_PUBKEY EVP_VerifyInit
EVP_VerifyUpdate
EVP_VerifyFinal
# comprova la signatura (fa servir la clau pública del certificat) i el compara amb el fitxer original
openssl pkeyutl -verify -certin -inkey certificate.crt -in toto.txt -sigfile toto_signed.txtx509 = PEM_read_X509(fp, NULL, NULL, NULL);
pkey=X509_get_pubkey(x509);- demos/sign/sign.c
certificates
# certificate request
openssl req -new ...
- demos/x509/mkreq.c
Aquesta taula continua cap a la dreta — desplaça-la o gira el mòbil.
- Prerequisits
http://www.francescpinyol.cat/tls.html
Primera versió: / First version: 18 XII.2012
Darrera modificació: 10 de novembre de 2024 / Last update: 10th
November 2024