Certificado HTTP y SSL

Índice

Autoridad Certificadora (CA) y certificado autofirmado

Para la creación de una autoridad certificadora, en primer lugar se debe crear un directorio con el esquema de directorios y documentos necesarios para poder configurar la autoridad certificadora.

❯ mkdir CA
mkdir: se ha creado el directorio 'CA'
❯ mkdir CA/{certsdb,certreqs,crl,private}
mkdir: se ha creado el directorio 'CA/certsdb'
mkdir: se ha creado el directorio 'CA/certreqs'
mkdir: se ha creado el directorio 'CA/crl'
mkdir: se ha creado el directorio 'CA/private'
❯ chmod 700 CA/private/
❯ touch CA/index.txt

Así, la estructura de directorios necesaria para la creación de la autoridad certificadora es la siguiente:

❯ tree CA
CA
├── certreqs
├── certsdb
├── crl
├── index.txt
└── private

5 directories, 1 file

Para configurar la autoridad certificadora se puede partir del fichero de configuración de openssl que ya está en el sistema. Este fichero puede estar en varios directorios. En este caso, se encuentra en /etc/ssl/openssl.cnf

❯ sudo cp /etc/ssl/openssl.cnf .

La autoridad certificadora se configura modificando este fichero.

❯ cat openssl.cnf 
#
# OpenSSL example configuration file.
# See doc/man5/config.pod for more info.
#
# This is mostly being used for generation of certificate requests,
# but may be used for auto loading of providers

# Note that you can include other files from the main configuration
# file using the .include directive.
#.include filename

# This definition stops the following lines choking if HOME isn't
# defined.
HOME			= ./

 # Use this in order to automatically load providers.
openssl_conf = openssl_init

# Comment out the next line to ignore configuration errors
config_diagnostics = 1

# Extra OBJECT IDENTIFIER info:
# oid_file       = $ENV::HOME/.oid
oid_section = new_oids

# To use this configuration file with the "-extfile" option of the
# "openssl x509" utility, name here the section containing the
# X.509v3 extensions to use:
# extensions		=
# (Alternatively, use a configuration file that has only
# X.509v3 extensions in its main [= default] section.)

[ new_oids ]
# We can add new OIDs in here for use by 'ca', 'req' and 'ts'.
# Add a simple OID like this:
# testoid1=1.2.3.4
# Or use config file substitution like this:
# testoid2=${testoid1}.5.6

# Policies used by the TSA examples.
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7

# For FIPS
# Optionally include a file that is generated by the OpenSSL fipsinstall
# application. This file contains configuration data required by the OpenSSL
# fips provider. It contains a named section e.g. [fips_sect] which is
# referenced from the [provider_sect] below.
# Refer to the OpenSSL security policy for more information.
# .include fipsmodule.cnf

[openssl_init]
# providers = provider_sect

# List of providers to load
# [provider_sect]
# default = default_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
# fips = fips_sect

# If no providers are activated explicitly, the default one is activated implicitly.
# See man 7 OSSL_PROVIDER-default for more details.
#
# If you add a section explicitly activating any other provider(s), you most
# probably need to explicitly activate the default provider, otherwise it
# becomes unavailable in openssl.  As a consequence applications depending on
# OpenSSL may not work correctly which could lead to significant system
# problems including inability to remotely access the system.
# [default_sect]
# activate = 1


####################################################################
[ ca ]
default_ca	= CA_default		# The default ca section

####################################################################
[ CA_default ]

dir		= ./			# Where everything is kept
certs		= $dir/certsdb		# Where the issued certs are kept
crl_dir		= $dir/crl		# Where the issued crl are kept
database	= $dir/index.txt	# database index file.
#unique_subject	= no			# Set to 'no' to allow creation of
					# several certs with same subject.
new_certs_dir	= $certs		# default place for new certs.

