- Download and Install JSSE
- Downloading and Installing PureTLS
- Apache tomcat 6.0 (6.0.53) – ssl configuration how-to
- Apply the changes
- Apr-based installation
- Building tomcat with ssl support
- Credits
- Pkcs#12
- Pkcs#7
- Ssl via apache
- Step 1: prepare the files
- Step 1: prepare the ssl files
- Step 1: upload files
- Step 1: upload ssl files
- Step 2: configure the connector
- Step 2: edit ssl configuration
- Step 2: modify the keystore
- Step 3: apply changes
- Step 3: apply the changes
- Step 3: complete the ssl installation
- Step 3: edit the connector
- Step 4 – restart tomcat
- Step 4: enforce the changes
- View keystore content
- Бесплатный сертификат интеграция в apache–tomcat
Download and Install JSSE
Download the
Java Secure Socket Extensions
(JSSE) package,
version 1.0.2 or later, from
Downloading and Installing PureTLS
The easiest way to download PureTLS is by simply downloading the
prebuilt version from
Apache tomcat 6.0 (6.0.53) – ssl configuration how-to
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:
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:
Unix:
(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:
Unix:
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). You MUST
use the same password here as was used for the keystore password itself.
This is a restriction of the Tomcat implementation.
(Currently, the keytool prompt will tell you that pressing the
ENTER key does this for you automatically.)
If everything was successful, you now have a keystore file with a
Certificate that can be used by your server.
Note: your private key password and keystore password
should be the same. If they differ, you will get an error along the lines
of java.io.IOException: Cannot recover key, as documented in
Bugzilla issue 38217,
which contains further references for this issue.
Apply the changes
Save the changes and restart Tomcat either via the systemd service if there is any available, like so:
sudo systemctl restart tomcat
Or by using binaries. These will most likely be found in the following location:
/opt/tomcat/bin/shutdown.sh
/opt/tomcat/bin/startup.sh
Apr-based installation
Most Linux distributions ship packages for APR out-of-the-box. Still, additional libtcnative, libapr1-dev and libssl-dev packages are required for APR to function properly with Tomcat (if you do not have installed them yet).
Tomcat Native libraries also need to be compiled. We do not address this topic in this guide; it’s assumed you already have APR set up with Tomcat. If no APR is set up on your Apache Tomcat, check out this installation method.
Building tomcat with ssl support
If you want to build Tomcat with support for SSL, be careful of your
classpath. I usually clear the
CLASSPATH
environment variable in
order to avoid possible conflicts in jars. A common case of conflict is for XML
parsers (xerces & jaxp). Tomcat required a recent XML parser, such as
Apache Group’s
or Sun’s
You now have two options for building Tomcat with SSL support: Sun’s JSSE
and Claymore Systems’s PureTLS. The functionality that they offer is
roughly equivalent. The primary relevant difference is in licensing:
PureTLS is open source (BSD-style license)
Credits
This document was written by
and
Pkcs#12
If you have no APR enabled on Apache Tomcat, this method of SSL installation is the optimal balance between the PKCS#7 and PEM import methods. PKCS#12 is a certificate standard when all the required parts (end-entity certificate for the hostname, CA bundle, and the Private key) are stored in the same file.
Pkcs#7
The most time-efficient way to install your SSL on Tomcat from a keystore is to use a PKCS#7 formatted certificate (a file with the .p7b or .cer extension).
Ssl via apache
mod_jk supports the VirtualHost directive of Apache. This is especially
useful when using Apache mod_ssl with Tomcat.
The following configuration will easily secure your webapps via Apache SSL
support (be careful when setting these jk variables outside VirtualHost
directives):
Step 1: prepare the files
This method requires you to have each of the certificates saved in separate files:
- CA root certificate.
- CA second intermediate certificate (optional and can be omitted if your CA bundle contains only 1 intermediate certificate).
- CA intermediate certificate.
- End-entity certificate for your domain.
The order of the certificate will be as follows for the most frequently used PositiveSSL certificate:
keytool -import AAA Certificate Services
Step 1: prepare the ssl files
Feel free to jump right to the next part if you already have a PKCS#12 (.pfx/.p12) certificate. If you do not have one, convert the corresponding files first.
Step 1: upload files
First, upload the certificate, the Private key, and the CA bundle (if the Certificate Signing Request was generated elsewhere) to the server.
Step 1: upload ssl files
Upload the PKCS#7 certificate file on the server. Then, import it using the following command:
keytool -import -trustcacerts -alias tomcat -file certificate.p7b -keystore yourkeystore.jks
Where:
tomcatis the actual alias of your keystorecertificate.p7bis the actual name/path to your certificate fileyourkeystore.jksis the actual name/path to the keystore file
Make sure the certificate file has the same alias used for creating the keystore. Otherwise, the “Input not an X.509 certificate” error may take place.
After you have imported successfully, you should receive the following output:
Certificate reply was installed in keystore
Step 2: configure the connector
Next, modify the existing connector for the default port 8443 or 443. The modification should be done in the ‘Tomcat installation directory’/conf/server.xml file.
You can find the location of the directory containing the server.xml configuration file by issuing below command:
sudo find / -ipath ‘*tomcat*server.xml’
It will most likely be in /opt/tomcat/conf/server.xml or /etc/tomcat/server.xml
Step 2: edit ssl configuration
In the next step, you will need to modify the connector for the default port 8443 or 443.
The modification should be done in the ‘Tomcat installation directory’/conf/server.xml file. You can find the location of the directory containing the server.xml configuration file by issuing this command:
sudo find / -ipath ‘*tomcat*server.xml’
It will most likely be in /opt/tomcat/conf/server.xml or /etc/tomcat/server.xml
Step 2: modify the keystore
PKCS#12 file is considered as a keystore in itself. Thus, you will just need to specify the path to the PKCS#12 file in the keystoreFile directive. The process is pretty much the same as for the PKCS7 and PEM standards.
The modification should be done in the ‘Tomcat installation directory’/conf/server.xml file. You can find the location of the directory containing the server.xml configuration file by issuing the below command:
sudo find / -ipath ‘*tomcat*server.xml’
It will most likely be in /opt/tomcat/conf/server.xml or /etc/tomcat/server.xml.
Step 3: apply changes
Once done, please restart Tomcat in order to apply the changes. If you are not quite sure about the steps to reproduce, feel free to jump to this section to apply the changes and verify SSL installation.
Step 3: apply the changes
Once done, please restart Tomcat in order to apply changes. If you are not quite sure about the steps to reproduce, feel free to jump to this section to apply the changes and verify SSL installation.
Step 3: complete the ssl installation
Once done, please restart Tomcat in order to apply changes. If you are not quite sure about the steps to reproduce, skip to this section to apply the changes and verify SSL installation.
Step 3: edit the connector
In the next step, you will need to modify the connector for the default port 8443 or 443.
The modification should be done in the ‘Tomcat installation directory’/conf/server.xml file. You can find the location of the directory containing the server.xml configuration file by issuing the below command:
sudo find / -ipath ‘*tomcat*server.xml’
Most likely, it will be in /opt/tomcat/conf/server.xml or /etc/tomcat/server.xml
Step 4 – restart tomcat
Use your init script (if have) to restart tomcat service, In my case i use shell scripts (startup.sh and shutdown.sh) for stopping and starting tomcat.
./bin/shutdown.sh ./bin/startup.sh
Step 4: enforce the changes
Once done, please restart Tomcat in order to apply changes.If you are not quite sure about the steps to reproduce, you can go to this section to apply the changes and verify SSL installation.
View keystore content
Use this command to check the imported decoded certificates in the keystore. For each correctly-imported certificate, you will see its details in a keystore entry. The Private key entry is displayed in the list as well:
keytool -list -keystore yourkeystore.jks -v
The output should be similar to the below listing:
$ keytool -list -keystore yourkeystore.jks -v
Бесплатный сертификат интеграция в apache–tomcat
Доброго времени суток, дорогие друзья. У меня возникла необходимость настроить https на сервере, который используется в онлайн-игре. Для этого мне понадобится бесплатная регистрация на StartSSL и немного времени. Инструкции на самом сайте StartSSL довольно туманные. Эта публикация призвана пролить свет на детали.
Первым делом проходим простую регистрацию на StartSSL, её результатом будет созданный приватный сертификат. Во время регистрации указываем свои домашние данные. Все данные желательно заполнять латиницей. Сертификат следует обязательно сохранить в безопасном месте. Для этого в вашем любимом браузере идем в настройки, где хранятся сертификаты и экспортируем в файл ваш сертификат.
Второй шаг подразумевает под собой валидацию домена, где будет использован сертификат https. Для этого в панели управления на сайте StartSSL переходим в раздел Validations Wizard и выбираем пункт Domain Name Validation. Выбираем на какой почтовый адрес отправить проверочный код, отправляем, проверяем почту, подтверждаем код — домен подтвержден.
Третий большой шаг. Генерация сертификата. Для этого нам понадобится создать файл-запрос для получения серфтификата и хранилище, которое будет использовано для авторизации https. Инициализируем приватный ключ и создадим хранилище, где PASSWORD — одинаковый пароль, который мы будем использовать во всех командах ниже и DOMAIN_NAME — просто имя вашего домена, без .ru, .org и т.д. Выполняем в терминале:
keytool -genkey -keysize 2048 -keyalg RSA -sigalg SHA1withRSA -alias webserver -keystore ks2 -keypass PASSWORD -storepass PASSWORD -dname "CN=DOMAIN_NAME.org, OU=Unknown, O=DOMAIN_NAME, L=Slovakia, ST=Unknown, C=SK"Теперь мы можем создать файл-запрос, он же Certificate Request (CSR), результат появится в файле DOMAIN_NAME.csr:
keytool -certreq -alias webserver -file DOMAIN_NAME.csr -keystore ks2Идем в раздел Certificates Wizard и там выбираем Web Server SSL/TSL Certificate. Нажимаем Skip. Открываем наш файл DOMAIN_NAME.csr и копируем его содержимое в буфер обмена. Возвращаемся на сайт StartSSL и в появившееся поле вставляем из буфера наш Certificate Request (CSR), который будет в формате Base64. Отправляем. StartSSL предлагает к основному домену добавить еще и поддомен. Можно указать стандартное www или то, что Вам хочется. В течении 15-180 минут будет создан сертификат
Четвертый шаг. Вы дождались письма от StartSSL о том что Ваш серфтикат готов. Идем к ним на сайт и получаем его в Tool Box — Retrieve Certificate, выбираем Ваш домен и появившийся текст в кодировке Base64 копируем в буфер обмена. Создаем на диске файл ssl.crt и вставляем в него наш сертификат. Теперь у нас есть все для финального шага. Качаем корневой сертификат StartSSL:
www.startssl.com/certs/ca.crt
www.startssl.com/certs/sub.class1.server.ca.crt
Импортируем эти сертификаты в наше хранилище:
keytool -import -alias startsslca -file ca.cer -keystore ks2 -trustcacerts
keytool -import -alias startsslca1 -file sub.class1.server.ca.crt -keystore ks2 -trustcacertsИмпортируем наш сертификат из файла ssl.crt:
keytool -import -alias webserver -file ssl.crt -keystore ks2Пятый шаг. Последний. Пропишем в файле server.xml коннектор:
<Connector port="8443" maxThreads="200" scheme="https" secure="true" SSLEnabled="true" keystoreFile=“pathtokeystoreks2" keystorePass="PASSWORD" clientAuth="false" sslProtocol="TLS"/>И установим редирект:
<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />Готово.
P.S. Прошу прощения за допущенные мною орфографические ошибки, а так же за возможно сумбурный гайд. Автор самоучка и, возможно, некоторые вещи называет не своими именами. Всем спасибо за внимание. Надеюсь, публикация будет кому-то полезной.
P.S.S. Подразумевается, что все файлы сохраняются и создаются в одной папке, в этой же папке выполняются и команды в терминале.
