Guia Certificados Autofirmados

Descargar como docx, pdf o txt
Descargar como docx, pdf o txt
Está en la página 1de 37

1.

Crear y exportar un certificado autofirmado


Personas que lo han encontrado útil: 3 de 3 - Valorar este tema

Puede utilizar estos procedimientos para crear un certificado autofirmado mediante servicios de
Internet Information Server (IIS) y, a continuación, exporte el certificado para su uso en los
equipos cliente.
Debe ser miembro del grupo de administradores de 7 de IIS para realizar este procedimiento.
Para crear un certificado autofirmado
1. En alojado-01, haga clic en Inicio, haga clic en Ejecutary, a continuación,
escriba mmc. Se abrirá Microsoft Management Console (MMC).
2. En MMC, haga clic en archivoy, a continuación, haga clic en Agregar o quitar
complemento. Se abre el cuadro de diálogo Agregar o quitar complementos . En
loscomplementos disponibles, haga clic en Administrador de servicios de Internet
Information Server (IIS)y, a continuación, haga clic en Agregar. Haga clic en Aceptar.
3. En la consola IIS, haga doble clic en Administrador de servicios de Internet
Information Server (IIS)y, a continuación, haga clic en alojado-01 (alojado-01).

4. En el Inicio alojado-01, desplácese a y haga doble clic en Certificados de servidor.


5. En acciones, haga clic en Crear certificado autofirmado.

6. Abre la página Crear certificado autofirmado . En especificar un nombre descriptivo


para el certificado, escriba BranchCache.
7. Haga clic en Aceptar. El Administrador de IIS crea un certificado autofirmado
denominado BranchCache, que se muestra en el Administrador de IIS. No cierre la
consola MMC, como se utiliza en el siguiente procedimiento.
Puede utilizar el siguiente procedimiento para exportar el certificado de BranchCache a una
ubicación de carpeta alojado-01.
Debe ser miembro del grupo Administradores para realizar este procedimiento.
Para exportar el certificado de BranchCache
1. En MMC, haga clic en archivoy, a continuación, haga clic en Agregar o quitar
complemento. Se abre el cuadro de diálogo Agregar o quitar complementos . En
loscomplementos disponibles, haga clic en certificadosy, a continuación, haga clic
en Agregar.
2. Abre la página del complemento certificados . En la página el complemento
certificados , haga clic en la cuenta de equipoy, a continuación, haga clic en siguiente.

3. En Seleccionar equipo, asegúrese de que está seleccionado equipo Local y, a


continuación, haga clic en Finalizar.
4. Haga clic en Aceptar. El complemento certificados, se agrega a la misma consola de
MMC que contiene el complemento Administrador de IIS. En MMC, haga doble clic
encertificados (equipo Local), haga doble clic en Personaly, a continuación, haga clic
en certificados. En el panel de detalles, se muestra el certificado de BranchCache
emitido a alojado-01 .
5. Con el botón derecho alojado-01, haga clic en Todas las tareasy, a continuación, haga
clic en Exportar.

6. Se abre el Asistente para exportación de certificados. Haga clic en siguiente.


7. En Exportar la clave privada, asegúrese de que No, no exporte la clave privada está
seleccionada y, a continuación, haga clic en siguiente.

8. En El formato de archivo de exportación, asegúrese de que DER binario codificado


