Pkix path building failed windows

Пройдите тест, узнайте какой профессии подходите

Одной из распространенных проблем, с которыми сталкиваются разработчики на Java при работе с библиотеками для взаимодействия с внешними сервисами

Одной из распространенных проблем, с которыми сталкиваются разработчики на Java при работе с библиотеками для взаимодействия с внешними сервисами через HTTPS, является ошибка PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target.

Данная ошибка возникает при попытке установить защищенное соединение с сервером, но не удалось найти доверенный сертификат для данного сервера в хранилище доверенных сертификатов Java.

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.net.HttpURLConnection для установки HTTPS соединения.

Освойте Python на курсе от Skypro. Вас ждут 400 часов обучения и практики (достаточно десяти часов в неделю), подготовка проектов для портфолио, индивидуальная проверка домашних заданий и помощь опытных наставников. Получится, даже если у вас нет опыта в IT.

Пример проблемы

Запрос к внешнему сервису через HTTPS, например, Twitter API:

URL url = new URL("https://api.twitter.com/1.1/statuses/user_timeline.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");

Решение проблемы

Для решения этой проблемы необходимо добавить сертификат сервера, к которому происходит подключение, в хранилище доверенных сертификатов Java. Это можно сделать с помощью утилиты keytool, которая поставляется вместе с JDK:

keytool -importcert -trustcacerts -file [PathToYourCertificate] -alias [YourAliasForCertificate] -keystore [PathToCacerts]

где:

  • [PathToYourCertificate] — путь к файлу сертификата сервера;
  • [YourAliasForCertificate] — псевдоним, который будет использоваться для этого сертификата;
  • [PathToCacerts] — путь к файлу хранилища доверенных сертификатов (обычно находится в папке lib/security внутри директории JRE).

После выполнения этой команды сертификат будет добавлен в хранилище, и приложение сможет успешно установить защищенное соединение с сервером.

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

На курсе Skypro «Python-разработчик» освоите основные инструменты программирования, получите опыт на реальных проектах и сможете стартовать в профессии уверенным новичком. Преподаватели — практикующие программисты с большим опытом, а в центре карьеры помогут составить цепляющее резюме и подготовиться к собеседованию.

Summary

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.

Accessing SSL-encrypted applications or websites (HTTPS, LDAPS, IMAPS, etc.) throws an exception, and the connection is refused.

Solution

Check the logs

The connection refused error can occur when attempting to establish a secure connection to any of the following:

  • Active Directory server, Jira User server or Crowd

  • Mail server

  • Another Atlassian application using Application Links

  • Atlassian Marketplace

  • Atlassian Migration Service

For example, the following error appears in the UI when Using the Jira Issues Macro:

1
Error rendering macro: java.io.IOException: Could not download: https://siteURL/jira/secure/IssueNavigator.jspa?view=rss&&type=12&type=4&type=3&pid=10081&resolution=1&fixfor=10348&sorter/field=issuekey&sorter/order=DESC&sorter/field=priority&sorter/order=DESC&tempMax=100&reset=true&decorator=none

While the following appears in the application log:

1
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

Check the truststore with SSLPoke

Use SSL Poke to verify connectivity

Try the Java class SSLPoke to see if your truststore contains the right certificates. This class lets you connect to an SSL service, send a byte of input, and watch the output.

  1. Download SSLPoke.class

  2. Execute the class as documented below, changing the URL and port appropriately. Take care that you are running the same Java your application (Confluence, Jira, etc.) is running with. If you used the installer you will need to use <application-home>/jre/java

    Replace atlassian.com with your domain below.

    1
    $JAVA_HOME/bin/java SSLPoke jira.atlassian.com 443

    A mail server would be of the form 
    mail.atlassian.com 465

A failed connection would produce the below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$JAVA_HOME/bin/java SSLPoke jira.example.com 443
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1351)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:156)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:925)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:860)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:728)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
at SSLPoke.main(SSLPoke.java:31)
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 15 more

⚠️ To get more details from a failed connection, use the -Djavax.net.debug=ssl parameter. For example:

1
java -Djavax.net.debug=ssl SSLPoke jira.example.com 443

A successful connection would look like this:

1
2
$JAVA_HOME/bin/java SSLPoke jira.example.com 443
Successfully connected

If -Djavax.net.ssl.trustStore is present in your JVM arguments, Java will use that truststore instead of the default (cacerts). You can verify whether the -Djavax.net.ssl.trustStore parameter is causing problems by running the SSLPoke test using the same JVM argument which will execute SSLPoke using your custom truststore. For example:

1
$JAVA_HOME/bin/java -Djavax.net.ssl.trustStore=/my/custom/truststore -Djavax.net.debug=ssl SSLPoke jira.atlassian.com 443

