## SSL/TLS Configuration How-To

### Table of Contents

- Quick Start
- Introduction to SSL/TLS
- SSL/TLS and Tomcat
- Certificates
- General Tips on Running SSL
- Configuration
  1. Prepare the Certificate Keystore
  2. Edit the Tomcat Configuration File
- Installing a Certificate from a Certificate Authority
  1. Create a local Certificate Signing Request (CSR)
  2. Importing the Certificate
- Using OCSP Certificates
  1. Generating OCSP-Enabled Certificates
- Troubleshooting
- Using the SSL for session tracking in your application
- Miscellaneous Tips and Bits

### 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 follow these simple steps. For more information, read the rest of this How-To.

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

   Windows:

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

   Unix:

       $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA

   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

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

Another important aspect of the SSL/TLS protocol is Authentication. This means that during your initial attempt to communicate with a web server over a secure connection, that server will present your web browser with a set of credentials, in the form of a "Certificate", as proof the site is who and what it claims to be. In certain cases, the server may also request a Certificate from your web browser, asking for proof that you are who you claim to be. This is known as "Client Authentication," although in practice this is used more for business-to-business (B2B) transactions than with individual users. 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 of secure sockets is usually only necessary when running it as a stand-alone web server. Details can be found in the Security Considerations Document. When running Tomcat primarily as a Servlet/JSP container behind another web server, such as Apache or Microsoft IIS, it is usually necessary to configure the primary web server to handle the SSL connections from users. Typically, this server will negotiate all SSL-related functionality, then pass on any requests destined for the Tomcat container only after decrypting those requests. Likewise, Tomcat will return cleartext responses, that will be encrypted before being returned to the user's browser. In this environment, Tomcat knows that communications between the primary web server and the client are taking place over a secure connection (because your application needs to be able to ask about this), but it does not participate in the encryption or decryption itself.

Tomcat is able to use any of the cryptographic protocols that are provided by the underlying environment. Java itself provides cryptographic capabilities through JCE/JCA and encrypted communications capabilities through JSSE. Any compliant cryptographic "provider" can provide cryptographic algorithms to Tomcat. The built-in provider (SunJCE) includes support for various SSL/TLS versions like SSLv3, TLSv1, TLSv1.1, and so on. Check the documentation for your version of Java for details on protocol and algorithm support.

If you use the optional `tcnative` library, you can use the OpenSSL cryptographic provider through JCA/JCE/JSSE which may provide a different selection of cryptographic algorithms and/or performance benefits relative to the SunJCE provider. Check the documentation for your version of OpenSSL for details on protocol and algorithm support.

### Certificates

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

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

Java provides a relatively simple command-line tool, called `keytool`, which can easily create a "self-signed" Certificate. Self-signed Certificates are simply user generated Certificates which have not been signed by a well-known CA and are, therefore, not really guaranteed to be authentic at all. While self-signed certificates can be useful for some testing scenarios, 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 assets that the site uses are served over SSL, so that an attacker can't bypass the security by injecting malicious content in a JavaScript file or similar. To further enhance the security of your website, you should evaluate to use the HSTS header. It allows you to communicate to the browser that your site should always be accessed over https.

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

### Configuration

#### Prepare the Certificate Keystore

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

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

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

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

    openssl pkcs12 -export -in mycert.crt -inkey mykey.key
                           -out mycert.p12 -name tomcat -CAfile myCA.crt
                           -caname root -chain

For more advanced cases, consult the OpenSSL documentation.

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

Windows:

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

Unix:

    $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA

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

This command will create a new file, in the home directory of the user under which you run it, named "`.keystore`". To specify a different 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 to reflect this new location in the `server.xml` configuration file, as described later. For example:

Windows:

    "%JAVA_HOME%\bin\keytool" -genkey -alias tomcat -keyalg RSA
      -keystore \path\to\my\keystore

Unix:

    $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA
      -keystore /path/to/my/keystore

