Using the Secure Sockets Layer

SSL is a protocol that allows clients and servers in a network environment to communicate securely. In addition to encryption of data (and hence secure communication), SSL provides for authentication.

The security protocols on which SSL is based are public key encryption and symmetric key encryption. Public key encryption uses a pair of encryption keys to encode a message—a public key that’s public and a private key that isn’t disclosed to anyone else. Anyone wanting to send a message to an application that has a known public key encrypts it with that key. Only the corresponding private key can decrypt the message, and thus the transmission is secure. Symmetric key encryption, on the other hand, uses the same secret key for both encryption and decryption. This algorithm, however, needs a reliable way to exchange the secret key between the two end points in the transmission.

When a client opens an SSL connection with a server, an SSL handshake is performed. The procedure for an SSL handshake is as follows:

  1. The server sends its digital certificate. This contains the public key of the server, information about the server, the authority that issued the server’s certificate, and the use-by date of the certificate.

  2. The client then authenticates the server based on the validity of the certificate and trustworthiness of the authority that issued the certificate. Certificates issued by well-known (and trusted) certificate authorities (CAs), such as VeriSign and Thawte, are recognized by most Web browsers. If the certificate can’t be validated, the user is warned, and they can choose to either accept the certificate or deny it.

  3. A session key is then generated and exchanged over the connection. The connection is now secured by the public key encryption mechanism, which means that the exchange is secure. The session key is a symmetric key and is used for the duration of the session to encrypt all subsequent data transmissions.

The server configuration may also require the client to present its own authentication details. In this situation, another step is introduced in the SSL handshake. Such a requirement isn’t common and is used only in some business-to-business application environments.