X.509 (.(CER) está seleccionada y, a continuación, haga clic en siguiente.
9. En el archivo para exportar, haga clic en Examinary, a continuación, desplácese a una
ubicación de la carpeta donde desea guardar el certificado. En nombre de archivo,
escriba BranchCachey, a continuación, haga clic en Guardar. Cierra el cuadro de
diálogo Examinar y aparecerá la página archivo para exportar con la ubicación de
archivo y el nombre de archivo que seleccionó. Por ejemplo, si ha seleccionado una
ubicación de archivo de C: y un nombre de archivo de BranchCache, se
muestraC:\BranchCache.cer .
10. Haga clic en siguientey, a continuación, haga clic en Finalizar. Se abre un cuadro de
diálogo de información que muestra el mensaje de la exportación realizada
correctamente. Haga clic en Aceptar.
11. Si es necesario, haga clic en Finalizar. Con el Explorador de Windows, desplácese hasta
la ubicación del archivo que guardó el certificado. Copie el certificado y guarde el
certificado en una ubicación de archivo en cliente-01 y 02 de cliente.
2. Tomcat SSL con certificado autofirmado en
Windows server 2003

Programas necesarios

1. Java JRE
2. Tomcat 7.0

Creacion del keystore

¿Qué es un keystore?
Es un "contenedor" de los certificados de seguridad para uso del servidor java , en este caso
tomcat 7.0 ,es decir , un archivo que va a servir para guardar los certificado que usa el servidor
web a la hora de usar el protocolo HTTPS.

Para habilitar el uso de conexiones seguras por el protocolo https en tomcat seguiremos los
siguientes pasos:
Primero procederemos a crear el denominado keystore de certificados para tomcat , es decir ,
el almacén de claves donde se encuentran los certificados que va a usar nuestro servidor.

Para ell o al estar tomcat programado en java, podemos usar una herramienta contenida en el
JDK de java,esta herramienta es la keytool.

Crearemos el keystore de la siguiente forma.

1. Abrimos el cmd
2. Introducimos el comando

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA -keystore


\path\to\my\keystore

(Java home es la ruta donde está instalado java)


*Si no sabemos o no queremos usar java home haremos lo que sigue

1. Abrimos el cmd.
2. Vamos abriendo los directorios hasta conseguir (Usando cd ..):

C:\>
C:\>cd "Archivos de programa"
C:\Archivos de programa>cd Java
C:\Archivos de programa\Java>cd jre7
C:\Archivos de programa\Java\jre7>cd bin

Una vez en bin introducimos el comando para crear el keystore

C:\Archivos de programa\Java\jre7\bin> keytool -genkey -alias tomcat


-keyalg RSA
-keystore \path\to\my\keystore\nombreArchivoKeystore

-keystore – Sirve para indicar la ruta donde se creara el archivo

Es importante fijarse bien y que la ruta donde se va a guardar el archivo exista , en el


ejemplo la carpeta key hay que crearla si queremos que se guarde en ella.

C:\Archivos de programa\Java\jre7\bin> keytool -genkey -alias tomcat \


-keyalg RSA -keystore "C:\Archivos de programa\Apache Software
Foundation\Tomcat 7.0\key\llave"
Introduzca la contrase±a del almacen de claves:
Volver a escribir la contraseña nueva:
┐Cuales son su nombre y su apellido?
[Unknown]: entidad
┐Cual es el nombre de su unidad de organizacion?
[Unknown]: organizacion
┐Cual es el nombre de su organizacion?
[Unknown]: organizacion
┐Cual es el nombre de su ciudad o localidad?
[Unknown]: se
┐Cual es el nombre de su estado o provincia?
[Unknown]: se
┐Cual es el codigo de pais de dos letras de la unidad?
[Unknown]: Es
┐Es correcto CN=entidad, OU=organizacion, O=organizacion, L=se, ST=se,
C=Es?
[no]: si
 
 

Es muy importante que en el ultimo paso pulsemos enter y no cambiemos la


contraseña , si no hacemos esto java lanzara una excepción y el archivo keystore no se
creara.

Introduzca la contraseña de clave para <tomcat>


(INTRO si es la misma contraseña que la del almacen de
claves):

Una vez ejecutado este comando se creara un archivo en la ruta especificada, en este caso en
la carpeta key se creara un archivo llave.

Este archivo keystore ya contiene un certificado autofirmado para usar en el servidor.

Habilitar ssl en el Tomcat


Para habilitar SSL en tomcat usando la configuración JSSE debemos modificar el conector en
el archivo server.xml

El archivo server.xml esta en la ruta

C:\Archivos de programa\Apache Software Foundation\Tomcat 7.0\conf

Como vamos a usar el certificado autofirmado incluido en el keystore creado y como en este
tutorial no tenemos la librería APR , el conector usara la configuración JSSE, como podremos
ver al ir al archivo server.xml.
Dentro de este archivo debemos buscar las siguentes lineas , que indican la configuracion
actual del conector para el puerto 8443

<!-- Define a SSL HTTP/1.1 Connector on port 8443


This connector uses the JSSE configuration, when using APR,
the connector should be using the OpenSSL style
described in the APR documentation -->

Y debemos modificar el conector para que quede de la siguiente forma, cambiando los
parámetros de keystoreFile por la ruta donde se encuentra el archivo creado anteriormente y el
keystorePass ,que no es otra que la contraseña que le pusimos al archivo keystore.

<Connector protocol="org.apache.coyote.http11.Http11Protocol"
port="8443" SSLEnabled="true" maxThreads="200"
scheme="https" secure="true"
keystoreFile="ruta archivo keystore"
keystorePass="contraseña keystore" clientAuth="false"
sslProtocol="TLS" />

Después de esto guardamos y reiniciamos el tomcat y nos vamos al navegador que no sea
chrome por ejemplo firefox y ponemos la dirección:

https://direccion_servidor:8443/

nos saldrá que el certificado del servidor no es seguro , procedemos hacer click en entender los
riesgos y añadirlo como excepción de seguridad.

Aun así nos seguirá apareciendo el https tachado y tendremos que confiar en el certificado,
para ello pulsamos en entiendo los riegos y añadir excepción de seguridad , y ya aparecerá la
pagina sin ninguno problema.
3. PostgreSQL y el uso de SSL
Mar, 01/12/2009 - 18:46 — rafaelma

Vamos a ver dos aspectos diferentes e independientes en el tema de las conexiones


seguras, el primero es como cifrar el tráfico entre nuestros clientes y el servidor, y el
segundo, como autentificar a los clientes/usuarios mediante certificados digitales.

Con el cifrado del tráfico entre los clientes y el servidor evitamos que alguien pueda
interceptar el tráfico de red y conseguir los datos que viajan por la conexión. Con la
autentificación por medio de certificados digitales evitamos que clientes/usuarios que no
tengan instalado el certificado correspondiente puedan conectarse a nuestro servidor,
incluso si lo hacen cifrando el tráfico de red.

PostgreSQL soporta nativamente el uso de conexiones SSL para cifrar las


comunicaciones, el único requerimiento es tener OpenSSL instalado en nuestro servidor
y PostgreSQL compilado con soporte SSL. El soporte SSL durante la compilación se
consigue usando el parametro --with-ssl con ./configure antes de compilar. Más
información sobre la instalación desde el código fuente se puede encontrar en el
artículoInstalación e inicialización básica de PostgreSQL desde el código fuente. Los
paquetes binarios disponibles para Unix/Linux y Windows suelen ser compilados con
soporte SSL.
Para activar el soporte SSL en un sistema que cumple los requerimientos que hemos
nombrado hay que hacer tres cosas:

 Definir el parámetro ssl en el fichero postgresql.conf


 Instalar el certificado de nuestro servidor, la clave privada correspondiente, el
certificado CA y un fichero crl con la lista de certificados revocados, en el
directorio de datos PGDATA
 Arrancar de nuevo el servidor PostgreSQL

Una vez que tenemos el soporte SSL instalado y activado hay que configurar en el
fichero pg_hba.conf que conexiones van a utilizar SSL para cifrar el tráfico y/ó
autentificarse con un certificado digital.

Una cosa buena de PostgreSQL en lo referente al uso de SSL para cifrar las conexiones,
es que el servidor PostgreSQL escucha por conexiones estándares (no-SSL) y SSL por el
mismo puerto y negocia automáticamente con el cliente el uso de SSL ó no dependiendo
de lo definido en pg_hba.conf.

Vamos a ver por pasos como configurar todo lo necesario.


Certificados

Lo primero que necesitamos es el certificado SSL que vamos a usar en nuestro servidor,
la correspondiente clave privada, el certificado CA y un fichero crl.

Normalmente los certificados digitales se suelen comprar a una entidad emisora y están


vigentes por un determinado periodo de tiempo. Estos certificados están firmados por
una autoridad de certificación (CA) la cual es una entidad de confianza, responsable de
emitir y revocar certificados digitales.

Si las conexiones que van a usar SSL son internas y locales, no hace falta pagar a una
autoridad de certificación para que emita y firme nuestros certificados con su certificado
CA. Nosotros mismos podemos generar el certificado y firmarlo como un CA local. Para
esto tenemos que hacer lo siguiente:

 Instalar la infraestructura necesaria para ser una CA local


 Generar un certificado y llave CA que utilizaremos para firmar los certificados
que vayamos a usar en nuestros sistemas
 Generar el certificado y la llave que el servidor PostgreSQL necesita
 Firmar nuestro certificado del servidor con el CA que hemos generado

Instalar la infraestructura necesaria para ser una CA local

Primero tenemos que instalar openssl en nuestro ordenador, para esto podemos utilizar
el sistema de instalación por defecto de nuestro sistema operativo.

A continuación creamos como root el directorio que albergará la infraestructura CA:

# mkdir -m 0755 /etc/CA_local

Después creamos los subdirectorios que necesitaremos dentro de /etc/CA_local

# mkdir -m 0755 \
/etc/CA_local \
/etc/CA_local/private \
/etc/CA_local/certs \
/etc/CA_local/newcerts \
/etc/CA_local/crl

Ahora copiamos el fichero de configuración global de openssl (/etc/ssl/openssl.cnf en


mi sistema) a nuestro directorio CA_local.

# cp /etc/ssl/openssl.cnf /etc/CA_local/openssl.local.cnf
# chmod 0600 /etc/CA_local/openssl.local.cnf
A continuación teneis que actualizar el fichero /etc/CA_local/openssl.local.cnf. En la
sección [ CA_default ], cambiar los parámetros dir, certificate y private_key a lo
siguiente:

dir = /etc/CA_local # Where everything is kept


certificate = $dir/certs/local_ca.crt # The CA certificate
private_key = $dir/private/local_ca.key # The private key

Tambien necesitamos tres ficheros extras que podemos crear de la siguiente manera:

# touch /etc/CA_local/index.txt
# echo '01' > /etc/CA_local/serial
# echo '01' > /etc/CA_local/crlnumber

Generar un certificado y llave CA y un fichero crl con la lista de


certificados revocados

Primero vamos a crear un certificado CA que utilizaremos para firmar los certificados
que usemos localmente en nuestros sistemas.

# cd /etc/CA_local/
# openssl req -config openssl.local.cnf -new -x509 -extensions v3_ca \
-keyout private/local_ca.key -out certs/local_ca.crt -days 1825

Este último comando creará un certificado CA autofirmado con una validez de 5 años.
Tendreis que definir una contraseña para la llave privada CA (no olvidar esta
contraseña!! ya que se necesitará cada vez que usemos el certificado local CA) y
rellenar algunos parámetros para vuestro sistema. En mi sistema de ejemplo, estos son
los datos introducidos.

Generating a 1024 bit RSA private key


...................++++++
writing new private key to 'private/local_ca.key'
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]:NO
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:Oslo
Organization Name (eg, company) [Internet Widgits Pty Ltd]:PostgreSQL-es.org
Organizational Unit Name (eg, section) []:.
Common Name (eg, YOUR name) []:postgresql-es.org
Email Address []:webmaster@postgresql-es.org

Una vez realizado estos pasos se habrán creado dos ficheros en vuestro sistema:
 /etc/CA_local/certs/local_ca.crt: Certificado CA local. Se puede distribuir
públicamente y todo el mundo puede acceder al mismo sin problemas de
seguridad.
 /etc/CA_local/private/local_ca.key: Llave CA privada. Se tiene que restringir el
acceso a la misma ( chmod 0400 /etc/CA_local/private/local_ca.key) y no se
puede distribuir públicamente.