After executing this command, you will first be prompted for the keystore password. 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 the `server.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 displayed to users who attempt to access a secure page in your application, so make sure that the information provided here matches what they will expect.

Finally, you will be prompted for the key password, which is the password specifically for this Certificate (as opposed to any other Certificates stored in the same keystore file). The `keytool` prompt will tell you that pressing the ENTER key automatically uses the same password for the key as the keystore. You are free to use the same password or to select a custom one. If you select a different password to the keystore password, you will also need to specify the custom password in the `server.xml` configuration file.

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

#### Edit the Tomcat Configuration File

Tomcat can use two different implementations of SSL:

- JSSE implementation provided as part of the Java runtime
- JSSE implementation that uses OpenSSL

The exact configuration details depend on which implementation is being used. If you configured Connector by specifying generic `protocol="HTTP/1.1"` then the implementation used by Tomcat is chosen 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 Java JSSE implementation.

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

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

    <!-- Define an HTTP/1.1 Connector on port 8443, JSSE NIO implementation -->
    <Connector protocol="org.apache.coyote.http11.Http11NioProtocol"
               sslImplementationName="org.apache.tomcat.util.net.jsse.JSSEImplementation"
               port="8443" .../>

    <!-- Define an HTTP/1.1 Connector on port 8443, JSSE NIO2 implementation -->
    <Connector protocol="org.apache.coyote.http11.Http11Nio2Protocol"
               sslImplementationName="org.apache.tomcat.util.net.jsse.JSSEImplementation"
               port="8443" .../>

The OpenSSL JSSE implementation can also be configured explicitly if needed. If the APR library is installed, using the sslImplementationName attribute allows enabling it. When using the OpenSSL JSSE implementation, the configuration can use either the JSSE attributes or the OpenSSL attributes, but must not mix attributes from both types in the same SSLHostConfig or Connector element.

    <!-- Define an HTTP/1.1 Connector on port 8443, JSSE NIO implementation and OpenSSL -->
    <Connector protocol="org.apache.coyote.http11.Http11NioProtocol" port="8443"
               sslImplementationName="org.apache.tomcat.util.net.openssl.OpenSSLImplementation"
               .../>

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

    <Listener className="org.apache.catalina.core.AprLifecycleListener"
              SSLEngine="someengine" SSLRandomSeed="somedevice" />

The default value is

    <Listener className="org.apache.catalina.core.AprLifecycleListener"
              SSLEngine="on" SSLRandomSeed="builtin" />

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 entropy but entropy may need a lot of time to be collected therefore test systems could use no blocking entropy sources 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 the Tomcat instance. An example `<Connector>` element for an SSL connector is included in the default `server.xml` file installed with Tomcat. To configure an SSL connector that uses JSSE with the JSSE configuration style, you will need to remove the comments and edit it so it looks something like this:

    <!-- Define an SSL Coyote HTTP/1.1 Connector on port 8443 -->
    <Connector
        protocol="org.apache.coyote.http11.Http11NioProtocol"
        port="8443"
        maxThreads="150"
        SSLEnabled="true"
        maxParameterCount="1000"
        >
      <SSLHostConfig>
        <Certificate
          certificateKeystoreFile="${user.home}/.keystore"
          certificateKeystorePassword="changeit"
          type="RSA"
          />
        </SSLHostConfig>
    </Connector>

Note: If tomcat-native is installed, the configuration will use JSSE with an OpenSSL implementation.

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

    <!-- Define an SSL Coyote HTTP/1.1 Connector on port 8443 -->
    <Connector
        protocol="org.apache.coyote.http11.Http11NioProtocol"
        port="8443"
        maxThreads="150"
        SSLEnabled="true"
        maxParameterCount="1000"
        >
      <SSLHostConfig>
        <Certificate
            certificateKeyFile="conf/localhost-rsa-key.pem"
            certificateFile="conf/localhost-rsa-cert.pem"
            certificateChainFile="conf/localhost-rsa-chain.pem"
            type="RSA"
            />
      </SSLHostConfig>
    </Connector>

The configuration options and information on which attributes are mandatory, are documented in the SSL Support section of the HTTP connector configuration reference. Tomcat supports either configuration style (JSSE or OpenSSL) with all TLS connectors.

The `port` attribute is the TCP/IP port number on which Tomcat will listen for secure connections. You can change this to any port number you wish (such as to the default port for `https` communications, which is 443). However, special setup (outside the scope of this document) is necessary to run Tomcat on port numbers 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 as you normally do, and you should be in business. You should be able to access any web application supported by Tomcat via SSL. For example, try:

    https://localhost:8443/

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

### Installing a Certificate from a Certificate Authority

To obtain and install a Certificate from a Certificate Authority (like verisign.com, thawte.com or 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 choice you have to create a so called Certificate Signing Request (CSR). That CSR will be used by the Certificate Authority to create a Certificate that will identify your website as "secure". To create a CSR follow these steps:

- Create a local self-signed Certificate (as described in the previous section):

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

  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:

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

Now you have a file called `certreq.csr` that you can submit to the Certificate Authority (look at the documentation 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

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

- And finally import your new Certificate

      keytool -import -alias tomcat -keystore <your_keystore_filename>
          -file <your_certificate_filename>

Each Certificate Authority tends to differ slightly from the others. They may require slightly different information and/or provide the certificate and associated certificate chain in different formats. Additionally, the rules that the Certificate Authorities use for issuing certificates change over time. As a result you may find that the commands given above may need to be modified. If you require assistance then help is available via the Apache Tomcat users mailing list.

### Using OCSP Certificates

Tomcat supports the Online Certificate Status Protocol (OCSP) to verify the status of client provided certificates for a sub-set of connector configurations.

To use OCSP, you require the following:

- OCSP-enabled certificates
- Tomcat with an OCSP enabled connector
- Configured OCSP responder

OCSP is currently implemented for the following connector configurations:

- NIO or NIO2 HTTP connector with the `org.apache.tomcat.util.net.openssl.OpenSSLImplementation`, a Tomcat Native build where OCSP is enabled and using the OpenSSL style configuration.
- NIO or NIO2 HTTP connector with the `org.apache.tomcat.util.net.openssl.panama.OpenSSLImplementation`, and using the OpenSSL style configuration. This uses FFM so Java 22 or later is also required.

OCSP is not supported if the `org.apache.tomcat.util.net.jsse.JSSEImplementation` is used or if the JSSE configuraton style is used.

#### Generating OCSP-Enabled Certificates

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:

    #... omitted for brevity

    [x509]
    x509_extensions = v3_issued

    [v3_issued]
    subjectKeyIdentifier=hash
    authorityKeyIdentifier=keyid,issuer
    # The address of your responder
    authorityInfoAccess = OCSP;URI:http://127.0.0.1:8088
    keyUsage = critical,digitalSignature,nonRepudiation,keyEncipherment,dataEncipherment,keyAgreement,keyCertSign,cRLSign,encipherOnly,decipherOnly
    basicConstraints=critical,CA:FALSE
    nsComment="Testing OCSP Certificate"

    #... omitted for brevity

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:

      openssl genrsa -aes256 -out ocsp-cert.key 4096

- Create a signing request (CSR):

      openssl req -config openssl.cnf -new -sha256 \
        -key ocsp-cert.key -out ocsp-cert.csr

- Sign the CSR:

      openssl ca -openssl.cnf -extensions ocsp -days 375 -notext \
        -md sha256 -in ocsp-cert.csr -out ocsp-cert.crt

- You may verify the certificate:

      openssl x509 -noout -text -in ocsp-cert.crt

### Troubleshooting

Additional information may be obtained about TLS handshake failures by configuring the dedicated TLS handshake logger to log debug level messages by adding the following to `$CATALINA_BASE/conf/logging.properties`:

    org.apache.tomcat.util.net.NioEndpoint.handshake.level=FINE

or

    org.apache.tomcat.util.net.Nio2Endpoint.handshake.level=FINE

depending on the Connector being used.

Here is a list of common problems that you may encounter when setting up SSL 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 `certificateKeystoreFile` attribute to the `<Certificate>` 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 `certificateKeystoreFile` and `certificateKeyAlias` are specified in the `<Certificate>` element in the Tomcat configuration file. REMINDER - `keyAlias` values may be case sensitive!

If you are still having problems, a good source of information is the TOMCAT-USER mailing list. You can find pointers to archives of previous messages on this list, as well as subscription and unsubscription information, at https://tomcat.apache.org/lists.html.

### Using the SSL for session tracking in your application

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:

    package org.apache.tomcat.example;

    import java.util.EnumSet;

    import jakarta.servlet.ServletContext;
    import jakarta.servlet.ServletContextEvent;
    import jakarta.servlet.ServletContextListener;
    import jakarta.servlet.SessionTrackingMode;

    public class SessionTrackingModeListener implements ServletContextListener {

        @Override
        public void contextDestroyed(ServletContextEvent event) {
            // Do nothing
        }

        @Override
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            EnumSet<SessionTrackingMode> modes =
                EnumSet.of(SessionTrackingMode.SSL);

            context.setSessionTrackingModes(modes);
        }

    }

### Miscellaneous Tips and Bits

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

    String sslID = (String)request.getAttribute("jakarta.servlet.request.ssl_session_id");

For additional discussion on this area, please see Bugzilla.

To terminate an SSL session, use:

    // Standard HTTP session invalidation
    session.invalidate();

    // Invalidate the SSL Session
    org.apache.tomcat.util.net.SSLSessionManager mgr =
        (org.apache.tomcat.util.net.SSLSessionManager)
        request.getAttribute("jakarta.servlet.request.ssl_session_mgr");
    mgr.invalidateSession();

    // Close the connection since the SSL session will be active until the connection
    // is closed
    response.setHeader("Connection", "close");