certificate	= $dir/cacert.pem	# The CA certificate
serial		= $dir/serial		# The current serial number
crldir		= $dir/crl
crlnumber	= $dir/crlnumber	# the current crl number
					# must be commented out to leave a V1 CRL
crl		= $dir/crl.pem		# The current CRL
RANDFILE	= $dir/private/.rand
private_key	= $dir/private/cakey.pem# The private key

x509_extensions	= usr_cert		# The extensions to add to the cert

copy_extnesions = copy

# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt	= ca_default		# Subject Name options
cert_opt	= ca_default		# Certificate field options

# Extension copying option: use with caution.
# copy_extensions = copy

# Extensions to add to a CRL. Note: Netscape communicator chokes on V2 CRLs
# so this is commented out by default to leave a V1 CRL.
# crlnumber must also be commented out to leave a V1 CRL.
# crl_extensions	= crl_ext

default_days	= 365			# how long to certify for
default_crl_days= 30			# how long before next CRL
default_md	= sha1			# use public key default MD
preserve	= no			# keep passed DN ordering

# A few difference way of specifying how similar the request should look
# For type CA, the listed attributes must be the same, and the optional
# and supplied fields are just that :-)
policy		= policy_match

# For the CA policy
[ policy_match ]
countryName		= match
stateOrProvinceName	= match
localityName		= supplied
organizationName	= match
organizationalUnitName	= optional
commonName		= supplied
emailAddress		= optional

# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName		= optional
stateOrProvinceName	= optional
localityName		= optional
organizationName	= optional
organizationalUnitName	= optional
commonName		= supplied
emailAddress		= optional

####################################################################
[ req ]
default_bits		= 2048
default_keyfile		= privkey.pem
distinguished_name	= req_distinguished_name
attributes		= req_attributes
x509_extensions		= v3_ca	# The extensions to add to the self signed cert
req_extensions		= v3_req

# Passwords for private keys if not present they will be prompted for
# input_password = secret
# output_password = secret

# This sets a mask for permitted string types. There are several options.
# default: PrintableString, T61String, BMPString.
# pkix	 : PrintableString, BMPString (PKIX recommendation before 2004)
# utf8only: only UTF8Strings (PKIX recommendation after 2004).
# nombstr : PrintableString, T61String (no BMPStrings or UTF8Strings).
# MASK:XXXX a literal mask value.
# WARNING: ancient versions of Netscape crash on BMPStrings or UTF8Strings.
string_mask = nombstr

# req_extensions = v3_req # The extensions to add to a certificate request

[ req_distinguished_name ]
countryName			= Country Name (2 letter code)
countryName_default		= ES
countryName_min			= 2
countryName_max			= 2

stateOrProvinceName		= State or Province Name (full name)
stateOrProvinceName_default	= Andalucia

localityName			= Locality Name (eg, city)
localityName_dafault		= Dos Hermanas

0.organizationName		= Organization Name (eg, company)
0.organizationName_default	= JaviHueteCA

# we can do this but it is not needed normally :-)
#1.organizationName		= Second Organization Name (eg, company)
#1.organizationName_default	= World Wide Web Pty Ltd

organizationalUnitName		= Organizational Unit Name (eg, section)
#organizationalUnitName_default	=

commonName			= Common Name (e.g. server FQDN or YOUR name)
commonName_max			= 64

emailAddress			= Email Address
emailAddress_max		= 64

# SET-ex3			= SET extension number 3

[ req_attributes ]
#challengePassword		= A challenge password
#challengePassword_min		= 4
#challengePassword_max		= 20

#unstructuredName		= An optional company name

[ usr_cert ]

# These extensions are added when 'ca' signs a request.

# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move

# Copy subject details
# issuerAltName=issuer:copy

# This is required for TSA certificates.
# extendedKeyUsage = critical,timeStamping

crlDistributionPoints = URI:http://www.example.com/example_ca.crl