El fichero CRL (Certificate Revocation List) con la lista de certificados revocados por este
CA lo podeis crear con:

openssl ca -config openssl.local.cnf -keyfile private/local_ca.key \


-cert certs/local_ca.crt -gencrl -out crl/local_ca.crl

Y comprobarlo y verificarlo con:

openssl crl -in crl/local_ca.crl -text -noout

Crear una solicitud de certificado para el servidor

Tenemos que generar una solicitud de certificado (server.csr) para generar un


certificado que se pueda usar en nuestro servidor. Para ello podemos utilizar los
siguientes comandos:

# cd /etc/CA_local/
# openssl req -config openssl.local.cnf -new -nodes \
-keyout private/ejemplo.postgresql-es.org.key \
-out ejemplo.postgresql-es.org.csr -days 730

Con esto generamos la solicitud de certificado con una validez de 2 años, después de
rellenar algunos parámetros de nuestro sistema. En nuestro ejemplo, estos son los
datos introducidos.

Generating a 1024 bit RSA private key


.........++++++
............................++++++
writing new private key to 'private/server.key'
-----
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]:NO
State or Province Name (full name) [Some-State]:.
Locality Name (eg, city) []:Oslo
Organization Name (eg, company) [Internet Widgits Pty Ltd]:PostgreSQL-es.org
Organizational Unit Name (eg, section) []:.
Common Name (eg, YOUR name) []:ejemplo.postgresql-es.org
Email Address []:webmaster@postgresql-es.org
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Los parámetros a rellenar más importantes son "Common Name" y "Email Address".
"Common Name" debería de tener el nombre de la máquina que va a estar utilizando el
certificado, "Email Address" es la dirección de contacto de vuestro sistema.

No teneis que introducir nada en los parametros "challenge password" y "optional


company name" del final. Hemos utilizado el parámetro -nodes para no tener que
proteger nuestra llave privada con una contraseña y no tener que escribir una
contraseña cada vez que arranquemos un servicio que use el certificado. Por ello es
muy importante no perder ó publicar el fichero con la llave privada.

Firmar nuestra solicitud de certificado con nuestro CA para generar el


certificado final

Una vez que tenemos la solicitud de certificado (server.csr), vamos a firmarla con
nuestro certificado CA. Para ello utilizamos este comando:

# cd /etc/CA_local/
# openssl ca -config openssl.local.cnf -policy policy_anything \
-days 730 -out certs/ejemplo.postgresql-es.org.crt \
-infiles ejemplo.postgresql-es.org.csr

Tendremos que utilizar la contraseña que usamos cuando creamos el certificado CA para
terminar de firmar nuestro certificado:

Using configuration from openssl.local.cnf


Enter pass phrase for /etc/CA_local/private/local_ca.key:
Check that the request matches the signature
Signature ok
Certificate Details:
Serial Number: 1 (0x1)
Validity
Not Before: Nov 30 20:05:18 2009 GMT
Not After : Nov 30 20:05:18 2011 GMT
Subject:
countryName = NO
localityName = Oslo
organizationName = PostgreSQL-es.org
commonName = ejemplo.postgresql-es.org
emailAddress = webmaster@postgresql-es.org
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
58:40:FC:0A:85:C7:58:9D:9D:66:8A:7F:0A:CB:46:65:CD:A2:92:20
X509v3 Authority Key Identifier:
keyid:54:11:C7:CD:1A:1D:54:01:42:D1:FC:1A:1A:DD:ED:B5:5E:E6:89:BF

Certificate is to be certified until Nov 30 20:05:18 2011 GMT (730 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
Data Base Updated

Vamos a asegurar mejor la clave privada del certificado. Este fichero es privado y no se
debe de distribuir:

# chown root:root /etc/CA_local/private/ejemplo.postgresql-es.org.key


# chmod 0400 /etc/CA_local/private/ejemplo.postgresql-es.org.key

Podeis ver la información contenida en el certificado con este comando:

# cd /etc/CA_local/
# openssl x509 -in certs/ejemplo.postgresql-es.org.crt -noout -text

Y comprobar y verificar el certificado con el siguiente comando:

# cd /etc/CA_local/
# openssl verify -purpose sslserver -CAfile /etc/CA_local/certs/local_ca.crt \
/etc/CA_local/certs/ejemplo.postgresql-es.org.crt

El fichero de solicitud de certificado ya no lo necesitais y lo podeis borrar

# rm /etc/CA_local/ejemplo.postgresql-es.org.csr

Esto es todo lo que necesitais saber sobre certificados si quereis hacerlo todo vosotros
para uso local/privado. Al final de todo el proceso tendreis los siguientes ficheros en el
directorio /etc/CA_local

 /etc/CA_local/certs/local_ca.crt: Certificado CA local que podeis utilizar para


firmar otros certificados.
 /etc/CA_local/certs/ejemplo.postgresql-es.org.crt: Certificado firmado por el CA
local que vamos a usar en ejemplo.postgresql-es.org
 /etc/CA_local/private/local_ca.key: Llave privada del certificado CA local
 /etc/CA_local/private/ejemplo.postgresql-es.org.key: Llave privada del certificado
firmado por el CA local y que vamos a usar en ejemplo.postgresql-es.org
 /etc/CA_local/crl/local_ca.crl: Fichero CRL (Certificate Revocation List) con la
lista de certificados revocados
Configuración de PostgreSQL para usar SSL

Una vez que tenemos todos los certificados que necesitamos, tenemos que configurar
PostgreSQL para activar y usar SSL.

Lo primero que hacemos es copiar los ficheros /etc/CA_local/certs/ejemplo.postgresql-


es.org.crt, /etc/CA_local/private/ejemplo.postgresql-es.org.key, /etc/CA_local/certs/loca
l_ca.crt y/etc/CA_local/crl/local_ca.crl al directorio de datos de nuestra instalación
PostgreSQL. En nuestro ejemplo tenemos el directorio de datos en /var/pgsql-8.4/data

# cp /etc/CA_local/certs/ejemplo.postgresql-es.org.crt \
/var/pgsql-8.4/data/server.crt

# cp /etc/CA_local/private/ejemplo.postgresql-es.org.key \
/var/pgsql-8.4/data/server.key

# cp /etc/CA_local/certs/local_ca.crt /var/pgsql-8.4/data/root.crt
# cp /etc/CA_local/crl/local_ca.crl /var/pgsql-8.4/data/root.crl

# chown postgres:postgres /var/pgsql-8.4/data/server.*


# chown postgres:postgres /var/pgsql-8.4/data/root.*
# chmod 0400 /var/pgsql-8.4/data/server.*
# chmod 0400 /var/pgsql-8.4/data/root.*

Después tenemos que actualizar nuestro fichero /var/pgsql-8.4/data/postgresql.conf.


Tenemos que cambiar el valor del parametro ssl.

ssl = on

Y arrancar PostgreSQL de nuevo usando el script det arranque de nuestro sistema. En


nuestro servidor ejemplo ejecutamos esto:

/etc/init.d/postgresql stop
/etc/init.d/postgresql start

Ahora actualizamos el fichero /var/pgsql-8.4/data/pg_hba.conf con esta linea:

hostssl all postgres 127.0.0.1/32 md5

Y volvemos a leer el fichero de configuración para activar los cambios.

/etc/init.d/postgresql reload

Si hemos hecho las cosas correctamente deberiamos de poder conectar con nuestro
servidor PostgreSQL via SSL y cifrando nuestro tráfico. La linea que hemos definido en
pg_hba.conf define que el usuario postgres puede conectarse desde 127.0.0.1/32 a
todas las bases de datos de nuestra instalacion solamente via SSL y escribiendo la clave
de acceso (Teneis que haber definido la clave del usuario postgres con antelación para
que esto funcione). Vosotros tendreis que configurar vuestro sistema para dar acceso a
los clientes de vuestro sistema.

postgres@core4:~$ psql -h 127.0.0.1


password:

psql (8.4.1)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
Type "help" for help.

postgres=#

La linea SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256) que se muestra al