If this fails (confirming that the truststore doesn’t contain the appropriate certificates), the certificate will need to be imported into your defined custom truststore using the instructions in Connecting to SSL Services.

Import the certificates to the truststore

  1. Make sure you have imported the public certificate of the target instance into the truststore according to the Connecting to SSL Services instructions.

  2. Make sure any certificates have been imported into the correct truststore; you may have multiple JRE/JDKs. See How to import a public SSL certificate into a JVM for this.

  3. Check to see that the correct truststore is in use. If -Djavax.net.ssl.trustStore has been configured, it will override the location of the default truststore, which will need to be checked.

  4. If this error results while integrating with an LDAP server over LDAPS and there is more than one LDAP server, then deselect the Follow referrals option within the LDAP user directory configuration per Connecting to and LDAP Directory. Optionally, import the SSL certificates from the other LDAP servers into the Confluence truststore.

  5. Check if your Anti Virus tool has «SSL Scanning» blocking SSL/TLS. If it does, disable this feature or set exceptions for the target addresses (check the product documentation to see if this is possible.)

  6. If connecting to a mail server, such as Exchange, ensure authentication allows plain text.

  7. Verify that the target server is configured to serve SSL correctly. This can be done with the SSL Server Test tool.

  8. If all else fails, your truststore might be out of date. Upgrade Java to the latest version supported by your application.

Important

Since the truststore only gets read once when the JVM is initialized, please restart the source application service after importing the new certificate(s).

Further details on truststores

Whenever Java attempts to connect to another application over SSL (e.g.: HTTPS, IMAPS, LDAPS), it will only be able to connect to applications it can trust. The way trust is handled in Java is that you have a truststore (typically $JAVA_HOME/lib/security/cacerts). The truststore contains a list of all known Certificate Authority (CA) certificates, and Java will only trust certificates that are signed by one of those CAs or public certificates that exist within that truststore. For example, if we look at the certificate for Atlassian, we can see that the *.atlassian.com certificate has been signed by the intermediate certificates, DigiCert High Assurance EV Root CA and DigiCert High Assurance CA-3. These intermediate certificates have been signed by the rootEntrust.net Secure Server CA:

These three certificates combined are referred to as the certificate chain, and, as they are all within the Java truststore (cacerts), Java will trust any certificates signed by them (in this case, *.atlassian.com). Alternatively, if the *.atlassian.com certificate had been in the truststore, Java would also trust that site.

This problem is therefore caused by a certificate that is self-signed (a CA did not sign it) or a certificate chain that does not exist within the Java truststore. Java does not trust the certificate and fails to connect to the application.

ℹ️ For details on how to examine a website’s certificate chain, see the section, View a certificate, in Secure Website Certificate.

More on SSL Poke

Atlassian’s SSL Poke source code can be found here.

You can find forked versions of SSL Poke in the community with support for extra features like Java 11, Proxy, etc.

Good examples:

  • https://github.com/gebi/sslpoke

  • https://gist.github.com/bric3/4ac8d5184fdc80c869c70444e591d3de

Если при обновлении Дримкас Старт, Вики Микро, службы ComProxy или Кабинет-УТМ возникла ошибка «PKIX path building failed», скачайте архив и распакуйте его на рабочий стол.

Следующим шагом замените файлы в папках в зависимости от устройства:

  • Дримкас Старт и Вики Микро

Для Дримкас Старт: перейдите в папку C:\Dreamkas\Start\crystal-cash и скопируйте два файла «_.selcdn.ru.crt»и «before.bat»

Для Вики Микро : перейдите в папку C:\Viki\crystal-cash  и скопируйте два файла «_.selcdn.ru.crt»и «before.bat»

Скриншот 18-12-2024 171844.jpg

После перезапустите кассовую программу и повторите обновление. Для этого перейдите в Меню → «Настройка» → «Обновление» → «Проверить обновление»

Если на Вики Микро при обновлении сохраняется ошибка,  вручную скопируйте файл «cacerts» в %JAVA_HOME%\lib\security, (обычно C:\Program Files\Java\jre1.8.0_151\lib\security).

  • Дримкас Агент

Перейдите в папку C:\ComProxy\jre\lib\security и скопируйте с заменой файл «cacerts». Важно! Файл не должен иметь расширения.

Скриншот 18-12-2024 174037.jpg

Перезапустите Дримкас агент и повторите обновление. Для этого откройте Меню правой кнопкой мыши → «Проверить обновление»

  • Кабинет-УТМ

Перейдите в папку C:\KabinetUTM\jre\lib\security и и скопируйте с заменой файл «cacerts». Важно! Файл не должен иметь расширения.