# Same as above, but cert req already has SubjectAltName
[ usr_cert_has_san ]
basicConstraints = CA:false
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
crlDistributionPoints = URI:http://www.example.com/example_ca.crl

[ v3_req ]

# Extensions to add to a certificate request

#basicConstraints = CA:FALSE
#keyUsage = nonRepudiation, digitalSignature, keyEncipherment
#subjetctAltName = email:move

[ v3_ca ]


# Extensions for a typical CA


# PKIX recommendation.

subjectKeyIdentifier=hash

authorityKeyIdentifier=keyid:always,issuer

basicConstraints = CA:true

# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
# keyUsage = cRLSign, keyCertSign

# Include email address in subject alt name: another PKIX recommendation
# subjectAltName=email:copy
# Copy issuer details
# issuerAltName=issuer:copy

# DER hex encoding of an extension: beware experts only!
# obj=DER:02:03
# Where 'obj' is a standard or added object
# You can even override a supported extension:
# basicConstraints= critical, DER:30:03:01:01:FF

crlDistributionPoints = URI:http://www.example.com/example_ca.crl

# Same as above, but CA req already has SubjectAltName
[ v3_ca_has_san ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
basicConstraints = CA:true
crlDistributionPoints = URI:http://www.example.com/example_ca.crl

[ crl_ext ]

# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.

# issuerAltName=issuer:copy
authorityKeyIdentifier=keyid:always

[ proxy_cert_ext ]
# These extensions should be added when creating a proxy certificate

# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.

basicConstraints=CA:FALSE

# This is typical in keyUsage for a client certificate.
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
# subjectAltName=email:copy
# An alternative to produce certificates that aren't
# deprecated according to PKIX.
# subjectAltName=email:move

# Copy subject details
# issuerAltName=issuer:copy

# This really needs to be in place for it to be a proxy certificate.
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo

####################################################################
[ tsa ]

default_tsa = tsa_config1	# the default TSA section

[ tsa_config1 ]

# These are used by the TSA reply generation only.
dir		= ./demoCA		# TSA root directory
serial		= $dir/tsaserial	# The current serial number (mandatory)
crypto_device	= builtin		# OpenSSL engine to use for signing
signer_cert	= $dir/tsacert.pem 	# The TSA signing certificate
					# (optional)
certs		= $dir/cacert.pem	# Certificate chain to include in reply
					# (optional)
signer_key	= $dir/private/tsakey.pem # The TSA private key (optional)
signer_digest  = sha256			# Signing digest to use. (Optional)
default_policy	= tsa_policy1		# Policy if request did not specify it
					# (optional)
other_policies	= tsa_policy2, tsa_policy3	# acceptable policies (optional)
digests     = sha1, sha256, sha384, sha512  # Acceptable message digests (mandatory)
accuracy	= secs:1, millisecs:500, microsecs:100	# (optional)
clock_precision_digits  = 0	# number of digits after dot. (optional)
ordering		= yes	# Is ordering defined for timestamps?
				# (optional, default: no)
tsa_name		= yes	# Must the TSA name be included in the reply?
				# (optional, default: no)
ess_cert_id_chain	= no	# Must the ESS cert id chain be included?
				# (optional, default: no)
ess_cert_id_alg		= sha1	# algorithm to compute certificate
				# identifier (optional, default: sha1)

[insta] # CMP using Insta Demo CA
# Message transfer
server = pki.certificate.fi:8700
# proxy = # set this as far as needed, e.g., http://192.168.1.1:8080
# tls_use = 0
path = pkix/

# Server authentication
recipient = "/C=FI/O=Insta Demo/CN=Insta Demo CA" # or set srvcert or issuer
ignore_keyusage = 1 # potentially needed quirk
unprotected_errors = 1 # potentially needed quirk
extracertsout = insta.extracerts.pem

# Client authentication
ref = 3078 # user identification
secret = pass:insta # can be used for both client and server side

# Generic message options
cmd = ir # default operation, can be overridden on cmd line with, e.g., kur

# Certificate enrollment
subject = "/CN=openssl-cmp-test"
newkey = insta.priv.pem
out_trusted = apps/insta.ca.crt # does not include keyUsage digitalSignature
certout = insta.cert.pem

[pbm] # Password-based protection for Insta CA
# Server and client authentication
ref = $insta::ref # 3078
secret = $insta::secret # pass:insta

[signature] # Signature-based protection for Insta CA
# Server authentication
trusted = $insta::out_trusted # apps/insta.ca.crt

# Client authentication
secret = # disable PBM
key = $insta::newkey # insta.priv.pem
cert = $insta::certout # insta.cert.pem

[ir]
cmd = ir

[cr]
cmd = cr

[kur]
# Certificate update
cmd = kur
oldcert = $insta::certout # insta.cert.pem

[rr]
# Certificate revocation
cmd = rr
oldcert = $insta::certout # insta.cert.pem

Por último hay que crear la autoridad certificadora. Para ello se necesita un par de claves.

❯ openssl req -new -newkey rsa:2048 -keyout private/cakey.pem -out careq.pem -config ./openssl.cnf
.........+.....+......+......+.+.........+.....+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+..+...+.+........+.+..+...+.......+........+.+.....+...+.+.....+......+...+.......+...+..+....+............+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..........+...+.............................+..........+...+.....+....+.........+..+.........+......+.......+..+....+.....+.+...+...+........+.+...+...........+..........+..+....+...+..+.+........+.+..............+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.......+..+...............+......+...+............+..................+.......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*........+....+..+.+........+...............+.......+..+..........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*............+.........+.+.....+.........+......+....+..+.+.....+...+.+...+..+.+........+......+..........+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
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) [ES]:
State or Province Name (full name) [Sevilla]:
Locality Name [Dos Hermanas]:
Organization Name (eg, company) [JaviHueteCA]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:JaviHuete
Email Address []:javi@javihueteca.org