conectar con el servidor nos indica que la conexión está cifrada via SSL.

Si habeis llegado hasta aquí, ya teneis el servidor PostgreSQL configurado para recibir
conexiones via SSL y cifrar el tráfico entre los clientes y el servidor de bases de datos.

Autentificar a los clientes mediante certificados SSL

También podemos utilizar certificados digitales para autentificar a los clientes que se
quieran conectar con nuestro servidor. De esta manera solamente podrán conectarse a
nuestro servidor los clientes que tengan instalado un certificado que esté firmado por
una autoridad de certificación (CA) registrada en el fichero /var/pgsql-
8.4/data/root.crt de nuestro servidor.

Para activar esta posibilidad lo primero que tenemos que hacer es crear un certificado
para nuestro cliente y firmarlo con nuestro certificado CA local. A continuación debemos
crear un subdirectorio (~/.postgresql/) en el directorio HOME del usuario que va a
ejecutar el programa cliente, y para terminar tenemos que copiar a este subdirectorio
cuatro ficheros. En nuestro ejemplo creamos el directorio /home/postgresql/.postgresql y
copiamos en el los ficheros necesarios:

 /home/postgresql/.postgresql/postgresql.crt: Certificado firmado por el CA local


que hemos creado para nuestro cliente
 /home/postgresql/.postgresql/postgresql.key: Llave privada del certificado creado
para el cliente
 /home/postgresql/.postgresql/root.crt: Certificado CA local utilizado para firmar
el certificado creado para el cliente
 /home/postgresql/.postgresql/root.crl: Fichero CRL (Certificate Revocation List)
con la lista de certificados revocados

Definimos los permisos necesarios:


# chmod 0400 /home/postgresql/.postgresql/*

A continuación actualizamos el fichero /var/pgsql-8.4/data/pg_hba.conf con una linea


similar a esta:

hostssl all postgres 127.0.0.1/32 md5 clientcert=1

Y leemos el fichero de configuración para activar los cambios.

/etc/init.d/postgresql reload

Los dos parámetros importantes en esta linea son hostssl y clientcert=1. De esta


manera podemos definir que la conexión se pueda realizar solamente desde clientes que
tengan instalado un certificado que esté firmado por una autoridad de certificación (CA)
que reconozcamos. Si no tuviesemos los ficheros necesarios
en /home/postgresql/.postgresql/, nos daria un error al intentar conectarnos.

# psql -h 127.0.0.1 -U postgres


psql: could not open certificate file "/home/postgres/.postgresql/postgresql.crt":
No such file or directory

FATAL: connection requires a valid client certificate


FATAL: no pg_hba.conf entry for host "127.0.0.1", user "postgres",
database "postgres", SSL off

Autentificar a los usuarios mediante certificados SSL

Hasta ahora hemos visto como encriptar el trafico de red y como autentificar a clientes
con certificados digitales. A partir de la versión 8.4.0 de PostgreSQL tambien se pueden
utilizar certificados digitales para autentificar a los usuarios que se quieran conectar con
nuestro servidor.

Este tipo de autentificación se activa usando el metodo 'cert' en la


opción métodocuando definamos el acceso en pg_hba.conf. Si usamos este método de
autentificación no necesitaremos escribir ninguna clave de acceso pero deberemos de
proveer un certificado valido.

El atributo CN (lo que se define en 'Common Name (eg, YOUR name) []:') del certificado
es el atributo que se comprueba para ver si corresponde con el usuario con el que se
intenta conectar. Si el CN no es igual al usuario de la base de datos con el que se
intenta conectar podemos usar mapas de usuario en el servidor para hacer la
conversión.

Lo primero que tenemos que hacer es crear un certificado para nuestro usuario
('Common Name (eg, YOUR name) []: postgres') y firmarlo con nuestro certificado CA
local. A continuación copiamos este certificado y la llave privada
a/home/postgresql/.postgresql/postgresql.crt y /home/postgresql/.postgresql/postgresql.k
ey en el ordenador cliente.

Después tenemos que actualizar el fichero /var/pgsql-8.4/data/pg_hba.conf con una linea


similar a esta:

hostssl all postgres 127.0.0.1/32 cert

Y por último leemos el fichero de configuración para activar los cambios.

/etc/init.d/postgresql reload

Si no tuviesemos el certificado correcto instalado, el sistema nos daria un error similar


al que se obtiene cuando la autentificación con certificado del ordenador cliente falla.
4. JBOSS To deploy a self-signed certificate: 

1. On the IBM Content Search Services server, open a command prompt and navigate to
the YourCSSfolder\bin folder. YourCSSfolder is the folder where you installed the IBM Content
Search Services server.

2. Export the certificate to a file by entering the following command: 

keytool -export -alias cssSelfsigned -keypass YourKeyPassword -


keystore selfsignedServerStore -storepass YourStorePassword -file
selfsignedCert.cer

3. Copy the selfsignedCert.cer file to a folder on the Content Platform Engine server, for


example, C:\IBM\cssKeystore.

4. On the Content Platform Engine server, open a command prompt and navigate to the folder
where you copied the selfsignedCert.cer file in step 3.

5. On the WebLogic application server where you deployed Content Platform Engine,
determine the current configured trust keystore. For example, WebLogic might be configured to use
DemoTrust (DemoTrust.jks) by default. (Note that Oracle does not recommend using DemoTrust
in a production environment.)

6. Deploy the selfsignedCert.cer file to the keystore that you determined in step 5 by


entering the following command. (If your keystore is not DemoTrust, or you are not running
WebLogic 10.3 on a Windows platform, make the appropriate substitutions in the command.)

keytool -import -alias cssSelfsigned -keystore


C:\Oracle\Middleware\WLserver_10.3\server\lib\DemoTrust.jks -storepass
YourStorePassword -file selfsignedCert.cer

7. Verify that the certificate was created in the keystore by entering the following command: 

keytool -list -v -keystore selfsignedCaStore


-storepass YourStorePassword

8. To perform SSL authentication, specify the following Java system parameters on the
Content Platform Engine application server. For more information about adding Java system
parameters, see your application server documentation. (If your keystore is not DemoTrust, or you
are not running WebLogic 10.3 on a Windows platform, make the appropriate parameter
substitution.)

o -
Djavax.net.ssl.trustStore=C:\Oracle\Middleware\WLserver_10.3\server\li
b\DemoTrust.jks
o -Djavax.net.ssl.trustStorePassword=YourStorePassword

9. Restart the Content Platform Engine application server instance.

To deploy a third-party CA certificate: 

1. Download a CA certificate from the Certificate Authority website and save it as ca.cer in
any folder on your Content Platform Engine server, for example,C:\IBM\cssKeystore.
2. On the Content Platform Engine server, open a command prompt and navigate to the folder
where you copied the ca.cer file in step 1.

3. On the WebLogic application server where you deployed Content Platform Engine,
determine the current configured trust keystore. For example, WebLogic might be configured to use
DemoTrust (DemoTrust.jks) by default. (Note that Oracle does not recommend using DemoTrust
in a production environment.)

4. Deploy the ca.cer file to the keystore that you determined in step 3 by entering the
following command. (If your keystore is not DemoTrust, or you are not running WebLogic 10.3 on a
Windows platform, make the appropriate substitutions in the command.)

keytool -import -alias cssThirdParty -keystore


C:\Oracle\Middleware\WLserver_10.3\server\lib\DemoTrust.jks
-storepassYourStorePassword -file ca.cer

5. Verify that the certificate was imported into the keystore by entering the following command:

keytool -list -v -keystore thirdPartyCaStore


-storepass YourStorePassword

6. To perform SSL authentication, specify the following Java system parameters on the
Content Platform Engine application server. For more information about adding Java system
parameters, see your application server documentation. (If your keystore is not DemoTrust, or you
are not running WebLogic 10.3 on a Windows platform, make the appropriate parameter
substitution.)

