Hardening Tomcat 9

 

SSL/TLS Configuration How-To

Table of Contents

Please check out my blog(for more technical videos. Apache Tomcat Application Sever 9 STIG - Ver 2, Rel 2 1.68 MB 22 Jan 2021. Apple iOS 12 STIG - Ver 1, Rel 2 1.28 MB 09 Mar 2019. Apple iOS 12 STIG Release Memo 282.51 KB 11 Mar 2019. Apple macOS 11 (Big Sur) STIG - Ver 1, Rel 2 1.55 MB 27 Apr 2021. Apple OS X 10.13 STIG. Center for Internet Security Benchmarks Download Form. Download Our Free Benchmark PDFs. The CIS Benchmarks are distributed free of charge in PDF format to propagate their worldwide use and adoption as user-originated, de facto standards.

  • Configuration
  • Installing a Certificate from a Certificate Authority
  • Using OCSP Certificates

Quick Start

The description below uses the variable name $CATALINA_BASE to refer the base directory against which most relative paths are resolved. If you have not configured Tomcat for multiple instances by setting a CATALINA_BASE directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, the directory into which you have installed Tomcat.

To install and configure SSL/TLS support on Tomcat, you need to followthese simple steps. For more information, read the rest of this How-To.

  1. Create a keystore file to store the server's private key andself-signed certificate by executing the following command:

    Windows:

    Unix:

    and specify a password value of 'changeit'.

  2. Uncomment the 'SSL HTTP/1.1 Connector' entry in $CATALINA_BASE/conf/server.xml and modify as described in the Configuration section below.

Introduction to SSL/TLS

Securing tomcat 9

Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer(SSL), are technologies which allow web browsers and web servers to communicateover a secured connection. This means that the data being sent is encrypted byone side, transmitted, then decrypted by the other side before processing.This is a two-way process, meaning that both the server AND the browser encryptall traffic before sending out data.

Another important aspect of the SSL/TLS protocol is Authentication. This meansthat during your initial attempt to communicate with a web server over a secureconnection, that server will present your web browser with a set ofcredentials, in the form of a 'Certificate', as proof the site is who and whatit claims to be. In certain cases, the server may also request a Certificatefrom your web browser, asking for proof that you are who you claimto be. This is known as 'Client Authentication,' although in practice this isused more for business-to-business (B2B) transactions than with individualusers. Most SSL-enabled web servers do not request Client Authentication.

SSL/TLS and Tomcat

It is important to note that configuring Tomcat to take advantage ofsecure sockets is usually only necessary when running it as a stand-aloneweb server. Details can be found in theSecurity Considerations Document.When running Tomcat primarily as a Servlet/JSP container behindanother web server, such as Apache or Microsoft IIS, it is usually necessaryto configure the primary web server to handle the SSL connections from users.Typically, this server will negotiate all SSL-related functionality, thenpass on any requests destined for the Tomcat container only after decryptingthose requests. Likewise, Tomcat will return cleartext responses, that willbe encrypted before being returned to the user's browser. In this environment,Tomcat knows that communications between the primary web server and theclient are taking place over a secure connection (because your applicationneeds to be able to ask about this), but it does not participate in theencryption or decryption itself.

Tomcat is able to use any of the the cryptographic protocols that areprovided by the underlying environment. Java itself provides cryptographiccapabilities through JCE/JCAand encrypted communications capabilities through JSSE.Any compliant cryptographic 'provider' can provide cryptographic algorithmsto Tomcat. The built-in provider (SunJCE) includes support for variousSSL/TLS versions like SSLv3, TLSv1, TLSv1.1, and so on. Check the documentationfor your version of Java for details on protocol and algorithm support.

If you use the optional tcnative library, you can usethe OpenSSL cryptographic providerthrough JCA/JCE/JSSE which may provide a different selection of cryptographicalgorithms and/or performance benefits relative to the SunJCE provider.You can also use tcnative to enable the APRconnector which uses OpenSSL for its cryptographic operations. Check thedocumentation for your version of OpenSSL for details on protocol andalgorithm support.

Certificates

In order to implement SSL, a web server must have an associated Certificatefor each external interface (IP address) that accepts secure connections.The theory behind this design is that a server should provide some kind ofreasonable assurance that its owner is who you think it is, particularlybefore receiving any sensitive information. While a broader explanation ofCertificates is beyond the scope of this document, think of a Certificate as a'digital passport' for an Internet address. It states which organisation thesite is associated with, along with some basic contact information about thesite owner or administrator.

This certificate is cryptographically signed by its owner, and istherefore extremely difficult for anyone else to forge. For the certificate towork in the visitors browsers without warnings, it needs to be signed by atrusted third party. These are called Certificate Authorities (CAs). Toobtain a signed certificate, you need to choose a CA and follow the instructionsyour chosen CA provides to obtain your certificate. A range of CAs is availableincluding some that offer certificates at no cost.

Java provides a relatively simple command-line tool, calledkeytool, which can easily create a 'self-signed' Certificate.Self-signed Certificates are simply user generated Certificates which have notbeen signed by a well-known CA and are, therefore, not really guaranteed to beauthentic at all. While self-signed certificates can be useful for some testingscenarios, they are not suitable for any form of production use.

General Tips on Running SSL

When securing a website with SSL it's important to make sure that all assetsthat the site uses are served over SSL, so that an attacker can't bypassthe security by injecting malicious content in a JavaScript file or similar. Tofurther enhance the security of your website, you should evaluate to use theHSTS header. It allows you to communicate to the browser that your site shouldalways be accessed over https.

Using name-based virtual hosts on a secured connection requires carefulconfiguration of the names specified in a single certificate or Tomcat 8.5onwards where Server Name Indication (SNI) support is available. SNI allowsmultiple certificates with different names to be associated with a single TLSconnector.

Configuration

Prepare the Certificate Keystore

Tomcat currently operates only on JKS, PKCS11 orPKCS12 format keystores. The JKS formatis Java's standard 'Java KeyStore' format, and is the format created by thekeytool command-line utility. This tool is included in the JDK.The PKCS12 format is an internet standard, and can be manipulatedvia (among other things) OpenSSL and Microsoft's Key-Manager.

Each entry in a keystore is identified by an alias string. Whilst manykeystore implementations treat aliases in a case insensitive manner, casesensitive implementations are available. The PKCS11 specification,for example, requires that aliases are case sensitive. To avoid issues relatedto the case sensitivity of aliases, it is not recommended to use aliases thatdiffer only in case.

To import an existing certificate into a JKS keystore, please read thedocumentation (in your JDK documentation package) about keytool.Note that OpenSSL often adds readable comments before the key, butkeytool does not support that. So if your certificate hascomments before the key data, remove them before importing the certificate withkeytool.

To import an existing certificate signed by your own CA into a PKCS12keystore using OpenSSL you would execute a command like:

For more advanced cases, consult theOpenSSL documentation.

To create a new JKS keystore from scratch, containing a singleself-signed Certificate, execute the following from a terminal command line:

Windows:

Unix:

(The RSA algorithm should be preferred as a secure algorithm, and thisalso ensures general compatibility with other servers and components.)

This command will create a new file, in the home directory of the userunder which you run it, named '.keystore'. To specify adifferent location or filename, add the -keystore parameter,followed by the complete pathname to your keystore file,to the keytool command shown above. You will also need toreflect this new location in the server.xml configuration file,as described later. For example:

Windows:

Unix:

After executing this command, you will first be prompted for the keystorepassword. The default password used by Tomcat is 'changeit'(all lower case), although you can specify a custom password if you like.You will also need to specify the custom password in theserver.xml configuration file, as described later.

Next, you will be prompted for general information about this Certificate,such as company, contact name, and so on. This information will be displayedto users who attempt to access a secure page in your application, so makesure that the information provided here matches what they will expect.

Finally, you will be prompted for the key password, which is thepassword specifically for this Certificate (as opposed to any otherCertificates stored in the same keystore file). The keytool promptwill tell you that pressing the ENTER key automatically uses the same passwordfor the key as the keystore. You are free to use the same password or to selecta custom one. If you select a different password to the keystore password, youwill also need to specify the custom password in the server.xmlconfiguration file.

If everything was successful, you now have a keystore file with aCertificate that can be used by your server.

Edit the Tomcat Configuration File

Tomcat can use three different implementations of SSL:

  • JSSE implementation provided as part of the Java runtime
  • JSSE implementation that uses OpenSSL
  • APR implementation, which uses the OpenSSL engine by default

The exact configuration details depend on which implementation is being used.If you configured Connector by specifying genericprotocol='HTTP/1.1' then the implementation used by Tomcat ischosen automatically. If the installation uses APR- i.e. you have installed the Tomcat native library -then it will use the JSSE OpenSSL implementation, otherwise it will use the JavaJSSE implementation.

Auto-selection of implementation can be avoided if needed. It is done by specifying a classnamein the protocol attribute of the Connector.

To define a Java (JSSE) connector, regardless of whether the APR library isloaded or not, use one of the following:

The OpenSSL JSSE implementation can also be configured explicitly if needed. If the APR libraryis installed (as for using the APR connector), using the sslImplementationName attributeallows enabling it. When using the OpenSSL JSSE implementation, the configuration can useeither the JSSE attributes orthe OpenSSL attributes (as used for the APR connector), but must not mix attributes fromboth types in the same SSLHostConfig or Connector element.

Alternatively, to specify an APR connector (the APR library must be available) use:

Hardening Tomcat

If you are using APR or JSSE OpenSSL, you have the option of configuring an alternative engine to OpenSSL.

The default value is

Also the useAprConnector attribute may be used to have Tomcat default tousing the APR connector rather than the NIO connector:

So to enable OpenSSL, make sure the SSLEngine attribute is set to something other than off.The default value is on and if you specify another value,it has to be a valid OpenSSL engine name.

SSLRandomSeed allows to specify a source of entropy. Productive system needs a reliable source of entropybut entropy may need a lot of time to be collected therefore test systems could use no blocking entropysources like '/dev/urandom' that will allow quicker starts of Tomcat.

The final step is to configure the Connector in the$CATALINA_BASE/conf/server.xml file, where$CATALINA_BASE represents the base directory for theTomcat instance. An example <Connector> elementfor an SSL connector is included in the default server.xmlfile installed with Tomcat. To configure an SSL connector that uses JSSE, youwill need to remove the comments and edit it so it looks something likethis:

Note: If tomcat-native is installed, the configuration will use JSSE with an OpenSSL implementation, which supports either this configuration or the APR configuration example given below.

Hardening Apache Tomcat 9

The APR connector uses different attributes for many SSL settings, particularly keys and certificates. An example of an APR configuration is:

The configuration options and information on which attributesare mandatory, are documented in the SSL Support section of theHTTP connector configurationreference. Make sure that you use the correct attributes for the connector youare using. The NIO and NIO2 connectors use JSSE unless the JSSE OpenSSL implementation isinstalled (in which case it supports either the JSSE or OpenSSL configuration styles),whereas the APR/native connector uses APR.

The port attribute is the TCP/IPport number on which Tomcat will listen for secure connections. You canchange this to any port number you wish (such as to the default port forhttps communications, which is 443). However, special setup(outside the scope of this document) is necessary to run Tomcat on portnumbers lower than 1024 on many operating systems.

If you change the port number here, you should also change the value specified for the redirectPort attribute on the non-SSL connector. This allows Tomcat to automatically redirect users who attempt to access a page with a security constraint specifying that SSL is required, as required by the Servlet Specification.

After completing these configuration changes, you must restart Tomcat asyou normally do, and you should be in business. You should be able to accessany web application supported by Tomcat via SSL. For example, try:

Tomcat

and you should see the usual Tomcat splash page (unless you have modifiedthe ROOT web application). If this does not work, the following sectioncontains some troubleshooting tips.

Installing a Certificate from a Certificate Authority

To obtain and install a Certificate from a Certificate Authority (like verisign.com, thawte.comor trustcenter.de), read the previous section and then follow these instructions:

Create a local Certificate Signing Request (CSR)

In order to obtain a Certificate from the Certificate Authority of your choiceyou have to create a so called Certificate Signing Request (CSR). That CSR will be usedby the Certificate Authority to create a Certificate that will identify your websiteas 'secure'. To create a CSR follow these steps:

  • Create a local self-signed Certificate (as described in the previous section): Note: In some cases you will have to enter the domain of your website (i.e. www.myside.org) in the field 'first- and lastname' in order to create a working Certificate.
  • The CSR is then created with:

Now you have a file called certreq.csr that you can submit to the Certificate Authority (look at thedocumentation of the Certificate Authority website on how to do this). In return you get a Certificate.

Importing the Certificate

Now that you have your Certificate you can import it into you local keystore.First of all you have to import a so called Chain Certificate or Root Certificate into your keystore.After that you can proceed with importing your Certificate.

  • Download a Chain Certificate from the Certificate Authority you obtained the Certificate from.
    For Verisign.com commercial certificates go to: http://www.verisign.com/support/install/intermediate.html
    For Verisign.com trial certificates go to: http://www.verisign.com/support/verisign-intermediate-ca/Trial_Secure_Server_Root/index.html
    For Trustcenter.de go to: http://www.trustcenter.de/certservices/cacerts/en/en.htm#server
    For Thawte.com go to: http://www.thawte.com/certs/trustmap.html
  • Import the Chain Certificate into your keystore
  • And finally import your new Certificate

Each Certificate Authority tends to differ slightly from the others. They mayrequire slightly different information and/or provide the certificate andassociated certificate chain in different formats. Additionally, the rules thatthe Certificate Authorities use for issuing certifcates change over time. As aresult you may find that the commands given above may need to be modified. Ifyou require assitance then help is available via theApache Tomcat usersmailing list.

Using OCSP Certificates

To use Online Certificate Status Protocol (OCSP) with Apache Tomcat, ensure you have downloaded, installed, and configured the Tomcat Native Connector.Furthermore, if you use the Windows platform, ensure you download theocsp-enabled connector.

To use OCSP, you require the following:

  • OCSP-enabled certificates
  • Tomcat with SSL APR connector
  • Configured OCSP responder

Generating OCSP-Enabled Certificates

Securing Tomcat 9

Apache Tomcat requires the OCSP-enabled certificate to have the OCSP responder location encoded in the certificate. The basic OCSP-related certificate authority settings in the openssl.cnf file could look as follows:

The settings above encode the OCSP responder address 127.0.0.1:8088 into the certificate. Note that for the following steps, you must have openssl.cnf and other configuration of your CA ready. To generate an OCSP-enabled certificate:

  • Create a private key:
  • Create a signing request (CSR):
  • Sign the CSR:
  • You may verify the certificate:

Configuring OCSP Connector

To configure the OCSP connector, first verify that you are loading the Tomcat APR library. Check the Apache Portable Runtime (APR) based Native library for Tomcatfor more information about installation of APR. A basic OCSP-enabled connector definition in the server.xml file looks as follows:

Starting OCSP Responder

Apache Tomcat will query an OCSP responder server to get the certificate status. When testing, an easy way to create an OCSP responder is by executing the following:

Do note that when using OCSP, the responder encoded in the connector certificate must be running. For further information, see OCSP documentation .

Troubleshooting

Here is a list of common problems that you may encounter when setting upSSL communications, and what to do about them.

  • When Tomcat starts up, I get an exception like 'java.io.FileNotFoundException: {some-directory}/{some-file} not found'.

    A likely explanation is that Tomcat cannot find the keystore file where it is looking. By default, Tomcat expects the keystore file to be named .keystore in the user home directory under which Tomcat is running (which may or may not be the same as yours :-). If the keystore file is anywhere else, you will need to add a keystoreFile attribute to the <Connector> element in the Tomcat configuration file.

  • When Tomcat starts up, I get an exception like 'java.io.FileNotFoundException: Keystore was tampered with, or password was incorrect'.

    Assuming that someone has not actually tampered with your keystore file, the most likely cause is that Tomcat is using a different password than the one you used when you created the keystore file. To fix this, you can either go back and recreate the keystore file, or you can add or update the keystorePass attribute on the <Connector> element in the Tomcat configuration file. REMINDER - Passwords are case sensitive!

  • When Tomcat starts up, I get an exception like 'java.net.SocketException: SSL handshake error javax.net.ssl.SSLException: No available certificate or key corresponds to the SSL cipher suites which are enabled.'

    A likely explanation is that Tomcat cannot find the alias for the server key within the specified keystore. Check that the correct keystoreFile and keyAlias are specified in the <Connector> element in the Tomcat configuration file. REMINDER - keyAlias values may be case sensitive!

  • My Java-based client aborts handshakes with exceptions such as 'java.lang.RuntimeException: Could not generate DH keypair' and 'java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 1024 (inclusive)'

    If you are using the APR/native connector or the JSSE OpenSSL implementation, it will determine the strength of ephemeral DH keys from the key size of your RSA certificate. For example a 2048 bit RSA key will result in using a 2048 bit prime for the DH keys. Unfortunately Java 6 only supports 768 bit and Java 7 only supports 1024 bit. So if your certificate has a stronger key, old Java clients might produce such handshake failures. As a mitigation you can either try to force them to use another cipher by configuring an appropriate SSLCipherSuite and activate SSLHonorCipherOrder, or embed weak DH params in your certificate file. The latter approach is not recommended because it weakens the SSL security (logjam attack).

If you are still having problems, a good source of information is theTOMCAT-USER mailing list. You can find pointers to archivesof previous messages on this list, as well as subscription and unsubscriptioninformation, athttps://tomcat.apache.org/lists.html.

Using the SSL for session tracking in your application

Securing Tomcat 9 Owasp

This is a new feature in the Servlet 3.0 specification. Because it uses the SSL session ID associated with the physical client-server connection there are some limitations. They are:

  • Tomcat must have a connector with the attribute isSecure set to true.
  • If SSL connections are managed by a proxy or a hardware accelerator they must populate the SSL request headers (see the SSLValve) so that the SSL session ID is visible to Tomcat.
  • If Tomcat terminates the SSL connection, it will not be possible to use session replication as the SSL session IDs will be different on each node.

To enable SSL session tracking you need to use a context listener to set the tracking mode for the context to be just SSL (if any other tracking mode is enabled, it will be used in preference). It might look something like:

Note: SSL session tracking is implemented for the NIO and NIO2 connectors. It is not yet implemented for the APR connector.

Miscellaneous Tips and Bits

To access the SSL session ID from the request, use:

For additional discussion on this area, please seeBugzilla.

To terminate an SSL session, use:

Note that this code is Tomcat specific due to the use of the SSLSessionManager class. This is currently only available for the NIO and NIO2 connectors, not the APR/native connector.