The HTTP over SSL (HTTPS) protocol uses SSL as a layer under HTTP. Transport Layer Security (TLS) is the Internet Engineering Task Force (IETF) version of the SSL protocol. It’s defined by RFC 2246 (http://www.ietf.org/rfc/rfc2246.txt) and is intended to eventually supersede SSL.

Adding support for SSL or TLS in Tomcat is a four-step process.

  1. Download and install an SSL/TLS implementation (not necessary for JDK 1.4 and newer).

  2. Create the certificate keystore containing a self-signed certificate, which is generated by you and isn’t guaranteed by anyone else, such as a CA.

  3. Obtain a certificate from a CA such as VeriSign (http://www.verisign.com), Thawte (http://www.thawte.com), or Trustcenter.de (http://www.trustcenter.de). Use your self-signed certificate to generate a certificate-signing request, and submit it to the CA to get a certificate digitally signed by them. This certificate, when presented to a user, guarantees that you are who you claim to be. If you’re using Tomcat in a test/development environment, you can skip this step. You’d need a certificate for a production deployment, though, as users may not be willing to accept a self-signed certificate.

  4. Make the Tomcat configuration changes for SSL.

Installing JSSE

Java Secure Socket Implementation (JSSE) is Sun’s implementation of the SSL and TLS protocols. JSSE is available for free but isn’t open source. For more information on JSSE, see http://java.sun.com/products/jsse/. You have to install JSSE if you’re using JDK 1.2 or 1.3. JDK 1.4 and newer includes JSSE, so you should skip the following step if you have JDK 1.4 installed.

Download JSSE from http://java.sun.com/products/jsse/. The three JSSE JAR files (jsse.jar, jnet.jar, and jcert.jar) need to be in Tomcat’s classpath. Copy them to the JAVA_HOME/jre/lib/ext directory.

Preparing the Certificate Keystore

You may have seen how to prepare a keystore in Chapter 9, but here’s a reminder:

 > JAVA_HOME\bin\keytool -genkey -alias tomcat -keyalg RSA 

The -genkey option specifies that a key pair (private key, public key) should be created. This key pair is enclosed in a self-signed certificate. The -keyalg option specifies the algorithm (which in this case is RSA) to be used for the key pair. All keystore entries are accessed via unique aliases using the -alias option—here the alias is tomcat. The keytool command will ask for a password, which you should take the usual precautions with.

The default name for the keystore file is .keystore, and it’s stored in the home directory of the user who runs the keytool command. This directory will vary depending on the operating system. For example, if you install Tomcat as a user called tomcat on Linux, the keystore file will be in /home/tomcat. Similarly, if you install it as the tomcat user on Windows, the keystore file would be in C:\Documents and Settings\tomcat. You can also specify an alternative keystore filename and password using the -keystore and -keypass options.

 > JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA    -keypass somepass -keystore /path/to/keystorefile 

Here’s an example run of the keytool:

 > keytool -genkey -alias tomcat -keyalg RSA  Enter keystore password:  tomcat  What is your first and last name?    [Unknown]:  localhost  What is the name of your organizational unit?    [Unknown]:  Editorial  What is the name of your organization?    [Unknown]:  Java  What is the name of your City or Locality?    [Unknown]:  Glasgow  What is the name of your State or Province?    [Unknown]:  Scotland  What is the two-letter country code for this unit?    [Unknown]:  UK  Is CN=localhost, OU=Editorial, O=Java, L=Glasgow, ST=Scotland, C=UK correct?    [no]:  yes  Enter key password for <tomcat>          (RETURN if same as keystore password): 

Note that the first field you’re asked for is the domain name of your server, which becomes the common name (CN). This needs to be of the format www.domainname.com, hostname.domainname.com, or just domainname.com. This name is embedded in the certificate. The CN should be the fully qualified hostname for the machine where Tomcat is deployed. If this isn’t so, then users will get a warning message in their Web browsers when they try to access a secure page from your Web site, as you saw in Chapter 9.

If this is a test/development environment or you don’t want a certificate from a CA, you can stop here. You’re now ready to make Tomcat-related setup changes. If you were deploying in a production environment, you’d need to get a certificate that’s validated by a CA.

Installing a Certificate from a Certificate Authority

First, create a local certificate as before using the keytool command.

 > keytool -genkey -alias tomcat -keyalg RSA -keystore <keystore_filename> 

Next, use this certificate to create a certificate signing request (CSR).

 > keytool -certreq -keyalg RSA -alias tomcat -file certreq.csr -keystore <  keystore_filename> 

If the keystore file is the default (that is, a file named .keystore in the home directory), then you can omit the -keystore <keystore_filename> option.

The -certreq option creates a CSR file called certreq.csr that you can submit to the CA to get a certificate. The file will be in the directory where you ran the keytool command previously. Getting a certificate requires payment to the CA for the authentication services. Some CAs have test certificates available for download at no cost, which are usually valid only for a short time.

To submit your CSR, go to the CA of your choice and paste the contents of the file into the form provided there. Then follow the instructions.

Importing the Certificate

After you have the certificate from the CA, you need to get the chain certificate (also called the root certificate) from them. You can download this from the following sites (depending on the CA):

  • http://www.verisign.com/support/install/intermediate.html

  • http://www.trustcenter.de/set_en.htm

  • http://www.thawte.com/roots/

The chain certificate is a self-signed certificate from the CA that contains its well-known public key. You can view the contents of a certificate using the -printcert option.

 > keytool -printcert -file /path/to/certificate 

This is good practice before you import a third-party certificate into the keystore. You then import the chain certificate into the keystore.

 > keytool -import -alias root -keystore <keystore_filename>    -trustcacerts -file <filename_of_the_chain_certificate> 

And finally, import the new certificate.

 > keytool -import -alias tomcat -keystore <keystore_filename>    -trustcacerts -file <certificate_filename> 

Here, the <filename_of_the_chain_certificate> contains the chain certificate you got from the CA. As mentioned earlier, the -keystore <keystore_filename> option isn’t required if the keystore file has a default name (.keystore). You’re now ready to make Tomcat-related setup changes.

Protecting Resources with SSL

You can protect resources with SSL just as you can protect resources with authentication constraints. The <user-data-constraint> subelement of <security-constraint> in web.xml specifies the guaranteed integrity of the data flowing between the client and the server for this resource. There are three levels of integrity: NONE, INTEGRAL, and CONFIDENTIAL.

NONE means there’s no guarantee that the data hasn’t been intercepted and tampered with, and INTEGRAL guarantees the integrity of the data, meaning that the data hasn’t been interfered with. The strongest guarantee is CONFIDENTIAL, which guarantees that a third party hasn’t intercepted the data. If you specify INTEGRAL or CONFIDENTIAL, the server will use SSL for all requests to this resource by redirecting the client to the SSL port of the server. The redirection port is configured in the redirectPort attribute of the HTTP connector.

For your secure resource, you want to be sure that all the data you transfer is safe, so you’ll use the CONFIDENTIAL level. Simply add the element in Listing 12-16 to the <security-constraint> in your web.xml file from the previous example.

Listing 12-16: Guaranteeing the Integrity of Data with a Security Constraint

image from book
   <security-constraint>      ...      <user-data-constraint>        <description>         Constrain the user data transport for the whole application        </description>        <transport-guarantee>CONFIDENTIAL</transport-guarantee>      </user-data-constraint>    </security-constraint> 
image from book

This will force all requests for your secure Web application to use HTTPS, even if the original request came in over HTTP. This is the only setup required in web.xml.

Configuring the SSL Connector

The setup procedure for an SSL connector is straightforward. You’ve already seen its attributes in Chapter 4, so this section covers how to configure a connector for the keystore you created earlier.

Modify the default SSL HTTP connector, and add the location and password of the keystore if appropriate (see Listing 12-17).

Listing 12-17: Configuring an SSL Connector

image from book
 <!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->  <Connector port="8443"             maxThreads="150" minSpareThreads="25" maxSpareThreads="75"             enableLookups="false" disableUploadTimeout="true"             acceptCount="100" debug="0" scheme="https" secure="true"             clientAuth="false" sslProtocol="TLS"             keystorePass="tomcat"/> 
image from book

Now start Tomcat, and point a browser to http://localhost/tomcatBook/. You’ll be presented with a warning about the suspicious certificate (note that this warning may vary depending on your browser).

You can choose to view the certificate to see the details of the issuer. These details will match those you specified when you created the certificate. Before you proceed your browser will give you the option to install this certificate forever (you’ll have to view the certificate with Internet Explorer to do this), which means that you trust this site and won’t be shown the security warning again. An additional warning will be given if you didn’t use the domain name of your server.

Once you’ve confirmed you’re happy with accepting this certificate, you’ll see the login page from Listing 12-13, only this time your session will be conducted over SSL. To confirm this, examine the URL. It should be https://localhost:8443/tomcatBook/. Tomcat knows to redirect you to this port for SSL because of the redirectPort="8443" setting in the default HTTP connector.

Using SSL with the Apache Web Server

You’ve seen how the stand-alone HTTP connector handles SSL. Another approach that’s more widely used is to have a dedicated Web server handle the SSL-related functionality. This is a more stable configuration and has better performance. In this configuration, the communication between the user’s browser and Web server is encrypted over SSL, but the communication between the Web server and Tomcat isn’t.

Before you can configure Apache, you need to create a private key and certificate. This is a separate process from Tomcat’s because the keytool command creates a propriety keystore format (maintained by Sun) that Apache can’t use. To create a private key and a certificate for Apache, you need the OpenSSL library from http://www.openssl.org.

If you’re using Windows, you should visit http://hunter.campbus.com and download the Apache/OpenSSL combination for your Apache installation. You don’t need to install the whole bundle but will need the openssl utility and the libeay32.dll, ssleay32.dll, and mod_ssl.so files. Place the first three (openssl, libeay32.dll, and ssleay32.dll) in Apache’s bin directory and mod_ssl.so in Apache’s modules directory.

If you don’t have an openssl.cnf file, create one with contents similar to those shown in Listing 12-18. These are the certificate details you would have entered in the previous keytool examples.

Listing 12-18: The openssl.cnf File Setting Your Server’s Certificate Properties

image from book
 [ req ]  default_bits = 1024  distinguished_name = req_distinguished_name  attributes         = req_attributes  [ req_distinguished_name ]  countryName                    = Country Name (2 letter code)  countryName_default            = UK  countryName_min                = 2  countryName_max                = 2  stateOrProvinceName            = State or Province Name (full name)  stateOrProvinceName_default    = Scotland  localityName                   = Locality Name (eg, city)  localityName_default           = Glasgow  organizationName               = Organization Name (eg, company)  organizationName_default       = Java  organizationalUnitName         = Organizational Unit Name (eg, section)  organizationalUnitName_default = Editorial  commonName                     = Common Name (eg, YOUR name)  commonName_default             = localhost  commonName_max                 = 64  emailAddress                   = Email Address  emailAddress_max               = 40  [ req_attributes ]  challengePassword              = A challenge password  challengePassword_min          = 4  challengePassword_max          = 20 
image from book

Then run the following to create a private key:

 > openssl genrsa -des3 1024 > ./certs/localhost.key  Loading 'screen' into random state - done  Generating RSA private key, 1024 bit long modulus  ...++++++  ...............++++++  e is 65537 (0x10001)  Enter pass phrase:  Verifying - Enter pass phrase: 

This will create the localhost.key key file in the certs directory with password protection. You’ll have to provide this password to enable SSL when you start or restart Apache. If you don’t want to use a password to protect this file (more on this later), then omit the -des3 switch.

Now create a CSR, which you can use to request a certificate from a CA or create a self-signed certificate.

 > openssl req -new -key ./certs/localhost.key    -out ./certs/localhost.csr -config openssl.cnf  Enter pass phrase for ./certs/localhost.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) [UK]:  State or Province Name (full name) [Scotland]:  Locality Name (eg, city) [Glasgow]:  Organization Name (eg, company) [Java]:  Organizational Unit Name (eg, section) [Editorial]:  Common Name (eg, YOUR name) [localhost]:  Email Address []:  Please enter the following 'extra' attributes  to be sent with your certificate request  A challenge password []:tomcat 

This creates the localhost.csr file in the certs directory. Note the default values from openssl.cnf. Provide the password for the private key as appropriate. The final step is to create the certificate.

 >openssl req -x509 -key ./certs/localhost.key -in ./certs/localhost.csr    -out ./certs/localhost.crt  Enter pass phrase for ./certs/localhost.key: 

This creates the localhost.crt certificate in the certs directory. You’re now ready to configure Apache and Tomcat.

Deploying a Web Application

Begin by configuring Apache. If you’re responding to user requests on port 80 (the default HTTP port) and the SSL port (default value 443), Apache needs to listen on both these ports. In this example you’ll protect the tomcatBook Web application with Apache’s SSL and leave the default Apache files unprotected.

 # Listen on port 80 and 443 (the SSL port)  Listen 80  Listen 443  # Use name-based virtual hosts on these ports  NameVirtualHost *:80  NameVirtualHost *:443 

You now have to make the SSL-related settings in Apache.

 <VirtualHost *:443>    # The name of this host    ServerName localhost    # Switch on SSL for this host    SSLEngine on    # The path to the certificate    SSLCertificateFile /path/to/certs/localhost.crt    # The path to the private key    SSLCertificateKeyFile /path/to/certs/localhost.key    # You are protecting the tomcatBook webapp    # so enable the connector settings    Include /path/to/tomcatBook/WEB-INF/jk2/jk2.conf"  </VirtualHost> 

Here you create a virtual host listening on the SSL port (443) for protecting the tomcatBook Web application. You switch on SSL for this host and set the locations of the certificate and the private key. Assuming that you’ve enabled mod_jk2 and have generated the settings using the techniques from Chapter 9, you then include the settings for the tomcatBook Web application.

Next, you need to configure the non-SSL host for Apache’s static files.

 <VirtualHost *:80>    ServerName localhost    DocumentRoot /path/to/Apache2/htdocs  </VirtualHost> 

A final point to consider is running Apache and SSL on Windows. The default private key password prompt doesn’t work on Windows, so you must either configure a private key without password protection or configure a script or utility to provide the password. Both scenarios have inherent problems, so you must make sure that both files (the private key or the utility) are heavily protected.

To specify the file that will give the key password to Apache, set the following outside your virtual host definitions:

 SSLPassPhraseDialog exec:bin/password.bat 

This points to the password batch file in Apache’s bin directory. Listing 12-19 shows the password batch file.

Listing 12-19: The password.bat File That Sends the Key Password to Tomcat

image from book
 @echo tomcat 
image from book

There’s no more to it than that (providing that tomcat is your key password), though this doesn’t do any checking as to whom is running the script and for which domain. If more than one domain were to use this file, and each domain had a different password, then you’d have to check the domain name. Apache sends this information as servername:port as the first argument to the script and the appropriate algorithm as the second argument. Listing 12-20 shows an example batch file that does this for the server you have configured.

Listing 12-20: The password.bat File That Sends the Key Password to Tomcat

image from book
 @echo off  if "%1" == "localhost:443" @echo tomcat 
image from book

Here you check that the first argument matches the name and port of the server. If this is the case, then you echo the password to stdout.

Listing 12-21 shows an example workers2.properties file for this setup.

Listing 12-21: The workers2.properties file using Apache’s SSL functionality

image from book
 # Define the channel  [channel.socket:localhost:8009]  # Define the worker  [ajp13:localhost:8009]  channel=channel.socket:localhost:8009  # Uri mapping  [uri:localhost:443/tomcatBook/*]  group=ajp13:localhost:8009 
image from book

The important thing to note here is the URI mapping. Only requests to the tomcatBook Web application that also map to the server name and the SSL port will be passed on to Tomcat.

Testing the Installation

After making these changes, restart Tomcat and Apache. You should be able to access the secure Tomcat Web application through https://localhost/tomcatBook and the nonsecure Apache files through http://localhost.

A common problem in the setup is related to SSL configuration on Apache. Apache may fail to start or not serve up SSL content. If you face this problem, first check the new directives added to httpd.conf.

 > apache/bin/apache -t 

This should uncover any errors related to directive syntax. Next, look for Apache error messages logged in APACHE_HOME/logs/error.log. You can control logging via the LogLevel Apache directive.

 LogLevel debug 

The log levels are debug, trace, info, warn, error, and none. A debug level of none turns off all logging. The log levels are in order of priority, and setting logging to a certain level shows messages of that and higher levels. For example, the warn level shows warnings and error messages.



Pro Jakarta Tomcat 5
Pro Apache Tomcat 5/5.5 (Experts Voice in Java)
ISBN: 1590593316
EAN: 2147483647
Year: 2004
Pages: 94

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net