o -
Djavax.net.ssl.trustStore=C:\Oracle\Middleware\WLserver_10.3\server\li
b\DemoTrust.jks
o -Djavax.net.ssl.trustStorePassword=YourStorePassword

7. Restart the Content Platform Engine application server instance.


5. How to Configure SSL between Apache 2.2 and
JBoss AS 5.1 in a Cluster with mod_cluster
1.2.6
creado por Tim Elston el 19-jun-2014 16:45, modificado por última vez por Tim Elston el 19-jun-2014 16:45

Versión 1

Introduction
 
This blog post documents the solution that worked for me to encrypt the connection between
Apache 2.2.25 and JBoss AS 5.1 on port 8443 in a clustered environment (clustered with
mod_cluster 1.2.6 on port 8888), with Apache serving as a proxy (see note below  in this
introduction about the network configuration in which Apache serves as this proxy).  The
solution was achieved in a Windows environment, but it can, no doubt, be applied to Linux, with
appropriate command line and system equivalents. I used a self-signed certificate, so I will
include instructions for creating the necessary certificate files.  (I will not include instructions for
using a certificate signed by a Certification Authority.)  I will also include in this solution steps to
encrypt the connection between the browser client and Apache with SSL and steps to redirect
unencrypted requests on port 80 to encrypted requests on port 443.
 
I spent several weeks attempting to solve encryption between Apache 2.2 and JBoss AS 5.1,
partly because I was (and still am) a newbie to both Apache and JBoss, and partly because the
documentation I found online was various combinations of inadequate, inscrutable, incorrect,
and inapplicable to the version of JBoss I was using.  I do not claim to understand the solution
described here at a deep level; what I do know is that it proved to work in my environment,
unlike all of the examples in the existing documentation I found online. Hopefully this blog post
will be of help to newbie admins who are trying to achieve the same goal instead of become one
more contribution to confusion.  I write this blog as a newbie, for newbies, with a specific
emphasis on averting the several misconceptions that developed for me as I attempted to
interpret the existing online instructions. Apache and JBoss experts may find factual errors in
my explanations, and I welcome corrections, but I "do solumnly swear" that the solution, as
given in detail here, actually did work in my environment.
 
I mentioned earlier in this introduction that Apache serves as a proxy in this solution.  In the
particular environment for which this solution was implemented, the browser client, the Apache
server host, and the JBoss server host are in the same internal network.  For this reason, I
cannot vouch for whether the solution exactly as given is appropriate for Apache serving as
either a forward proxy or reverse proxy, according to the strict definitions of which both an
internal network and the Internet are at play. But even if changes are needed for those
topologies, I hope these instructions clear up some misconceptions about Apache and JBoss
configuration and set the novice on good conceptual ground for moving forward from here.
 
These instructions presume a clean installation of both Apache 2.2 and JBoss AS 5.1, with
clustering with mod_cluster 1.2.6 already configured. 
 
Creating the Self-Signed Certificate
 
Creating a working certificate file set specifically suited to meet the requirements of the Apache
2.2-to-JBoss AS 5.1 SSL connection, as stated by existing online documentation, and knowing
the right way to configure the certificate files was the single most difficult and frustrating task
involved in the solution.  Had I achieved the right certificate configuration from the outset, it is
likely that I would have saved myself days of seemingly endless trial-and-error troubleshooting. 
What seemed to be the most promising online instructions talked about creating both a keystore
and a truststore for JBoss, but those instructions did not work for me.  It didn't help that the
instructions were confusing and incomplete.  So, I hope in this section potentially to save a lot of
frustration for developers who find this guide.
 
These instructions presume that you have a version of the Java JDK installed on your system
and that its bin folder is indicated on your system Path variable. (This is for running
the keytool commands.)  They also presume that OpenSSL is installed on your system and
that its bin folder is indicated on your system Path variable.  For me, OpenSSL came as part of
the installation of Apache 2.2.25 I downloaded
from http://apache.mirrors.hoobly.com/httpd/binaries/win32/httpd-2.2.25-win32-x86-openssl-
0.9.8y.msi (note the "openssl-0.9.8y" part of the MSI file name), but you can install OpenSSL
separately. My OpenSSL executable was located under the Apache 2.2 bin folder. Wherever
your OpenSSL installation is, the folder in which its executable file exists needs to be in the
system Path variable.
 
1. Create the Certificate and Key Files
 
Note that in the following command you should change -days to the number of days you want
the certificate to be valid. Also note that if you use an installation of OpenSSL that is
independent of the Apache installation, the openssl.cnf file will be in a different location
from C:\Apache2.2\conf and possibly a different file name.  For example, if you
install Win64OpenSSL-0_9_86.exe from the OpenSSL.org site and do not change the default
installation directory, the -conf option should point toC:\OpenSSL\bin\openssl.cfg. 
 
The command below will output a server.crt file, a server.key file, and a .rnd file to the
directory from which you run it in a command prompt.  I created aC:\Apache2.2\certs folder
and ran this and the subsequent commands in this section from there. I will explain in later
sections where these files need to be declared in the Apache and JBoss configurations.
 
openssl req -new -x509 -nodes -days 365 -newkey rsa:2048 -out server.crt -keyout server.key
-config C:\Apache2.2\conf\openssl.cnf
 
