Java не открывает сертификат

How to import a public SSL certificate into a JVM

Platform notice: Server and Data Center only. This article only applies to Atlassian products on the server and data center platforms .

The content on this page relates to platforms which are not supported. Consequently, Atlassian Support cannot guarantee providing any support for it. Please be aware that this material is provided for your information only and using it is done so at your own risk.

Problem

When connecting two servers via HTTPS, the public SSL certificate from each server must be added to the other server’s JVM truststore.

Resolution

There are 2 ways to import a public SSL certificate into a JVM:

Using Portecle

This is a third-party application and not supported by Atlassian.

If running on a Linux/UNIX server, X11 will need to be forwarded when connecting to the server (so you can use the GUI), as below:

  • Select the Examine menu and then click Examine SSL/TLS Connection:
  • Enter the SSL Host and Port of the target system:
  • Wait for it to load, then select the public certificate and click on PEM:
  • Export the certificate and save it.
  • Go back to the main screen and select the Open an existing keystore from disk option, select the truststore file (for example $JAVA_HOME/lib/security/cacerts ) then enter the password (the default is changeit ).
  • Select the Import a trusted certificate into the loaded keystore button:
  • Select the certificate that was saved in step 6 and confirm that you trust it, giving it an appropriate alias (e.g.: confluence).
    1. You may hit this error:
    2. If so, hit OK, and then accept the certificate as trusted.
    Читайте также:  Тег OPTION, атрибут selected
  • Save the keystore to disk:
  • Restart your application.
  • Test that you can connect to the host.
  • Command Line Installation

    1. Fetch the certificate, replacing google.com with the FQDN of the server your application is attempting to connect to:
    openssl s_client -connect google.com:443 -servername google.com < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' >public.crt
    openssl s_client -connect google.com:443 -servername google.com < NUL | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' >public.crt

    If you are under a redirection domain page, you must specify always -servername in order to ensure we are loading the correct domain, otherwise, openssl takes the first SSL cert it receives, when it should be the second cert that belongs to your domain.

    The command above will only be executed if you have Sed for Windows as well as OpenSSL installed on your environment. If you don’t have Sed or OpenSSL or you don’t want to install it, use the instructions below as an alternative. Issue the following command:

    openssl s_client -connect google.com:443 -servername google.com

    Save the output to a file called public.crt. Edit the the public.crt file so it contains only what is between the BEGIN CERTIFCATE and END CERTIFICATE lines. This is how your file should look like after you edited it:

    -----BEGIN CERTIFICATE----- < Certificate content as fetched by the command line. Don't change this content, only remove what is before and after the BEGIN CERTIFICATE and END CERTIFICATE. That's what your Sed command is doing for you :-) >-----END CERTIFICATE-----

    keytool for fetching a certificate does not support Server Name Indication (SNI). If you need to specify a server name to get the correct certificate, please use openssl instead.

    $JAVA_HOME/bin/keytool -printcert -sslserver google.com:443 -rfc >> public.crt
    %JAVA_HOME%/bin/keytool -printcert -sslserver google.com:443 -rfc >> public.crt
    /bin/keytool -importcert -alias -keystore /jre/lib/security/cacerts -file public.crt
    /bin/keytool -importcert -alias -keystore /lib/security/cacerts -file public.crt

    Then enter the password if prompted (the default is changeit ).

    Note: If the cacerts file already has a certificate for the same server name, the import may fail with the following error:

    keytool error: java.lang.Exception: Certificate not imported, alias already exist

    If this happens, you first need to remove the existing certificate from cacerts before re-trying to import the new certificate.
    To remove the existing certificate, you can use the command below:

    /bin/keytool -delete -alias -keystore /jre/lib/security/cacerts
    /bin/keytool -delete -alias -keystore /lib/security/cacerts

    Alternative TrustStore Locations

    Java will normally use a system-wide truststore:

    • Java 8: $JAVA_HOME/jre/lib/security/cacerts
    • Java 11: $JAVA_HOME/lib/security/cacerts

    However it is possible to use a different truststore by specifying a parameter, — Djavax.net.ssl.trustStore=/path/to/truststore , where ‘ /path/to/truststore ‘ is the absolute file path of the alternative truststore. Information on how to configure JIRA startup variables can be found here.

    However, setting this is not recommended because if Java is told to use a custom truststore (eg. containing a self-signed certificate), then Java will not have access to the root certificates of signing authorities found in $JAVA_HOME/jre/lib/security/cacerts , and accessing most CA-signed SSL sites will fail. It is better to add new certificates (eg. self-signed) to the system-wide truststore (as above).

    Debugging

    Problems are typically one of two forms:

    • The certificate was installed into the incorrect truststore.
    • The truststore does not contain the certificate of the SSL service you’re connecting to.
    Description When connecting two servers via HTTPS, the public SSL certificate from each server must be loaded on to the other server.
    Product Jira, Confluence, Bamboo, Bitbucket

    Источник

    Устранение ошибок хранилища сертификатов в JVM

    В этом руководстве мы рассмотрим распространенные проблемы, с которыми мы можем столкнуться при отправке SSL-запросов.

    2. Ошибка хранилища сертификатов​

    Всякий раз, когда приложение Java открывает SSL-соединение с удаленной стороной, оно должно проверить, заслуживает ли сервер доверия или нет, путем проверки своих сертификатов . Если корневой сертификат не содержится в файле хранилища сертификатов, возникает исключение безопасности:

     Untrusted: Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 

    Мы должны помнить, что расположение этого файла по умолчанию — $JAVA_HOME/lib/security/cacerts.

    3. Самоподписанные сертификаты​

    В непроизводственных средах часто встречаются сертификаты, подписанные ненадежными эмитентами, которые называются самозаверяющими сертификатами .

    Мы можем найти несколько примеров ненадежных сертификатов по адресу https://wrong.host.badssl.com/ или https://self-signed.badssl.com/. Открытие обоих URL-адресов в любом браузере приведет к исключению безопасности. Мы можем проверить их и увидеть различия в сертификатах.

    После открытия https://self-signed.badssl.com/ мы видим, что браузер возвращает ошибку «Cert Authority Invalid» , так как сертификат был выдан центром, неизвестным браузеру:

    С другой стороны, открытие https://wrong.host.badssl.com/ приводит к ошибке «Cert Common Name Invalid» , другой тип ошибки, указывающий на то, что сертификат был выпущен для другого имени хоста, чем предоставленное:

    То же самое произойдет с приложением, работающим внутри JDK/JRE. Эти исключения безопасности не позволят нам открыть SSL-соединение с этими ненадежными сторонами.

    4. Управление хранилищем сертификатов, чтобы доверять нашим сертификатам​

    К счастью, JDK/JRE предоставляет инструмент для взаимодействия с хранилищем сертификатов для управления его содержимым . Этот инструмент называется Keytool и находится в $JAVA_HOME/bin/keytool .

    Важное примечание : для взаимодействия с keytool требуется пароль. Пароль по умолчанию — «changeit».

    4.1. Список сертификатов​

    Чтобы получить список всех сертификатов, зарегистрированных в хранилище сертификатов JVM, нам нужно выполнить следующую команду:

     keytool -list -keystore $JAVA_HOME/lib/security/cacerts 

    Это вернет список со всеми записями, например:

     Your keystore contains 227 entries  Alias name: accvraiz1 Creation date: Apr 14, 2021  Entry type: trustedCertEntry  Owner: C=ES, O=ACCV, OU=PKIACCV, CN=ACCVRAIZ1 Issuer: C=ES, O=ACCV, OU=PKIACCV, CN=ACCVRAIZ1  .... 

    4.2. Добавить сертификаты​

    Чтобы вручную добавить сертификат в этот список, чтобы он проверялся всякий раз, когда мы выдаем запрос SSL, нам нужно выполнить следующую команду:

     keytool -import -trustcacerts -file [certificate-file] -alias [alias] -keystore $JAVA_HOME/lib/security/cacerts 
     keytool -import -alias ss-badssl.com -keystore $JAVA_HOME/lib/security/cacerts -file ss-badssl.pem 

    4.3. Пользовательский путь к хранилищу сертификатов​

    Если ничего из вышеперечисленного не работает, возможно, наше Java-приложение использует другое хранилище сертификатов. Чтобы убедиться в этом, мы можем указать хранилище сертификатов, которое будет использоваться всякий раз, когда мы запускаем ваше Java-приложение:

     java -Djavax.net.ssl.trustStore=CustomTrustStorePath ... 

    Таким образом, мы удостоверимся, что он использует хранилище сертификатов, которое мы ранее редактировали. Если это не поможет, мы также можем отладить соединения SSL, применив параметр VM:

    5. Скрипт автоматизации​

    В заключение мы можем создать простой, но удобный скрипт для автоматизации всего процесса:

     #!/bin/sh   # cacerts.sh  /usr/bin/openssl s_client -showcerts -connect $1:443 /dev/null 2>/dev/null | /usr/bin/openssl x509 -outform PEM > /tmp/$1.pem  $JAVA_HOME/bin/keytool -import -trustcacerts -file /tmp/$1.pem -alias $1 -keystore $JAVA_HOME/lib/security/cacerts  rm /tmp/$1.pem 

    В сценарии мы видим, что первая часть открывает SSL-соединение с DNS, переданным в качестве первого аргумента, и запрашивает его для отображения сертификатов. После этого информация о сертификате передается через openssl для обработки и сохранения в виде файла PEM.

    Наконец, этот файл PEM мы будем использовать, указав keytool импортировать сертификат в файл cacerts с DNS в качестве псевдонима.

    Например, мы можем попробовать добавить сертификат для https://self-signed.badssl.com:

     cacerts.sh self-signed.badssl.com 

    И после его запуска мы можем проверить, что наш файл cacerts теперь содержит сертификат:

     keytool -list -keystore $JAVA_HOME/lib/security/cacerts 

    Наконец, мы увидим новый сертификат:

     #5: ObjectId: 2.5.29.32 Criticality=false  CertificatePolicies [   [CertificatePolicyId: [2.5.29.32.0]   Alias name: self-signed.badssl.com Creation date: Oct 22, 2021  Entry type: trustedCertEntry  Owner: CN=*.badssl.com, O=BadSSL, L=San Francisco, ST=California, C=US Issuer: CN=*.badssl.com, O=BadSSL, L=San Francisco, ST=California, C=US Serial number: c9c0f0107cc53eb0 Valid from: Mon Oct 11 22:03:54 CEST 2021 until: Wed Oct 11 22:03:54 CEST 2023  Certificate fingerprints:  .... 

    6. Добавление сертификата вручную​

    Мы также можем использовать наш браузер для извлечения сертификата и добавления его через keytool , если по какой-либо причине мы не хотим использовать openssl .

    В браузерах на основе Chromium мы открываем веб-сайт, например https://self-signed.badssl.com/, и открываем инструменты разработчика (F12 для Windows и Linux). Затем давайте перейдем на вкладку «Безопасность» и, наконец, на «Просмотр сертификата». Появится информация о сертификате:

    ./09d508558db55a3d19e781e234a29569.png

    Перейдем во вкладку «Подробности», нажмем на кнопку «Экспорт» и сохраним. Это наш файл PEM:

    ./870391e5651c018b601626062df086d8.png

    Наконец, мы импортируем его с помощью keytool:

     $JAVA_HOME/bin/keytool -import -trustcacerts -file CERTIFICATEFILE -alias ALIAS -keystore $JAVA_HOME/lib/security/cacerts 

    7. Заключение​

    В этой статье мы увидели, как добавить самоподписанный сертификат в наше хранилище сертификатов JDK/JRE. Теперь наши Java-приложения могут доверять стороне сервера всякий раз, когда они открывают соединение SSL с сайтами, содержащими эти сертификаты.

    Источник

    INFORMATICS

    2.png6.png8.png3.png1.png2.png 9.png

    Ошибка Java «Не удалось проверить сертификат. Приложение не будет выполнена»

    Звезда не активнаЗвезда не активнаЗвезда не активнаЗвезда не активнаЗвезда не активна

    Ошибка Java » Не удалось проверить сертификат . Приложение не будет выполнена «

    Как исправить ошибку . Откройте Java Console в команде командной строки :

    Trusted.certs удалите папку C: \ Users \ Имя пользователя \ AppData \ Local \ Sun \ Sun \ Java \ Deployment \

    На вкладке Java расширенный :

    отключить » Включить проверку онлайн сертификат «

    включить » Разрешить Пользователь разрешений грантовых к содержимому из untrasted власти «

    Источник

    Оцените статью