El siguiente paso en la creación de la autoridad certificadora es autofirmar la solicitud CSR para crear el certificado CRT de la autoridad.

❯ openssl ca -create_serial -out cacert.pem -days 365 -keyfile private/cakey.pem -selfsign -extensions v3_ca -config ./openssl.cnf -infiles careq.pem
Using configuration from ./openssl.cnf
Enter pass phrase for private/cakey.pem:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number:
            03:63:db:72:4f:8c:36:21:62:9a:21:2c:e8:2d:9a:40:b9:2a:35:71
        Validity
            Not Before: Jan  9 11:23:27 2025 GMT
            Not After : Jan  9 11:23:27 2026 GMT
        Subject:
            countryName               = ES
            stateOrProvinceName       = Sevilla
            organizationName          = JaviHueteCA
            commonName                = JaviHuete
            emailAddress              = javi@javihueteca.org
        X509v3 extensions:
            X509v3 Subject Key Identifier: 
                1E:36:CD:F9:E7:98:C3:AB:66:61:45:C0:41:78:CF:2A:6C:27:8B:05
            X509v3 Authority Key Identifier: 
                1E:36:CD:F9:E7:98:C3:AB:66:61:45:C0:41:78:CF:2A:6C:27:8B:05
            X509v3 Basic Constraints: critical
                CA:TRUE
Certificate is to be certified until Jan  9 11:23:27 2026 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Database updated

Firmar solicitudes de certificados como Autoridad Certificadora (CA)

Para firmar una solicitud CSR recibida se descarga en el directorio CA/certreqs.