When you run this command, you will be prompted for several items of information.  Fill in
information for each item.  The most critical item is the Common Name, which should be the
name of the website that will be used in the URLs that go to your application.  For example, if
your website is acme.com such that users will enter http://acme.com, then the Common Name
should be acme.com.  (Note: if you are configuring this in a local development environment in
Windows, you will need to enter a mapping of the local machine's IP address to this website
name in your hosts file. See the next section for instructions on how to do this.)
 
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:Illinois
Locality Name (eg, city []:Chicago
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Acme Company
Organizational Unit Name (eg, section) []:Roadrunner Gear
Common Name (e.g. server FQDN or YOUR name) []:acme.com
Email Address []:admin@acme.com
 
2. Create the Keystore for JBoss
 
For this solution, only a keystore will be needed.  Much, if not all, of the online documentation I
found said to use both a keystore and truststore, but none of the attempts to implement those
instructions worked for me. What finally worked was not configuring a truststore and using only
a keystore.  I have no doubt that using a truststore would work if properly implemented, but the
instructions I found did not provide enough information for me to be successful with that
approach.  Hopefully I will provide you with enough information for the keystore-only approach
to work for you.
 
The next command will create a temporary keystore in PKCS12 format from the certificate and
key created in the previous step. It will be used to create a keystore in JKS format in the next
command.  The command as written presumes
that server.crt, server.key, and .rnd are in the same location as the command
prompt.  The output keystore will be to the same location.
 
When you run the following openssl pkcs12 command, you'll be prompted for a password.  In this
and many examples online, the password 'changeit' is used. A different password should be
used in non-development environments.  These will be the prompts you see when you run the
next command.
 
Enter Export Password:changeit
Verifying – Enter Export Password:changeit
 
Note: If your version of Openssl did not create a .rnd file for the –rand option, see alternate
commands below.
 
openssl pkcs12 -export -inkey server.key -name acme -in server.crt -out
keystore.p12 –rand .rnd
 
If there is no .rnd file already in your working directory, then from the command prompt set a
RANDFILE system property. This property can be temporary to your command prompt session,
so simply running the following command should be sufficient.  Of course, if there is already a
valid RANDFILE system property on your machine, this setcommand does not need to be run.
 
set RANDFILE=.\.rnd
 
Now you can run the openssl pkcs12 command without the –rand option to create the
keystore.
 
openssl pkcs12 -export -inkey server.key -name acme -in server.crt -out keystore.p12
 
Next, use the keystore.p12 file to create a new keystore in JKS format. A prerequisite for
running this keytool command is an installation of the Java JDK, with its bin folder in the Path
system variable. This time you will be prompted to enter a password for the JKS keystore. To
avoid complications, use the same password you used forkeystore.p12.  You will use the
password of the JKS keystore in the JBoss configuration of the JKS keystore, and it helps to
keep things straightforward by using the same password for the source and destination
keystores when executing the command that follows.  Here is what you will be prompted to
enter when you run the command:
 
Enter destination keystore password:changeit
Re-enter new password:changeit
Enter source keystore password:changeit
 
The command will output a keystore.jks file to the working directory. After running this
command you will have three files that you will use to configure SSL on Apache and
JBoss: server.key, server.crt, and keystore.jks. These files will be configured for use
in subsequent sections. Run this command.
 
keytool -importkeystore -destkeystore keystore.jks -srckeystore
keystore.p12 -srcstoretype pkcs12 -alias acme
 
 
Configuring SSL between the Browser Client and Apache 2.2
 
The first SSL connection we'll implement is between the browser and Apache.  The connection
will be on port 443, which is the default port for HTTPS. The configuration demonstrated here
will include redirecting port 80 (HTTP) to port 443 (HTTPS), but SSL on port 443 is independent
of redirection and can be set up without it. The steps as shown in this section are on a clean
installation of Apache 2.2.25, so if your installation is not clean you may need to adapt these
steps to your configuration context.  On my system Apache is installed at C:\Apache2.2, so I
will reference that location in the instructions, but you should substitute your own location in for
it.
 
1. 1. Configure Port 443 with SSL
 
Open the httpd.conf file that is found under C:\Apache2.2\conf in a text editor of your
choice. Find the line that reads "LoadModule ssl_module modules/mod_ssl.so" and uncomment
it (that is, remove the '#' from the beginning of the line). In context, the line should look like the
middle one here:
 
#LoadModule speling_module modules/mod_speling.so
LoadModule ssl_module modules/mod_ssl.so
#LoadModule status_module modules/mod_status.so
 
In the same file, find the line that reads "Include conf/extra/httpd-ssl.conf" and uncomment it,
too. In context, it should look like this.
 
# Secure (SSL/TLS) connections
Include conf/extra/httpd-ssl.conf
#
 
The above Include directive tells the Apache compiler to include the directives that are stated in
the httpd-ssl.conf file. So, now open that file fromC:\Apache2.2\conf\extra in a text
editor.  Find the line that reads " <VirtualHost _default_:443>". After this line you will see several
directives, one of which is ServerName.  Apache programmatically set this value to the
computer name on which it was installed, followed by port number 443.  For example, if the full
computer name ismycomputer.acme.lcl, the Apache installation will have automatically set this
line to read
 
ServerName mycomputer.acme.lcl:443
 
If this name does not match the Common Name you used when you created the certificate in
the previous section, then you will need to change the ServerName value to use the Common
Name by which you identified the certificate.  In this tutorial, we used acme.com,
so ServerName should be changed to
 
ServerName acme.com:443
 
As stated previously, in a Windows system for local development you will need to enter a
mapping for the Common Name in your hosts file. This file can be found in%WINDIR
%\System32\drivers\etc.  The text editor used to modify it must be opened as an
administrator.  After substituting your IP address and Common Name, the editedhosts file
should contain the new entry, as shown in the next box.  The IP address should be mapped only
once.  If you map the same IP address to multiple domain names, JBoss will be able to read
only the first one, and if it doesn't match the name in the certificate, the SSL connection from
Apache to JBoss will fail.  If you are not in a development environment and your web domain is
already associated with the host IP through DNS (as is usually the case with system test
servers, for example, and is always the case with production servers), then you do not need to
modify the hosts file.
 
# Copyright (c) 1993-2009 Microsoft Corp.
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
# ...
# localhost name resolution is handled within DNS itself.
#     127.0.0.1       localhost
#     ::1             localhost
192.103.68.124          acme.com
 
Note, as shown below, that for the ErrorLog and TransferLog directives in the httpd-
ssl.conf file, I have modified the log file names to 443error.log and443access.log,
respectively. This is not necessary, but it helps distinguish between logs for the port 443 virtual
host and logs for other virtual hosts.  (For example, if you already have Apache and JBoss
configured in a clustered environment--a condition that this tutorial presumes--then you most
likely have a virtual host declared in yourhttpd.conf file for the mod_cluster_manager.  In my
configuration the mod_cluster_manager virtual host is declared to be on port 8888, so it has
been useful to distinguish between port 443 and port 8888 error and access logs.)  Also note
that the Apache installation created an admin email address based on the computer domain
extension:admin@acme.lcl. You should change this to an appropriate email address, such
as yourname@acme.com. In context, assuming you followed the changes explained above, the
lines should look like what is in the following example.
 
IMPORTANT: All paths in Apache .conf files should be created with forward slashes, not
back slashes, since the latter are not recognized by the compiler. 
 
<VirtualHost _default_:443>
 
#   General setup for the virtual host
DocumentRoot "C:/Apache2.2/htdocs"
ServerName acme.com:443
ServerAdmin yourname@acme.com
ErrorLog "C:/Apache2.2/logs/443error.log"
TransferLog "C:/Apache2.2/logs/443access.log"
 
Note that immediately below these lines is a directive
 
SSLEngine on
 
This is critical to a successful SSL connection and should be left uncommented.  Further below
this line, find the directives SSLCertificateFile andSSLCertificateKeyFile.  Change
the former to point to the server.crt file and the latter to point to the server.key file
created in the previous section. In my case, I created these files in C:\Apache2.2\certs, so I
will point to these files in that location. (Alternately, I could move the certificate and key files
to C:\Apache2.2\conf, which is the preset location.)  After these changes, the directives will
look like this:
 
#   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.)
SSLCertificateFile "C:/Apache2.2/certs/server.crt"
#SSLCertificateFile "C:/Apache2.2/conf/server-dsa.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.)
SSLCertificateKeyFile "C:/Apache2.2/certs/server.key"
#SSLCertificateKeyFile "C:/Apache2.2/conf/server-dsa.key"
 
Quick Check
 
After saving all edited files, restart the Apache service. This action needs to be taken as an
administrator, so you need credentials to an adminstrator account on the machine. On Windows
7, for example (assuming you are prototyping the configuration in a development environment),
you can access the Services console through Windows Start > type "services" in the search box
> right-click on Services when it appears from the search > click "Run as administator".  You will
be prompted for administrator credentials if you are not already logged in as an administrator. 
When the Services console opens, highlight the Apache2.2 service in the list and click the
Restart link.
 
After the Apache service has restarted, open your browser and, substituting your application
domain, enter https://acme.com and press Enter.  Since the SSL configuration uses the self-
signed certificate you created, the browser will prompt you for a response to the untrusted
certificate.  If you are using Internet Explorer the option link to accept the certificate reads
"Continue to this website (not recommended)".  Click this link.  If the configuration has no
issues, the default Apache page that reads "It works!" will load through the HTTPS connection
on port 443.  After the page loads, notice that the URL remains https://acme.com.
 
2. Configure Redirection from Port 80 to Port 443
 
At this point, if you enter the non-SSL URL http://acme.com, the "It works!" page will load over
the unencrypted HTTP connection on port 80.  If you want to redirect this URL to HTTPS on port
443, perform the following steps.  Note that this redirection is not critical, but not configuring it
will allow for unencrypted connections to your application.  That may be appropriate for some
pages of your application, in which case you'll need to refer to other documentation for how to
configure some pages to load over port 80 (HTTP) and others to load over port 443 (HTTPS).
But for the purposes of this tutorial, the assumption is that all resources from your application
will travel through encrypted connections.
 
There are many directive variations of redirection, which fall into two categories.  The first
category is the responsibility of the module mod_alias, and the second category is the
responsibility of the module mod_rewrite.  In general, mod_alias supports simple redirection and
has less performance cost, while mod_rewrite is relatively more expensive performance-wise
but supports more complex redirection rules.  For the purposes of this tutorial, I will limit the
configuration to the redirection of the server root to port 443 and use
the RedirectMatch directive from mod_alias. That is,  I will demonstrate only redirection
from http://acme.com to https://acme.com. Note that this will assume users access your app
directly at the server root. If, however, they needed to access it through a separate application
root--for example, acmeApp--you would need to modify theRedirectMatch directive to the
appropriate URL; for example,
 
RedirectMatch ^/$ https://acme.com/acmeApp/
 
instead of what is shown in the next box.  This would redirect
from http://acme.com to https://acme.com/acmeApp. See the official
Apache mod_alias and mod_rewritedocumentation for more complex redirection capabilities.
 
In the httpd.conf file, which you edited earlier, find the line that reads "Listen 80".  In a clean
installation, this line will be uncommented by default; it should remain uncommented for this
tutorial. Directly underneath this line, add a VirtualHost for port 80, as shown below.  You will
need to substitute your IP address and the server name in both the ServerName and
the RedirectMatch directives.  These values should match those that you entered into your
Windows system's hosts file in the previous subsection. It is critical that ":80" not be removed
from the VirtuaHost declaration and that the redirection be to the HTTPS version of your
application's URL. The "Match" part ofRedirectMatch allows for Perl compatible regular
expressions to be used, and in this configuration, the regular expression operators ^ and $ are
being used to limit redirection to the server root. The / character in the substring ^/
$ represents the server root. See documentation on Perl Compatible Regular Expressions for
more information about the meaning of ^, $ and other operators, and how to use them.
 
Note that the RedirectMatch directive requires that the mod_alias module be loaded, which is
done when the line "LoadModule alias_module modules/mod_alias.so" in thehttpd.conf file
is uncommented.  This line is uncommented by default in a fresh installation, but if it has been
commented in your Apache instance, you need to uncomment it before restarting with
the RedirectMatch directive in place, as shown here:
 
Listen 80
<VirtualHost 192.103.68.124:80>
      ServerName acme.com
      RedirectMatch ^/$ https://acme.com/
</VirtualHost>
 
Quick Check
 
Restart the Apache service again (as described above). Enter http://acme.com (substituting your
Common Name).  If all is well, you should be prompted to trust the self-signed certificate again,
and when you click "Contine to this website (not recommended)" the "It works!" page will load
through HTTPS on port 443.  Once the page is loaded, the displayed URL should
read https://acme.com.
 
 
Configuring SSL between Apache 2.2 and JBoss AS 5.1
 
