Guia Certificados Autofirmados
Guia Certificados Autofirmados
Guia Certificados Autofirmados
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).
Programas necesarios
1. Java JRE
2. Tomcat 7.0
¿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.
1. Abrimos el cmd
2. Introducimos el comando
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 ejecutado este comando se creara un archivo en la ruta especificada, en este caso en
la carpeta key se creara un archivo llave.
El archivo server.xml esta en la ruta
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
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
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.
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.
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.
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:
Primero tenemos que instalar openssl en nuestro ordenador, para esto podemos utilizar
el sistema de instalación por defecto de nuestro sistema operativo.
# mkdir -m 0755 \
/etc/CA_local \
/etc/CA_local/private \
/etc/CA_local/certs \
/etc/CA_local/newcerts \
/etc/CA_local/crl
# 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:
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
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.
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:
# 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.
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.
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:
Vamos a asegurar mejor la clave privada del certificado. Este fichero es privado y no se
debe de distribuir:
# cd /etc/CA_local/
# openssl x509 -in certs/ejemplo.postgresql-es.org.crt -noout -text
# 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
# 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
Una vez que tenemos todos los certificados que necesitamos, tenemos que configurar
PostgreSQL para activar y usar SSL.
# 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
ssl = on
/etc/init.d/postgresql stop
/etc/init.d/postgresql start
/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.
psql (8.4.1)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
Type "help" for help.
postgres=#
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.
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:
/etc/init.d/postgresql reload
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.
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.
/etc/init.d/postgresql reload
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.
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.)
7. Verify that the certificate was created in the keystore by entering the following command:
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
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.)
5. Verify that the certificate was imported into the keystore by entering the following command:
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
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.
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
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.
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.