❯ openssl ca -config openssl.cnf -out certsdb/pineda.crt -infiles certreqs/server.csr
Using configuration from openssl.cnf
Enter pass phrase for /home/javi/Dropbox/ASIR/Seguridad/Criptografía/CA/private/cakey.pem:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number:
            03:63:db:72:4f:8c:36:21:62:9a:21:2c:e8:2d:9a:40:b9:2a:35:72
        Validity
            Not Before: Jan  9 11:38:36 2025 GMT
            Not After : Jan  9 11:38:36 2026 GMT
        Subject:
            countryName               = ES
            stateOrProvinceName       = Sevilla
            organizationName          = JaviHueteCA
            commonName                = JaviHuete
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            X509v3 Subject Key Identifier: 
                1B:D9:6B:78:1A:76:B7:E4:49:92:A5:AD:6C:38:B2:D0:2F:EA:3C:D0
            X509v3 Authority Key Identifier: 
                1E:36:CD:F9:E7:98:C3:AB:66:61:45:C0:41:78:CF:2A:6C:27:8B:05
Certificate is to be certified until Jan  9 11:38:36 2026 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Database updated

Este comando genera un certificado firmado con la extensión .crt en el directorio CA/certsdb. Este certificado se envía al solicitante junto con el certificado autofirmado de la autoridad certificadora.

Configuración de un servidor web con un certificado HTTPS

Solicitud del certificado

Para poder configurar de forma adecuada su servidor web se necesita el certificado firmado por la Autoridad Certificadora (CA) y el certificado autofirmado de la propia CA.

Para solicitar un certificado a la CA se debe generar una solicitud de certificado CSR junto a la clave privada asociada a ese certificado o se puede usar una clave privada previamente existente.

❯ openssl req -newkey rsa:4096 -keyout servidor.key -out servidor.csr
..+......+...+.+...+..+...+......+....+..+.+.....+..........+..+................+..+...+.+......+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+....+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+.................+...+........................+......+......+.+.....+....+...............+...+......+.....................+...+......+..+............+.+.....+.+...+.....+.+......+...........+..................+.+.........+............+....................+.............+......+...+..+.+.........+......+........+.+.....+.........+....+...............+..+...+...............+.............+...+......+........+......+.+......+...+.........+...+...............+..............+...+.....................+.......+................................+...+............+.......+.....+.........+.....................+...+.+............+.................+.......+...........+..................+....+......+..+............+...............+.+.....+...................+..+....+......+...............+...+..+.+........+....+...+.....+.......+...+....................+.......+...+...+..+.......+......+.....+......+...+......+....+.................+.+.....+.........+......+.........+....+.....+.+........+.+..+....+...+..+.+..+......+.......+.....+.........+.+..+...+...+.+...+..+.............+........+.......+......+.....+.+...+......+.....+.+.........+......+...........+....+...+..+...+..........+......+.....+.......+.....+.......+........+...+....+......+.....+........................+............+.+..+.............+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
..+.+..............+.+..+......+.+...+...+........+.......+.....+....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...+..+....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...+.....+...+.............+.....+...+....+...+...+.....+.......+...+.....+.+.....+...+...+....+.....+....+...............+......+.........+............+.....+.......+..+.+..................+...........+.+.....+...+.+...+.................+............................+...+..+.+...........+.+..+.............+..+......+....+.....+.......+......+...+..+..........+..+..........+...............+........+.........+....+...........+....+.....+....+...............+...+.....+.........+..................................+......+..............+.........+.......+......+..+...+..........+............+..+.+...+......+.........+.....+....+.....+.............+........+......+...+.+.........+............+...........+...+....+............+........+......+.+...+...+........+....+.....+..................+............+...+...+......+.....................+.............+.................+...+....+......+...............+..+...............+..........+...+..+.......+...+...+.........+..+.........+.+.........+.........+......+...........+...+.+..............................+.........+..+......+....+...........+...+.+...........+....+........+......+.+.....+...+.+.........+..+.+............+......+.....+................+...+.....+...+..........+..+...+.........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
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]:ES
State or Province Name (full name) [Some-State]:Sevilla
Locality Name (eg, city) []:Dos Hermanas
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Certificaciones Pineda
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:pineda
Email Address []:    

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Este comando utiliza el módulo req de openssl con la opción -newkey, que permite crear tanto la clave pirvada (-keyout) como el CSR (-out) en un único comando.