Now comes what was for me the hard part, which I anticipate will be easy for you as you follow
this guide.  I won't get into all the points of confusion that I had to struggle with, but if you are a
newbie and have already tried some of the documents I tried to use, you are probably familiar
enough with them. In the end, the configuration that worked for me, and which I document here,
is simple, but it took me several weeks to tangle and untangle the misconceptions that grew in
my mind as I tried as a newbie to interpret the various online documents I found for this task.
 
As stated earlier, this section presumes that you have Apache 2.2 and JBoss AS 5.1 already
configured in a cluster with Apache's mod_cluster 1.2.6 (or 1.2.0; see note below), with Apache
on the front end as the access point and at least one JBoss server as a cluster node.  In this
tutorial, the 'all' server will be used as the only node (found atJBOSS_HOME\server\all,
where JBOSS_HOME represents the home installation directory of your JBoss instance). If you
have multiple nodes in your configuration, you simply apply the same steps for
editing server.xml on each node, as I describe below for the one node in my tutorial
configuration. 
 
I use mod_cluster 1.2.6 here, but I also successfully configured the SSL connection between
Apache and JBoss in a cluster configured with mod_cluster 1.2.0.  However, the 1.2.0 version of
mod_cluster did not support the use of the RewriteRule directive (which I mentioned above
but do not demonstrate here), so I upgraded to mod_cluster 1.2.6.
 
1. Configure Apache for SSL Proxying to JBoss
 
Open the httpd-ssl.conf file that you edited in the previous section. This is located
at APACHE_HOME\conf\extras\httpd.ssl in a standard Apache 2.2 installation, where
APACHE_HOME represents the root directory of your installation.  Find the virtual host for port
443 in this file.  The default declaration is "<VirtualHost _default_:443>", but if it has been
modified in your configuration the "_default_" portion might have been replaced with your host IP
address.  Assuming that you have already configured
theServerName, SSLEngine, SSLCertificateFile,
and SSLCertificateKeyFile directives as described in the previous section of this tutorial,
add the following directives somewhere after the ServerName directive, substituting values
particular to your environment.  I will explain the directives and which values to use, below.
 
SSLProxyEngine On
SSLProxyCACertificateFile "/Apache22/certs/server.crt"
ProxyPass / https://192.103.69.99:8443/
ProxyPassReverse / https://192.103.69.99:8443/
 
In my httpd-ssl.conf file they are situated between
the TransferLog and SSLEngine directives.
 
<VirtualHost _default_:443>
 
#   General setup for the virtual host
DocumentRoot "C:/Apache2.2/htdocs"
ServerName acme.com:443
ServerAdmin admin@dshs.wa.lcl
ErrorLog "C:/Apache2.2/logs/443error.log"
TransferLog "C:/Apache2.2/logs/443access.log"
 
SSLProxyEngine On
SSLProxyCACertificateFile "/Apache2.2/certs/server.crt"
ProxyPass / https://192.103.69.99:8443/
ProxyPassReverse / https://192.103.69.99:8443/
 
#   SSL Engine Switch:
#   Enable/Disable SSL for this virtual host.
SSLEngine on
 
In the configuration shown, requests to the Apache server on port 443 are being redirected to
port 8443 on the JBoss server.  In the next step, the 'all' JBoss server, which is the only node
in my cluster, will be configured to accept requests on port 8443.  The two
directives ProxyPass and ProxyPassReverse are where you configure requests on port 443
to "pass through" Apache and go on to JBoss on port 8443. Paraphrasing, ProxyPass means
something like, "Apache is a proxy that incoming requests pass through",
and ProxyPassReverse means something like, "Returning responses from JBoss can pass
back through Apache to the browser." A single SSL session is being established for round trip
communication between the browser and JBoss, with Apache in the middle.  The first segment
of the session channel is over port 443 between the browser and Apache, and the second
segment of the session channel is over port 8443 between Apache and JBoss.
 
Note that the only modifications you need to perform on the Apache configuration for SSL
connection to JBoss is in this virtual host for port 443.  Assuming a standard mod_cluster
configuration, there is a separate virtual host, probably declared in your httpd.conf file, or
perhaps in APACHE_HOST\conf\extras\httpd-vhosts.conf, which is used for managing
the cluster, but this virtual host should not be configured to use SSL.  In my configuration the
port of this virtual host is 8888, but on yours it most likely is some other number.  Depending on
how your cluster is configured, you may be able to identify this virtual host by one of two ways.
The first way is to find a virtual host in which the ManagerBalancerName directive is declared
(probably in either the httpd.conf or httpd-vhosts.conf file). 
 
