TLS

Index

General

Està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 -


    • DTLS
  • 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


      • OpenSSL X.509 config
    • PKCS
      • PKCS#10: Certificate request
      • PKCS#12: Certificate encapsulation
    • Format (conversió/conversion)
      • DER
        • binary
      • PEM
        • -----BEGIN CERTIFICATE-----
          base64
          -----END CERTIFICATE-----
    • Encapsulació / Encapsulation

      key
      format

      pub
      priv
      DER
      (binary)
      PEM
      (base64 text)
      only asymmetric key




      X.509


      .crt, .der
      .pem
      X.509 / PKCS#7
      x
      -
      .p7c, .p7b, .p7s, .p7m
      X.509 / PKCS#12 x
      x
      .p12, .pfx

Programari / Software

  • OpenSSL
  • gnutls
    • Instal·lació / Installation
      • Mageia
        • dnf install gnutls
    • certtool
      • inspection
        • certtool -i <fullchain.pem

OpenSSL

  • OpenSSL / LibreSSL
  • 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 ()
      • 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:
    • 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
  • 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"
  • Generació de contrasenyes / Keyword generation
    • 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

    • 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-----
      openssl rsa -in private_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@localhost
      • ssh-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 ...
      Note: option "-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:
        • openssl genrsa -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
        • openssl genrsa -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
    • Extracció / Extraction
      • extracció de la clau pública / extraction of public key:
        • openssl rsa -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:
        • openssl rsa -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]):
        • openssl rsa -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

          • output
            -f toto -e [-m RFC4716] ---- BEGIN SSH2 PUBLIC KEY ----
            ...
            ---- END SSH2 PUBLIC KEY ----
            -f toto -e -m PEM -----BEGIN RSA PUBLIC KEY-----
            ...
            -----END RSA PUBLIC KEY-----
            -f toto -e -m PKCS8 -----BEGIN PUBLIC KEY-----
            ...
            -----END 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
    • # default algorithm: sha256
      openssl dgst [-sha256] big_toto.txt

    • openssl dgst -md5 big_toto.txt
    • openssl dgst -sha1 big_toto.txt
    • openssl list --digest-commands
  • 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
      openssl
      rsa -in public_private.pem -out public.pem -outform PEM -pubout
      # extreu la clau privada
      openssl
      rsa -in public_private.pem -out private.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
      openssl
      pkeyutl -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
      openssl
      pkeyutl -encrypt -inkey public_private.pem -in toto.txt -out toto_privada.ssl
      # desxifra amb la clau pública

      openssl pkeyutl -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)
      openssl pkeyutl -encrypt -certin -inkey certificate.crt -in toto.txt -out toto_publica.ssl
      # desxifra amb la clau privada
      openssl pkeyutl -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
      openssl
      smime -encrypt -aes128 -in big_toto.txt -out big_toto.msg user.pem

      # desxifra
      openssl
      smime -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 -inkey
      public_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 -in toto_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)
      openssl pkeyutl -verifyrecover -certin -inkey certificate.crt -in toto_signed.txt
      # desxifra el fitxer petit amb la clau pública (per tant obté el digest) i el compara amb el digest original (-sigfile)
      openssl
      pkeyutl -verify -inkey public_private.pem -in toto.txt -sigfile toto_signed.txt
      openssl pkeyutl -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)
      openssl pkeyutl -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
      -verify public.pem -signature big_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
    • base64
      • openssl enc -base64 ...
      • url safe
        • encoding
          • openssl enc -base64 | tr '-_' '+/'
        • decoding
          • echo "" | tr '' ''
  • Certification Authority (CA) (root, autosigned)
    • Single commands (in any directory) (Creating and using SSL certificates):
      1. [mkdir CA; cd CA;] mkdir newcerts private; echo '01' >serial; touch index.txt
      2. openssl.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
      3. 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"
      4. copy generated files:
        • cp private/rootcakey.pem /etc/pki/tls/private/rootcakey.pem
        • cp rootcacert.pem /etc/pki/tls/rootcacert.pem
    • Script:
      • cd /etc/pki/tls
      • misc/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

            ...
    • 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
        1. Prepareu un directori:
          • mkdir tests; cd tests
        2. 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
        3. Creeu una base de dades de certificats buida:
          • touch index.txt
        4. 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
        5. 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)
      • own Certificate Authority: Renewal of CA cert
  • Certification Authority (CA) (non-root)
    • Single commands (in any directory) (Multi-level CAs: openssl.cnf)
      1. cd CA
      2. openssl.cnf (el mateix que més amunt / same as above)
        • #### begin of general configuration for "req" ####
          [req]
          ...
          #### end of general configuration for "req" ####
      3. 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/
      4. openssl.cnf
        • #### extensions for "ca" ####
          [ v3_ca ]
          basicConstraints       = critical,CA:TRUE
          subjectKeyIdentifier   = hash
          # authorityKeyIdentifier = keyid:always,issuer:always authorityKeyIdentifier = keyid,issuer:always
      5. 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
      6. Copia els fitxers generats / Copy generated files:
        • cp private/cakey.pem /etc/pki/tls/private/cakey.pem
        • cp cacert.pem /etc/pki/tls/cacert.pem
  • Certificat digital / Digital certificate
    • Estructura / Structure (X509)
    • Allowing non-unique subjects ("TXT_DB error number 2")
    • subjectAltName
    • Expedició de certificat de servidor / Server certificate expedition:
      • Single commands:
        1. cd CA
        2. 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/
        3. openssl.cnf
          • dir = .
          • #### 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
        4. 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
        5. Copia els fitxers generats / Copy generated files:
          • cp newcerts/hostname_server.crt /etc/pki/tls/certs/hostname_server.crt
      • Script:
        1. cd /etc/pki/tls
        2. misc/CA.pl -newreq
          • Common Name (eg, your name or your server's hostname) []: hostname
          • "hostname" must match "ServerName" in Apache configuration
        3. misc/CA.pl -sign
        4. move the generated files:
          • mv newkey.pem private/hostname_server.key
          • mv newreq.pem certs/hostname_server.csr
          • mv newcert.pem certs/hostname_server.crt
    • Expedició de certificat de client / Client certificate expedition:
      • Single commands:
        1. cd CA
        2. 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"
        3. openssl.cnf
        4. 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
        5. 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 in serial file
        6. encapsulate the resulting files into a pkcs12 file
      • Script:
        1. cd /etc/pki/tls
        2. misc/CA.pl -newreq
          • Common Name (eg, your name or your server's hostname) []: clientname
        3. misc/CA.pl -sign
        4. encapsulate the resulting files into a pkcs12 file
        5. move the generated files:
          • mv newkey.pem private/client1.key
          • mv newreq.pem certs/client1.csr
          • mv newcert.pem certs/client1.crt
    • 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
        ...


      • 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 PEM
            • openssl x509 -in client.crt -inform DER -out client_pem.crt -outform PEM
            • openssl 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
            • -passin "pass:contrasenya"
            • -passout "pass:contrasenya"
          • 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
        • 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 -srckeystore all_my_domains_keystore.jks -deststoretype PKCS12 -destkeystore mydomain.p12
    • 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
      • 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
      • openssl pkcs12 -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 ...
      • ssh-keygen -lf toto.pem
      • ssh-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.crt
          • openssl rsa -noout -modulus -in privateKey.key
          • openssl req -noout -modulus -in CSR.csr
    • 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
    • Client SSL
  • 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:TRUE
    Version: 3 (0x2)

    X509v3 Subject Key Identifier
    X509v3 Authority Key Identifier
    X509v3 Basic Constraints:
                    CA:TRUE
    certificate 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






    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, serverAuth
    misc/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, clientAuth
    misc/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





  • Desenvolupament / Development

http://www.francescpinyol.cat/tls.html
Primera versió: / First version: 18 XII.2012
Darrera modificació: 24 d'octubre de 2023 / Last update: 24th October 2023

Valid HTML 4.01!

Cap a casa / Back home