Если папки jre нет в нужном каталоге (C:\KabinetUTM\jre) , скопируйте файл  «cacerts» с заменой в папку в %JAVA_HOME%\lib\security , (обычно C:\Program Files\Java\jre1.8.0_151\lib\security).

4343.jpg

Перезапустите утилиту и повторите обновление. Для этого откройте Меню правой кнопкой мыши → «Проверить обновление»

Problem:

The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: «PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target»

Solution:

This errors means that the identity of the database server that you are connecting to can’t be verified by the client, and it is common when a self-signed certificate is used.

Assuming you are using Microsoft’s JDBC driver, you have two options at this point: (A) either bypass the security check altogether (a quick but insecure workaround), or (B) configure the connection to trust this particular server’s certificate (more work but also more secure).

Option A:

As a quick workaround, you can bypass the security check if you trust the server. To do so, open the Properties tab for the connection and select the Driver Properties category. Set the driver property trustServerCertificate to true and connect:

Option B (simple scenario):

If you are running Microsoft Windows and the certificates have been generated by the system administrators (or the DBA) and they have pushed these certificates out to the client machines, then you can try to tell java to use the Microsoft Windows certificates. Open Tools->Tool Properties, choose General and add the following flag in the section called Java VM Properties:

-Djavax.net.ssl.trustStoreType=WINDOWS-ROOT

It should look like this:

Option B (advanced scenario):

If you are not running Microsoft Windows or you do not have the certificate in the Windows truststore, then you need to configure the database connection to trust the certificate. To do so:

1. Create a truststore containing the server certificate

  • Obtain the certificate used by the database server (in pem format)
  • Copy the default Java truststore (<Java Home>/lib/security/cacerts) to a suitable location
  • Import your server certificate to the truststore using the keytool utility (found in <Java Home>/bin)
keytool -importcert -alias mycert -file cert.pem -keystore /Users/me/mytruststore -storepass changeit

2. Configure the connection

  • trustStore=<path to your truststore>
  • trustStorePassword=<the password you chose above>
  • hostNameInCertificate=<Common Name (CN) in the server certificate>

For reference, see the following resources:

  • The SSL/TLS section in DbVisualizer User Guide: https://www.dbvis.com/docs/ug/database-connection-options/security/ssl/
  • Connection properties used by the Microsoft JDBC driver: https://learn.microsoft.com/en-us/sql/connect/jdbc/setting-the-connection-properties

While developing some application, we might sometimes come across the below error which the maven throws while building the application:

Reason: The error is due to the system firewall. The system firewall restricts the application to connect to external unsecured systems. The firewall requires a valid certificate to allow access to the external systems.

Solution: The solution is very simple. We just need to install the required certificates of the external system in our system so the firewall allows us to interact with the external system and complete our process.

We are going to perform two activities:

  1. Download the Certificate.
  2. Install the Certificate.

To Download the Certificate, Follow the Below Steps:

1. Take the particular URL from the error and copy it to a browser (In the above error the URL is https://repository.mulesoft.org/releases/).

2. Now to the left of the URL, there is a ‘lock’ icon. Click on this icon and a window will pop up. From the window, select the certificate.

3. Once we select the certificate, it will redirect to another window. From there we have to select the Details tab and from the Details click on Copy to File. After clicking again, a new window will pop up. In that window, select next.

4. After we perform all the above steps, we will be redirected to a new window where we need to select the format for the certificate. We will have to choose DER encoded binary and click on Next.

5. Now we need to choose a location where we need to save the certificate and we also need to give some name to the certificate.

6. Once a file name is given and saved, then select Next. It will direct us to another window showing the details. If all the details are correct, click on Finish. An export Success pop-up will appear.

Note: I saved the File name as repo.

So, the downloading of certificates is done. Now the next process is to install the certificate in the cacerts file of the jdk installed in our system using the command line.

Installation of the Certificate From Command Line:

Command for Installation:

For Me the Command Will Be:

Note:

1. I am using jdk1.8.0_131 so the cacerts file path for my system is «C:\Program Files\Java\jdk1.8.0_131\jre\lib\security\carcets». It may differ for you based on your system and jdk version.

2. I have given the alias name as repo and the path where I save my certificate is C:\Users\DELL\Desktop\repo.cer

To Install the Certificate, Follow the Below Steps:

1. Open Command Prompt as an Administrator and use the command for installation and press enter.

2. Once the command is executed, it will ask for confirmation. Write Yes and the certificate will be installed with a confirmation.

In the above process, we have downloaded and installed the certificate successfully in our system.

Now if we will execute the application it will not show certificate issues and will also download the required data from that particular system.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как исправить ошибку 0xc0000142 при запуске приложения в windows 10
  • После установки windows 7 на ноутбук нет интернета
  • Windows server http file server
  • Очень долго идет завершение установки windows
  • Скрин области экрана windows 11 горячие клавиши