The second way is to locate the
file JBOSS_HOME\server\all\deploy\mod_cluster.sar\META-INF\mod_cluster-
jboss-beans.xml. Depending on which server your configuration uses, the "all" portion of
this path may be something different; it depends on which server you are using. For example, if
you are using the 'default' server, the path would
be JBOSS_HOME\server\default\deploy\mod_cluster.sar\META-
INF\mod_cluster-jboss-beans.xml.  It could also be a custom server name defined by a
subdirectory of JBOSS_HOME\server; for example, JBOSS_HOME\server\node1,
where node1 is a custom server that constitutes the first node of your cluster.  Upon locating
the mod_cluster-jboss-beans.xml file--there should be one such named file for each
server node in your cluster--find the proxyList property. For each Apache server in the
cluster, there may be a hard-coded IP address and port number (but there might not, in which
case this method won't work for discovering which port your mod_cluster_manager is on).  For
example, in my configuration, the proxyList property looks like this:
 
<!-- Comma separated list of address:port listing the httpd servers
     where mod_cluster is running. -->
<property name="proxyList">192.103.68.124:8888</property>
<!-- URL prefix to send with commands to mod_cluster.  Default is no prefix. -->
<!--property name="proxyURL"></property-->
 
This shows that cluster management is occurring over port 8888, and there should be
a VirtualHost declared for this port in httpd.conf, or perhaps
inAPACHE_HOST\conf\extras\httpd-vhosts.conf.  The bottom line is that this virtual
host should not be configured for SSL.  If your cluster is already working before you attempt to
configure SSL between Apache and JBoss, you should not modify any of the directives within
this virtual host. The application resource traffic between Apache and JBoss will be over port
8443, so 8443 is the port that will be encrypted (in the step below).  The mod_cluster_manager
port (in my case, port 8888) should be left alone for the purposes of this tutorial. I spent a lot of
time confused about which port to encrypt; that's why I've gone to lengths to make this point
clear.
 
2. Configure JBoss Nodes for SSL Connectivity to Apache
 
Now the JBoss server needs to be configured to accept application traffic over port 8443.  In the
previous section, we configured Apache to redirect requests it receives on it's own port 443 to
the JBoss host's port 8443. But for that to work, we must configure JBoss to accept encrypted
application requests on port 8443.
 
First, on the JBoss server--if you are configuring in a development environment, this may be the
same server on which Apache is running--copy the keystore.jks file you created earlier in
this tutorial to a location under your JBoss installation. In my case, I created a new
folder C:\JBoss_AS_5.1\server\all\certs and pasted the keystore file
there.  C:\JBoss_AS_5.1 is the home directory of my JBoss installation.  I'll refer to this
location in subsequent steps as JBOSS_HOME.
 
Next, open the file JBOSS_HOME\server\all\deploy\jbossweb.sar\server.xml in a
text editor of your choice. As stated earlier, the "all" portion of this path will be different if you are
using a server other than the 'all' server.  Uncomment the Connector element for port 8443
and edit it as shown below, making appropriate modifications for the location of
the keystore.jks file you pasted above and the password you used when you created it. 
Note that there will also be Connector elements for ports 8009 and 8080.  These should be
left alone.
 
Pay special attention to the sslProtocol attribute value.  This needs to be within the scope of
the SSLProtocol directive that is declared in the httpd-ssl.conf file on the Apache
server.  In my case, that directive is declared as
 
#   SSL Protocol support:
#   List the protocol versions which clients are allowed to
#   connect with. Disable SSLv2 by default (cf. RFC 6176).
SSLProtocol all -SSLv2
 
This directive accepts all SSL protocols except SSLv2.  As of this writing TLS is the most secure
protocol, but if you declare this protocol you may need to modify a property on your browser to
enable it. In the default installation, JBoss sets TLS as the value of the sslProtocol attribute,
as shown below. For the purposes of this tutorial, I will use TLS.  In your case, you may want
either to change this to SSLv3 or to stay with TLS, making sure that your browser settings
accept it and that it is within the declared scope of theSSLProtocol directive in httpd-
ssl.conf.  (To enable TLS in Internet Explorer, go to Tools > Internet Options > Advanced tab
> scroll down to Security > and check the "Use TLS x.x" options you want to use.)  Note that
the clientAuth attribute is set to false.  It may be tempting to change this to true, but it needs
to be left at false for the connection to succeed because setting it to true means that the SSL
handshake will require a valid certificate chain, which is not used with a self-signed certificate.
 
Here is what the Connector element in server.xml should look like:
 
<Connector protocol="HTTP/1.1" SSLEnabled="true"
           port="8443" address="${jboss.bind.address}"
           scheme="https" secure="true" clientAuth="false"
keystoreFile="${jboss.server.home.dir}/certs/keystore.jks"
           keystorePass="changeit" sslProtocol = "TLS"
            />
 
Quick Check
 
Restart the JBoss server.  Depending on your configuration, you may be able to do this through
the Windows Services console or by starting JBoss from the command line
usingJBOSS_HOME\bin\run.bat. Now send a request to JBoss over port 8443 directly,
without going through Apache. For example, if the IP of your JBoss host is 192.103.69.99, send
this URL:
 
     https://192.103.69.99:8443
 
Whatever resource is configured to load from the server root should display over HTTPS after
you accept the unsigned certificate by clicking "Continue to this website (not recommended)" on
Internet Explorer. This might by your application's home page, or it might be the JBoss
management page, depending on your configuration.
 
Final Check
 
If the connection directly from the browser to JBoss over port 8443 succeeded in the previous
quick check, you know that JBoss is configured to accept proxy connections from Apache on
that port. When Apache was configured to serve as a proxy to JBoss in step 1 of this
section, ProxyPass was set to forward requests over port 443 to JBoss over port 8443. And
earlier, port 80 was configured to redirect requests for the resource at the server root to port
443.  If all is well, then, a request from the browser for the server root over port 80 (that is,
using http://) should redirect to the Apache host's port 443, which will forward the request to
JBoss's port 8443. Here's the final test:
 
     http://acme.com
 
If I have written these instructions correctly and clearly enough, you have implemented them as
described, and there are no complicating factors in your environment that weren't in mine, you
should be prompted to trust the self-signed certificate, and the expected resource should load
from the JBoss server root over an SSL connection.

6. Generate Your Apache Self Signed Certificate


Great! So now you know when to use an Apache self signed certificate and
when not to. Now, let’s create one: First, we need to make sure OpenSSL is
installed. If you are installing the self signed certificates on Windows, grab
the Windows version of OpenSSL (If you get an error when you run the installer,
you may need to download the Visual C++ 2008 Redistributables listed on that
page first). If you are on another type of server, try running “openssl” on the
command line to see if OpenSSL is already installed. If it is not, you will need to
download a package or compile it from its source.

Once you have OpenSSL installed, just run this one command to create an Apache
self signed certificate:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout

mysitename.key -out mysitename.crt

You will be prompted to enter your organizational information and a common name.
The common name should be the fully qualified domain name for the site you are
securing (www.mydomain.com). You can leave the email address, challenge
password, and optional company name blank. When the command is finished
running, it will create two files: a mysitename.key file and a mysitename.crt self
signed certificate file valid for 365 days.

Install Your Self Signed Certificate

Now, you just need to configure your Apache virtual host to use the SSL certificate.
If you only have one Apache virtual host to secure and you have an ssl.conf file
being loaded, you can just edit that file. Otherwise, you will need to make a copy of
the existing non-secure virtual host, paste it below, and change the port from port
80 to 443.

1. Open your Apache configuration file in a text editor. Depending on your


operating system and Apache version, it will be located in different places
but you will usually find it at /etc/httpd/httpd.conf. On a Windows machine,
you will usually find it at C:\Program Files\Apache\Apache2\conf\httpd.conf
2. In most cases, you will find the <VirtualHost> blocks in a separate file in a
directory like /etc/httpd/vhosts.d/ or /etc/httpd/sites/. Add the lines in bold
below. <VirtualHost 192.168.0.1:443>
DocumentRoot /var/www/website
ServerName www.yourdomain.com
SSLEngine on
SSLCertificateFile /etc/ssl/crt/mysitename.crt
SSLCertificateKeyFile /etc/ssl/crt/mysitename.key
</VirtualHost> 
3. Change the names of the files and paths to match your certificate files. Save
the changes and exit the text editor.
4. Restart your Apache web server using one of the following commands:
/usr/local/apache/bin/apachectl startssl
/usr/local/apache/bin/apachectl restart

Learn more about installing a certificate in Apache.

Check the Apache Self Signed Certificate Installation

If the Apache site is public, you can use


our SSL Checker to verify that it is installed
correctly (ignoring the warning that it is not
trusted because it is self signed). Otherwise,
just go to the website in your web browser
using https in the address bar
(https://www.mysitename.com) and verify
that the certificate is being given out by the
server by clicking the certificate icon (after
clicking through the warnings).

También podría gustarte