La CA debe devolver tanto el certificado firmado como su propio certificado autofirmado.

Configuración HTTPS en Apache2

Para configurar un virtual host en apache2 usando un certificado HTTPS se usa una configuración similar a la siguiente:

<VirtualHost *:443>
	ServerAdmin webmaster@localhost

	DocumentRoot /var/www/html

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined

	SSLEngine on

	SSLCertificateFile      /ruta/a/javihuete.crt
	SSLCertificateKeyFile   /ruta/a/servidor.key
	SSLCACertificateFile	/ruta/a/cacert.pem

	<FilesMatch "\.(?:cgi|shtml|phtml|php)$">
		SSLOptions +StdEnvVars
	</FilesMatch>
	<Directory /usr/lib/cgi-bin>
		SSLOptions +StdEnvVars
	</Directory>

</VirtualHost>

Para que se fuerce la redirección a la versión https del servidor web se establece también la siguiente configuración en el virtual host por defecto.

<VirtualHost *:80>

	ServerAdmin webmaster@localhost
	DocumentRoot /var/www/html

	RedirectMatch 301 ^/$ https://localhost

	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

En el navegador, hay que instalar el certificado de la autoridad certificadora para poder acceder al sitio HTTPS. En el caso de Firefox esto se hace pulsando el botón “importar” desde el menú de certificados en los ajustes del navegador.

Al acceder al servidor web por HTTPS desde el navegador se muestra un mensaje de error

Esto se debe a que el servidor web usa un certificado autofirmado cuyo emisor es desconocido para el navegador y, por tanto, no confía en él. Sin embargo, como tenemos confianza en el emisor del certificado, podemos pulsar “Aceptar el riesgo y continuar”.

Entonces podemos acceder a la web alojado en el servidor. En la información del a página se muestra que, aunque el sitio web no proporciona información de su dueño, sí está verificado, en este caso, por “Certificaciones Pineda”.

Configuración HTTPS en Nginx

Para configurar el servidor web Nginx para servir la página estática usando HTTPS se modifica el fichero por defecto con los siguientes parámetros:

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration

server {
	listen 80 default_server;
	listen [::]:80 default_server;

	return 301 https://localhost;
}

server {
	listen 443 ssl;
	listen [::]:443 ssl;
	ssl_certificate /ruta/a/javihuete.crt;
	ssl_certificate_key /ruta/a/servidor.key;
	ssl_password_file /ruta/a/password_file;
	ssl_protocols       TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
	ssl_ciphers         HIGH:!aNULL:!MD5;

	server_name _;
	
	root /var/www/html;
	index index.html;

	location / {
		try_files $uri $uri/ =404;
	}
}

Para que funcione la directiva ssl_password_file, que pasa la frase de paso de la clave privada con la que se solicitó el certificado a la autoridad certificadora, hay que crear este fichero y rellenarlo con esta frase de paso.

echo "passphrase" > password_file

Con esta configuración, se puede acceder a la web HTTPS alojada en el servidor Nginx.

comments powered by Disqus

Relacionados

Conceptos de gestión de paquetería en Debian

En este post se recoge un breve resumen sobre la información relativa a los gestores de paquetes apt y aptitude incluida en el manual de referencia de Debian.

Leer

Interconexión entre dos servidores Oracle

Este post constituye una breve guía con los pasos a seguir para establecer una interconexión entre dos servidores Oracle.

Leer

Creación de usuarios y políticas de seguridad en Debian

En este post se explica, a través de varios casos prácticos y ejemplos, el uso adecuado de los comandos básicos para la creación de usuarios y el establecimiento de políticas de seguridad en los sistemas operativos basados en Debian.

Leer