Noticias:

¿Quieres formar parte de Bomber Code? Entonces entra a este tema: Postulaciones al Staff

Menú principal

Como activar https con ssl incluido el virtualhost en Wamp 3.x

Publicado por Rock Lee, 07 Septiembre de 2022, 15:25

Tema anterior - Siguiente tema

0 Usuarios y 1 Visitante están viendo este tema.

Rock Lee

 :-[ Bueno luego de pelear un rato con Wamp :'( para poder hacer funcionar el SSL y mirando varios tutoriales (ninguno funcionaba como tal) logre hacerlo funcionar, aunque tuve ir por otro lado para adaptar el código en si. Por eso dejo esto a modo guía sumado casi nada esta en español cosa me pareció raro ::). En fin... primero aclarar que el puerto escucha de Apache no solo debe ser el puerto 443, sino también el puerto 80 (en muchos dicen solo debe ser uno cual es un error por que marca conexión perdida, luego de muchas pruebas lo note). En su momento lo incluía en la documentación de apache que necesita ambos VirtualHost, el puerto 80 y el puerto 443 son necesarios debido a que si uno falla automáticamente conecta el otro puerto pero en las ultimas versiones no aclaran mas esto. Aunque parezca contradictorio, supongo por eso no lo aclaran mas, tener ambos puertos se bloquearían mutuamente pero es todo lo contrario ya que el puerto 80 del VirtualHost está definido en el archivo httpd-vhosts.conf y el puerto 443 del VirtualHost está definido en el archivo httpd-ssl.conf.

***Una aclaración antes de seguir, yo tome como ejemplo las rutas tengo en mi maquina por eso puede variar versión y rutas, tenes que adaptarlos a tu configuración***

En este caso el directorio usado/comprobado es C:\wamp y la versión de apache usado es 2.4.51 en la compilación de x86/x64 bits. Antes que nada debemos detener todos los servicios/procesos de Wamp y procedemos a descomentar la linea 581 en el archivo ubicado en:

C:\wamp\bin\apache\apache2.4.51\conf\httpd.conf

Tiene aparacer algo como:
#Incluir conf/extra/httpd-ssl.conf

y debe quedar:
Incluir conf/extra/httpd-ssl.conf

También para poder activar el HTTPS SSL, se tiene que descomentar los módulos:
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
LoadModule ssl_module modules/mod_ssl.so

Ambos en el mismo archivo en las lineas 185 y 187 respectivamente, aunque estos módulos solo se activarán/cargaran después de completar todo el procedimiento de creación de claves y asegurarse de que el VirtualHost funciona correctamente en el puerto httpd 80.


Ahora buscamos el archivo:

C:\wamp\bin\apache\apache2.4.51\conf\extra\httpd-ssl.conf

Que tenemos la opción de leer los comentarios que se encuentran en el mismo archivo, además por defecto tiene una copia extra por si necesitas restaurarlo en C:\..\conf\original\ pero puedes hacer una copia manual por la dudas, remplazando ciertos datos o remplazarlo por el que dejo acontinuación:

#
# This is the Apache server configuration file providing SSL support.
# It contains the configuration directives to instruct the server how to
# serve pages over an https connection. For detailed information about these 
# directives see <URL:http://httpd.apache.org/docs/2.4/mod/mod_ssl.html>
# 
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.  
#
# Required modules: mod_log_config, mod_setenvif, mod_ssl,
#          socache_shmcb_module (for default value of SSLSessionCache)

#
# Pseudo Random Number Generator (PRNG):
# Configure one or more sources to seed the PRNG of the SSL library.
# The seed data should be of good random quality.
# WARNING! On some platforms /dev/random blocks if not enough entropy
# is available. This means you then cannot use the /dev/random device
# because it would lead to very long connection times (as long as
# it requires to make more entropy available). But usually those
# platforms additionally provide a /dev/urandom device which doesn't
# block. So, if available, use this one instead. Read the mod_ssl User
# Manual for more details.
#
#SSLRandomSeed startup file:/dev/random  512
#SSLRandomSeed startup file:/dev/urandom 512
#SSLRandomSeed connect file:/dev/random  512
#SSLRandomSeed connect file:/dev/urandom 512


#
# When we also provide SSL we have to listen to the 
# standard HTTP port (see above) and to the HTTPS port
#
Listen 0.0.0.0:443 https
Listen [::0]:443 https

# Where the certificates are
Define CERTIFS ${INSTALL_DIR}/bin/apache2.4.51/conf/certificados

##
##  SSL Global Context
##
##  All SSL configuration in this context applies both to
##  the main server and all SSL-enabled virtual hosts.
##

#   SSL Cipher Suite:
#   List the ciphers that the client is permitted to negotiate,
#   and that httpd will negotiate as the client of a proxied server.
#   See the OpenSSL documentation for a complete list of ciphers, and
#   ensure these follow appropriate best practices for this deployment.
#   httpd 2.2.30, 2.4.13 and later force-disable aNULL, eNULL and EXP ciphers,
#   while OpenSSL disabled these by default in 0.9.8zf/1.0.0r/1.0.1m/1.0.2a.
SSLCipherSuite SSL ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES256-GCM-SHA384
SSLProxyCipherSuite HIGH:MEDIUM:!MD5:!RC4:!3DES

# Encryptions TLSv1.3
SSLCipherSuite TLSv1.3 TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384
SSLOpenSSLConfCmd ECDHParameters secp521r1
SSLOpenSSLConfCmd Curves sect571r1:sect571k1:secp521r1:sect409k1:sect409r1:secp384r1

#  By the end of 2016, only TLSv1.2 ciphers should remain in use.
#  Older ciphers should be disallowed as soon as possible, while the
#  kRSA ciphers do not offer forward secrecy.  These changes inhibit
#  older clients (such as IE6 SP2 or IE8 on Windows XP, or other legacy
#  non-browser tooling) from successfully connecting.  
#
#  To restrict mod_ssl to use only TLSv1.2 ciphers, and disable
#  those protocols which do not support forward secrecy, replace
#  the SSLCipherSuite and SSLProxyCipherSuite directives above with
#  the following two directives, as soon as practical.
# SSLCipherSuite HIGH:MEDIUM:!SSLv3:!kRSA
# SSLProxyCipherSuite HIGH:MEDIUM:!SSLv3:!kRSA

#   User agents such as web browsers are not configured for the user's
#   own preference of either security or performance, therefore this
#   must be the prerogative of the web server administrator who manages
#   cpu load versus confidentiality, so enforce the server's cipher order.
SSLHonorCipherOrder on 

#   SSL Protocol support:
#   List the protocol versions which clients are allowed to connect with.
#   Disable SSLv3 by default (cf. RFC 7525 3.1.1).  TLSv1 (1.0) should be
#   disabled as quickly as practical.  By the end of 2016, only the TLSv1.2
#   protocol or later should remain in use.
SSLProtocol all +TLSv1.2 +TLSv1.3
SSLProxyProtocol all -SSLv3
SSLCompression Off

#   Pass Phrase Dialog:
#   Configure the pass phrase gathering process.
#   The filtering dialog program (`builtin' is an internal
#   terminal dialog) has to provide the pass phrase on stdout.
SSLPassPhraseDialog  builtin

#   Inter-Process Session Cache:
#   Configure the SSL Session Cache: First the mechanism 
#   to use and second the expiring timeout (in seconds).
#SSLSessionCache         "dbm:${SRVROOT}/logs/ssl_scache"
SSLSessionCache        "shmcb:${SRVROOT}/logs/ssl_scache(512000)"
SSLSessionCacheTimeout  300

#   OCSP Stapling (requires OpenSSL 0.9.8h or later)
#
#   This feature is disabled by default and requires at least
#   the two directives SSLUseStapling and SSLStaplingCache.
#   Refer to the documentation on OCSP Stapling in the SSL/TLS
#   How-To for more information.
#
#   Enable stapling for all SSL-enabled servers:
#SSLUseStapling On

#   Define a relatively small cache for OCSP Stapling using
#   the same mechanism that is used for the SSL session cache
#   above.  If stapling is used with more than a few certificates,
#   the size may need to be increased.  (AH01929 will be logged.)
#SSLStaplingCache "shmcb:${SRVROOT}/logs/ssl_stapling(32768)"

#   Seconds before valid OCSP responses are expired from the cache
#SSLStaplingStandardCacheTimeout 3600

#   Seconds before invalid OCSP responses are expired from the cache
#SSLStaplingErrorCacheTimeout 600

##
## SSL Virtual Host Context
##

<VirtualHost _default_:443>

#   General setup for the virtual host
DocumentRoot "${SRVROOT}/www"
ServerName www.localhost.com:443
ServerAdmin 
ErrorLog "${SRVROOT}/logs/error.log"
TransferLog "${SRVROOT}/logs/access.log"

#   SSL Engine Switch:
#   Enable/Disable SSL for this virtual host.
SSLEngine on

#   Server Certificate:
#   Point SSLCertificateFile at a PEM encoded certificate.  If
#   the certificate is encrypted, then you will be prompted for a
#   pass phrase.  Note that a kill -HUP will prompt again.  Keep
#   in mind that if you have both an RSA and a DSA certificate you
#   can configure both in parallel (to also allow the use of DSA
#   ciphers, etc.)
#   Some ECC cipher suites (http://www.ietf.org/rfc/rfc4492.txt)
#   require an ECC certificate which can also be configured in
#   parallel.
SSLCertificateFile "${SRVROOT}/conf/server-archivo.crt"
#SSLCertificateFile "${SRVROOT}/conf/server-dsa.crt"
#SSLCertificateFile "${SRVROOT}/conf/server-ecc.crt"

#   Server Private Key:
#   If the key is not combined with the certificate, use this
#   directive to point at the key file.  Keep in mind that if
#   you've both a RSA and a DSA private key you can configure
#   both in parallel (to also allow the use of DSA ciphers, etc.)
#   ECC keys, when in use, can also be configured in parallel
SSLCertificateKeyFile "${SRVROOT}/conf/server-llave.key"
#SSLCertificateKeyFile "${SRVROOT}/conf/server-dsa.key"
#SSLCertificateKeyFile "${SRVROOT}/conf/server-ecc.key"

#   Server Certificate Chain:
#   Point SSLCertificateChainFile at a file containing the
#   concatenation of PEM encoded CA certificates which form the
#   certificate chain for the server certificate. Alternatively
#   the referenced file can be the same as SSLCertificateFile
#   when the CA certificates are directly appended to the server
#   certificate for convenience.
#SSLCertificateChainFile "${SRVROOT}/conf/server-ca.crt"

#   Certificate Authority (CA):
#   Set the CA certificate verification path where to find CA
#   certificates for client authentication or alternatively one
#   huge file containing all of them (file must be PEM encoded)
#   Note: Inside SSLCACertificatePath you need hash symlinks
#         to point to the certificate files. Use the provided
#         Makefile to update the hash symlinks after changes.
#SSLCACertificatePath "${SRVROOT}/conf/ssl.crt"
#SSLCACertificateFile "${SRVROOT}/conf/ssl.crt/ca-bundle.crt"

#   Certificate Revocation Lists (CRL):
#   Set the CA revocation path where to find CA CRLs for client
#   authentication or alternatively one huge file containing all
#   of them (file must be PEM encoded).
#   The CRL checking mode needs to be configured explicitly
#   through SSLCARevocationCheck (defaults to "none" otherwise).
#   Note: Inside SSLCARevocationPath you need hash symlinks
#         to point to the certificate files. Use the provided
#         Makefile to update the hash symlinks after changes.
#SSLCARevocationPath "${SRVROOT}/conf/ssl.crl"
#SSLCARevocationFile "${SRVROOT}/conf/ssl.crl/ca-bundle.crl"
#SSLCARevocationCheck chain

#   Client Authentication (Type):
#   Client certificate verification type and depth.  Types are
#   none, optional, require and optional_no_ca.  Depth is a
#   number which specifies how deeply to verify the certificate
#   issuer chain before deciding the certificate is not valid.
#SSLVerifyClient require
#SSLVerifyDepth  10

#   TLS-SRP mutual authentication:
#   Enable TLS-SRP and set the path to the OpenSSL SRP verifier
#   file (containing login information for SRP user accounts). 
#   Requires OpenSSL 1.0.1 or newer. See the mod_ssl FAQ for
#   detailed instructions on creating this file. Example:
#   "openssl srp -srpvfile ${SRVROOT}/conf/passwd.srpv -add username"
#SSLSRPVerifierFile "${SRVROOT}/conf/passwd.srpv"

#   Access Control:
#   With SSLRequire you can do per-directory access control based
#   on arbitrary complex boolean expressions containing server
#   variable checks and other lookup directives.  The syntax is a
#   mixture between C and Perl.  See the mod_ssl documentation
#   for more details.
#<Location />
#SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
#            and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
#            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
#            and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
#            and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) \
#           or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
#</Location>

#   SSL Engine Options:
#   Set various options for the SSL engine.
#   o FakeBasicAuth:
#     Translate the client X.509 into a Basic Authorisation.  This means that
#     the standard Auth/DBMAuth methods can be used for access control.  The
#     user name is the `one line' version of the client's X.509 certificate.
#     Note that no password is obtained from the user. Every entry in the user
#     file needs this password: `xxj31ZMTZzkVA'.
#   o ExportCertData:
#     This exports two additional environment variables: SSL_CLIENT_CERT and
#     SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
#     server (always existing) and the client (only existing when client
#     authentication is used). This can be used to import the certificates
#     into CGI scripts.
#   o StdEnvVars:
#     This exports the standard SSL/TLS related `SSL_*' environment variables.
#     Per default this exportation is switched off for performance reasons,
#     because the extraction step is an expensive operation and is usually
#     useless for serving static content. So one usually enables the
#     exportation for CGI and SSI requests only.
#   o StrictRequire:
#     This denies access when "SSLRequireSSL" or "SSLRequire" applied even
#     under a "Satisfy any" situation, i.e. when it applies access is denied
#     and no other module can change it.
#   o OptRenegotiate:
#     This enables optimized SSL connection renegotiation handling when SSL
#     directives are used in per-directory context. 
#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
<FilesMatch "\.(cgi|shtml|phtml|php)$">
    SSLOptions +StdEnvVars
</FilesMatch>
<Directory "${SRVROOT}/www">
    SSLOptions +StdEnvVars
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride all
    Require local
</Directory>

#   SSL Protocol Adjustments:
#   The safe and default but still SSL/TLS standard compliant shutdown
#   approach is that mod_ssl sends the close notify alert but doesn't wait for
#   the close notify alert from client. When you need a different shutdown
#   approach you can use one of the following variables:
#   o ssl-unclean-shutdown:
#     This forces an unclean shutdown when the connection is closed, i.e. no
#     SSL close notify alert is sent or allowed to be received.  This violates
#     the SSL/TLS standard but is needed for some brain-dead browsers. Use
#     this when you receive I/O errors because of the standard approach where
#     mod_ssl sends the close notify alert.
#   o ssl-accurate-shutdown:
#     This forces an accurate shutdown when the connection is closed, i.e. a
#     SSL close notify alert is send and mod_ssl waits for the close notify
#     alert of the client. This is 100% SSL/TLS standard compliant, but in
#     practice often causes hanging connections with brain-dead browsers. Use
#     this only for browsers where you know that their SSL implementation
#     works correctly. 
#   Notice: Most problems of broken clients are also related to the HTTP
#   keep-alive facility, so you usually additionally want to disable
#   keep-alive for those clients, too. Use variable "nokeepalive" for this.
#   Similarly, one has to force some clients to use HTTP/1.0 to workaround
#   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
#   "force-response-1.0" for this.
BrowserMatch "MSIE [2-5]" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

#   Per-Server Logging:
#   The home of a custom SSL log file. Use this when you want a
#   compact non-error SSL logfile on a virtual host basis.
CustomLog "${SRVROOT}/logs/ssl_request.log" \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

</VirtualHost>

El VirtualHost ya existe y es válido con en el puerto http 443, por lo que si tenes alguno perzonalizado tenes ademas que modificar el archivo: C:\wamp\bin\apache\apache2.4.51\conf\extra\httpd-vhosts.conf especificaando el directorio.

Rock Lee

Luego tenemos que cambiar lo que dice en el archivo: C:\wamp\bin\apache\apache2.4.51\conf\openssl.cnf pudiendo leer y cambirlo a su gusto sino usar el siguiente:

#
# OpenSSL example configuration file.
# This is mostly being used for generation of certificate requests.
#

# 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            = .

# 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

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

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

dir        = ./certificados        # Where everything is kept
certs        = $dir/certs        # 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    = $dir/newcerts        # default place for new certs.

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

x509_extensions    = usr_cert        # The extensions to add to the cert

# 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    = 3650            # how long to certify for
default_crl_days= 3650            # how long before next CRL
default_md    = SHA-256        # 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
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        = 4096
default_keyfile     = llaveprivada.pem
distinguished_name    = req_distinguished_name
attributes        = req_attributes
x509_extensions    = v3_ca    # The extensions to add to the self signed cert

# 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 = utf8only

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

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

stateOrProvinceName        = Buenos Aires
stateOrProvinceName_default    = Buenos Aires

localityName            = Buenos Aires

0.organizationName        = Bomber Code
0.organizationName_default    = Bomber Code

# 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        = BomberCodeNet
#organizationalUnitName_default    =

commonName            = BomberCode
commonName_max            = 64

emailAddress            = 
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

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType            = server

# For an object signing certificate this would be used.
# nsCertType = objsign

# For normal client use this is typical
# nsCertType = client, email

# and for everything including object signing:
# nsCertType = client, email, objsign

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

# This will be displayed in Netscape's comment listbox.
nsComment            = "SSL ROOT CA"

# 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

#nsCaRevocationUrl        = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

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

[ v3_req ]

# Extensions to add to a certificate request

basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

[ v3_ca ]


# Extensions for a typical CA


# PKIX recommendation.

subjectKeyIdentifier=hash

authorityKeyIdentifier=keyid:always,issuer

basicConstraints = critical,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

# Some might want this also
# nsCertType = sslCA, emailCA

# 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

[ 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

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType            = server

# For an object signing certificate this would be used.
# nsCertType = objsign

# For normal client use this is typical
# nsCertType = client, email

# and for everything including object signing:
# nsCertType = client, email, objsign

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

# This will be displayed in Netscape's comment listbox.
nsComment            = "OpenSSL Generated Certificate"

# 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

#nsCaRevocationUrl        = http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

# 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)

Luego de todo esto toca generar el certificado mismo... en este caso se tiene varias opciones de como generarlo. Una opción valida seria usar Let's Encrypt que tomaría algunos pasos extra para hacerlo funcionar "originalmente" pero al ser localmente no necesito este al 100 mas si es para pruebas y tener un certificado para probar cosas puntuales. Por eso mismo yo lo genero por medio de la ventana de comandos (puede luego le aparezca el cartel no valido por que es auto firmado) y debe ser como administrador sino tampoco funcionara.

Como todo lo anterior puede simplemente pegar las lineas de comando y continuar pero si da errores tenes ir linea por linea aunque parezca no avanza va a tardar un poco, además remarcar no deben cerrar la ventana en ningún momento sino tampoco sera valido. También decir voy dejar separado por bloque de códigos que a mi me funciono pero puede que de problemas, en todo caso trata con menos lineas de ser necesario. Luego de aclarar todo tenemos que ir a la consola que esta en C:\wamp\bin\apache\apache2.4.51\bin\ y pasar los siguientes comandos (queda de mas aclarar que tenes adaptar algunas rutas a tu entorno sino dará error)

set installdir=C:\wamp
set apachever=2.4.51
cd /D %installdir%\bin
rmdir /S /Q Certificados
cd Certificados
copy nul .\Certificados\Index.txt
@echo 01> .\Certificados\Serial.txt
@echo MyPass> .\Certificados\Password.txt
set /P PASSWORD= <.\Certificados\Password.txt

cd apache\apache%apachever%\bin
set OPENSSL_CONF=%installdir%\bin\apache\apache%apachever%\conf\openssl.cnf
set DIRCERTS=%installdir%\bin\Certificados
openssl rand -out %DIRCERTS%/Certificados/Certificado.rnd -base64 1825
openssl genrsa -out %DIRCERTS%/Certificados/Certificado.key -rand %DIRCERTS%/Certificados/Certificado.rnd 4096
openssl req -new -sha256 -key %DIRCERTS%/Certificados/Certificado.key -out %DIRCERTS%/Certificados/Certificado.csr -subj "/C=AR/ST=BuenosAires/L=BuenosAires/O=Bomber Code/CN=Bomber Code Net"
openssl x509 -req -days 1825 -sha256 -in %DIRCERTS%/Certificados/Certificado.csr -signkey %DIRCERTS%/Certificados/Certificado.key -out %DIRCERTS%/Certificados/Certificado.crt
openssl x509 -in %DIRCERTS%/Certificados/Certificado.crt -outform der -out %DIRCERTS%/Certificados/Certificado.der
openssl x509 -in %DIRCERTS%/Certificados/Certificado.crt -outform pem -out %DIRCERTS%/Certificados/Certificado.pem
openssl rsa -in %DIRCERTS%/Certificados/Certificado.key -pubout -out %DIRCERTS%/Certificados/Certificado.pbc

set SERVLOCAL=localhost
openssl rand -out %DIRCERTS%/Server/Server.rnd -base64 1825
openssl genrsa -out %DIRCERTS%/Server/Server.key -rand %DIRCERTS%/Server/Server.rnd 4096
openssl req -new -sha256 -key %DIRCERTS%/Server/Server.key -out %DIRCERTS%/Server/Server.csr -subj "/C=AR/ST=BuenosAires/L=BuenosAires/O=Bomber Code/OU=Wampserver/CN=%SERVLOCAL%"
openssl x509 -req -days 1825 -sha256 -in %DIRCERTS%/Server/Server.csr -CA %DIRCERTS%/Cacerts/Certificat.crt -CAkey %DIRCERTS%/Certificados/Certificado.key -CAcreateserial -out %DIRCERTS%/Server/Server.crt
openssl x509 -outform der -in %DIRCERTS%/Server/Server.crt -out %DIRCERTS%/Server/Server.der
openssl x509 -inform DER -outform PEM -in %DIRCERTS%/Server/Server.der -out %DIRCERTS%/Server/Server.pem
openssl crl2pkcs7 -nocrl -certfile %DIRCERTS%/Certificados/Certificado.crt -certfile %DIRCERTS%/Server/Server.crt -out %DIRCERTS%/Server/%SERVLOCAL%.p7b
openssl pkcs12 -export -nodes -in %DIRCERTS%/Certificados/Certificado.crt -inkey %DIRCERTS%/Server/Server.key-out %DIRCERTS%/Server/%SERVLOCAL%.pfx -descert -name "%SERVLOCAL%" -password pass:%PASSWORD%
pass:MyPassword
openssl pkcs12 -nodes -export -in %DIRCERTS%/Server/Server.crt -inkey %DIRCERTS%/Server/Server.key -out %DIRCERTS%/www/%SERVLOCAL%.pfx -clcerts -descert -name "Cliente %SERVLOCAL% Certificado" -password pass:%PASSWORD%
copy /Y %DIRCERTS%\Server\Server.crt %DIRCERTS%\www\%SERVLOCAL%.crt
copy /Y %DIRCERTS%\Server\Server.key %DIRCERTS%\www\%SERVLOCAL%.key

Si necesitas crear otro certificado simplemente repetir el mismo proceso solo cambiando el nombre del servidor y servidor local :). Ahora por ultimo en la misma consola ejecutamos:

set installdir=C:\wamp
set apachever=2.4.51
set OPENSSL_CONF=%installdir%\bin\apache\apache%apachever%\conf\openssl.cnf
set DIRCertificados=%installdir%\bin\Certificados
cd /D %installdir%\bin\apache\apache%apachever%\bin
set /P PASSWORD= <..\..\..\Certificados\Password.txt

Bien ahora podemos forzar a usar el https para uno o varios VirtualHost. Para esto simplemente agregamos una directiva de reescritura en su estructura <VirtualHost *:80> en el archivo httpd-vhosts.conf.

<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  RewriteEngine On
  RewriteCond %{HTTPS} !=on
  RewriteRule ^ 'https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]'
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local
  </Directory>
</VirtualHost>

Y eso es todo amigos :P me tomo algo mas de tiempo poder hacerlo y puede surgir algunos errores en mi escritura por que omití mucho del borrador inicial, sino este mensaje seria muy largo, quitando cosas que simplemente no suman al resultado final. Pero claro siempre es bienvenido las sugerencias y comentarios al respecto en si, incluso yo pueda que cambie unas cositas para mejorar esto. Teniendo en mi mente hacer varias partes pero preferí hacer un solo mensaje (2 en este caso) comprimiendo todo y por eso puede me comiera información... en fin no le doy mas vueltas a esto ::) y cualquier cosa despues modifico el mensaje.


Saludos Familia!

Temas Similares (4)