Sslhandshakefailederror как исправить

I try to access a Server with QNetworkAccessManager and a QNetworkRequest and I receive the error: QNetworkReply::SslHandshakeFailedError on Android device.

I have already compiled the OpenSSL Library for android and added the library to my Qt project [ https://github.com/ekke/android-openssl-qt ]

I am using Qt 5.12, Andoird NDK 19, Android API 26

I added the following ssl configuration:

sslConf = QSslConfiguration::defaultConfiguration();
sslConf.setProtocol(QSsl::AnyProtocol);
sslConf.setPeerVerifyMode(QSslSocket::VerifyNone);
sslConf.setCaCertificates({});
QSslConfiguration::setDefaultConfiguration(sslConf);
netAccessManager.setStrictTransportSecurityEnabled(false);

Try to get the response:

QNetworkRequest nr;
nr.setSslConfiguration(this->sslConf);
nr.setUrl(QUrl("https://myserver.com/services/abc"));

//HTTP Basic authentication header value: base64(username:password)
QString concatenated = username + ":" + pw;
QByteArray data = concatenated.toLocal8Bit().toBase64();
QString headerData = "Basic " + data;
nr.setRawHeader("Authorization", headerData.toLocal8Bit());

QNetworkReply *reply = netAccessManager.get(nr);
reply->ignoreSslErrors();

QObject::connect(reply, SIGNAL(sslErrors(const QList<QSslError>)),
                 this, SLOT(sslError(const QList<QSslError>)));

The code works fine on Linux, and on Linux the error: QNetworkReply::SslHandshakeFailedError comes up.

SSL/TLS Handshake Failed error occurs when the client or server fails to establish a secure connection.

Has your SSL handshake failed? For someone who isn’t quite adept in technology, the term ‘SSL handshake’ might seem cryptic or out of the context. If you are in that zone and know nothing about why this error is popping up on your system, then read until the end.

clickssl promotional blog post banner

In this article, we shall not only discuss what an SSL handshake is, but we shall also delve deeper into why this error shows up and what you can do to fix it.

What is an SSL/TLS handshake?

The SSL handshake involves algorithm agreement, certificate exchange, and the exchange of keys using the shared algorithm. So, the ‘SSL handshake’ is the name given to a securely devised process that helps encrypt client-server communication through cryptographic keys. These keys are exchanged between the server and the client using one out of the two shared algorithms that both the server and the client mutually agreed upon. So, if any glitch occurs during this process, then the ‘SSL handshake failed’ error shows up.

Why does the ‘SSL/TLS handshake failed’ error occur?

An SSL handshake error, also known as error 525 occurs when the two endpoints (server and client) are unable to establish a secure connection. This can happen due to several issues, which might be on the server side or the client side. If you are experiencing this error, there is not much to worry about and no matter what’s causing it, we’ll help you fix it in no time. Let us now discuss some ways in which you can fix the SSL handshake error.

How to Fix the “SSL/TLS Handshake Failed” Error?

#1. Check your system’s time and date

Before you try any other fix for your SSL handshake error, we strongly recommend that you try correcting your system’s date and time. Silly as it may seem, this works for most people experiencing this sort of error. So, don’t undermine the power of your system’s date and time setting, which might be wrong due to many reasons.

It could be wrong due to pure neglect, a software glitch caused by malware, or simply because you are using a server located in another time zone through a VPN. If you are using a VPN, then it is recommended that you configure the date and time according to the server’s time zone. This refers to the date and time of the location in which the server is located, and not your physical location.

Windows user can reset the date and time in the following manner:

  • Click on the ‘Windows’ button.
  • Type ‘Date and Time Settings’ and choose the relevant option.
  • If you wish to set the time automatically, toggle the ‘set time automatically’ button.
  • If you are using a VPN or wish to set the time manually for any other reason, click on the ‘Set the date and time manually’ option.

date and time setup in windows

On Mac, the same can be done by navigating to ‘Menu’ and then to ‘System Preferences’. You will find similar settings for all other Operating Systems.

#2. Update your Web Browser

At all times, you must keep your Operating System and applications up to date. This alone can prevent many errors, including the ‘SSL handshake failed’ error. Chrome users can check that by opening the Chrome browser and clicking on the three vertical dots in the top-right hand corner. Next, click on ‘More Tools’ and if your Chrome browser needs an update, then you’ll find one here. If you don’t, it only means that your Chrome browser is up to date.

#3. Deactivate recently installed plugins or extensions

Most browser plugins and extensions come from unknown developers and could very well be packed with malicious code. So, if you recently installed one of those and have been experiencing the SSL handshake error, then try uninstalling it and clearing your cache and cookies. After you’ve done that, try reconnecting to the same website and check if you can now establish a secure connection.

Chrome users can uninstall the extension by following the below mentioned steps:

  • Click on the three vertical dots on the top-right corner
  • Click on ‘Settings’
  • Select ‘Extensions’
  • Choose the extension you recently installed and click on remove

google chrome extension setting

#4. Protocol Mismatch

Many people face the SSL handshake issue due to a protocol mismatch between the server and the client. Basically, there are multiple versions of the SSL/TLS protocol available and for a successful handshake, it is essential that the web server and the browser support the same version.

Often, the SSL handshake error shows up when the server runs on a protocol version that is much higher than that of the client computer. For instance, if the server uses the TLS 1.3 version but the browser’s using the TLS 1.1, then the SSL handshake is likely to fail because servers do not support previous versions. You can fix this by resetting your browser to its default settings and using it without any extensions.

To reset the browser settings to default on your Chrome browser, click on the three vertical dots on the top-right hand corner, choose ‘Settings’ and then ‘System’. Finally, click on the ‘reset settings to original default’ option and you are done.

reset settings to original defaults in google chrome

#5. Expired Certificate

You could be facing the handshake issue simply because you are trying to access a website that does not have a valid SSL certificate. Use our free SSL Certificate checker tool to validate your SSL certificate.

Conclusion:

We have discussed some of the most effective solutions for the SSL handshake problem, which might occur due to the browser or the system settings. In most cases, correcting the time and date settings or removing the trouble-causing extensions from the browser solves the issue.

For server-related concerns, it is only the website owner or administrator who can fix the ‘SSL handshake failed’ problem. Some of the common server-side issues are an invalid SSL certificate, a free SSL certificate from a fraudulent website, problems with the cipher suite, and incorrect installation of the SSL Certificate. In that case, it is recommended that you contact the website owner or administrator for an effective resolution.

Recommended Reading:

  • ERR_SSL_PROTOCOL_ERROR
  • NET::ERR_CERT_COMMON_NAME_INVALID
  • ERR_SSL_VERSION_OR_CIPHER_MISMATCH
  • ERR_SSL_VERSION_INTERFERENCE
  • ERR_BAD_SSL_CLIENT_AUTH_CERT

Ошибка продления лицензии — Метод GetLicense завершился с ошибкой: 6 (SslHandshakeFailedError)

30 сентября истёк срок действия корневого сертификата IdenTrust DST Root CA X3 Let’s Encrypt

Если у вас после 30 сентября появляется ошибка SslHandshakeFailedError обновления лицензии на IP-приёмнике, то, скорее всего, в вашей операционной системе не установлены обновлённые сертификаты. Для проверки пройдите по ссылке на сайт Let’s Encrypt.

Если на странице вы видите предупреждения безопасности, то вам необходимо добавить сертификат ISRG Root X1 в корневые доверенные сертификаты.

Скачать сертификат:

  • страница сертификатов Let’s Encrypt
  • напрямую с сайта Let’s Encrypt
  • с нашего сайта

Следующим шагом необходимо установить сертификат.

Установка сертификата

Открываем скачанный сертификат кликом мыши:

Установка корневого сертификата шаг 1

Жмём установить сертификат…

Установка корневого сертификата шаг 2

Установим для текущего пользователя, жмём далее

Установка корневого сертификата шаг 3

Выбираем «Поместить все сертификаты в следующее хранилище» и нажимаем далее

Установка корневого сертификата шаг 4

Выбираем «Доверенные корневые центры сертификации»

Далее

Готово

Затем повторяем те же шаги для «Локальный компьютер»

На этом установка сертификата закончена.

Перезапуск IP-приёмника

  • Завершаем работу IP-приёмника
  • Удаляем из папки IP-приёмника C:Program Files (x86)NPO PionerIP-приёмник Барьер файлы private.pem и public.pem
  • Запускаем IP-приёмник
  • В настройках на вкладке лицензия, проверяем что лицензия успешна получена

Действительность должна быть «Да», время получения — текущее время.

Если ничего не получилось

Если эта статья не помогла и получить лицензию так и не удалось, вам необходимо обратится в техподдержку.

1. Играю на нескольких серверах (HiTech 1.12.2, TechnoMagic, TechnoMagicRPG)
2. При попытке запустить лаунчер McSkill возникает ошибка «Ошибка при получении списка обновления: SslHandlshakeFailedError Проверьте соединение с интернетом, а так же попробуйте отключить антивирус!» Соединение норм — всё работает, лига легенд на норм пинге пашет, антивируса у меня вовсе нет.
unknown.png

Я попробовала:
1) добавила приложение в список разрешений брандмауэра
2) скачала и попробовала запустить McSkill.jar — вообще не запускается, даже в диспетчере задач не появляется
3) попробовала этот McSkill.jar открыть с помощью java.exe — всё равно даже в диспетчере нет
4) установила java jre1.8.0_301 — это помогло запуститься клиенту майнкрафта другого проекта, ранее показывал ошибку:
unknown.png

У меня на компе в ProgramFiles лежал jdk-17 и видимо оба клиента пытались запуститься через этот jdk, а не через позже установленный jre. Поустанавливала jre — клиент другого проекта то работал, то нет. При установленном jre удалила jdk оттуда нафиг — тот клиент заработал (наш — нет).
5) перезапустила комп несколько раз после разных вариантов решений проблемы (не ну мало ли, оч часто помогает))))
У меня подозрение, что это всё таки связано с версией java, которая стоит на компе, но решить чот не получается, help pls.
3. Скриншоты уже есть выше
4. Краш-лог получить не могу, до значка шестеренки даже не доходит (если это в хранилось в C:Users…AppDataRoaming то к сожалению папку McSkill я оттуда удалила).
5. discord Terapanthera#2749

Installing a Secure Sockets Layer (SSL) certificate on your WordPress site enables it to use HTTPS to ensure secure connections. Unfortunately, there are a variety of things that can go wrong in the process of confirming a valid SSL certificate and making a connection between your site’s server and a visitor’s browser.

If you’ve encountered an “SSL Handshake Failed” error message and are confused as to what it means, you’re not alone. It’s a common error that doesn’t tell you much on its own. While this can be a frustrating experience, the good news is that there are simple steps you can take to resolve the issue.

In this post, we’ll explain what the SSL Handshake Failed error is and what causes it. Then we’ll provide you with several methods you can use to fix it.

Let’s get started!

An Introduction to the SSL Handshake

Before we dig deeper into what causes a TLS or SSL handshake failure, it’s helpful to understand what the TLS/SSL handshake is. Secure Sockets Layer (SSL) and Transport Layer Security (TLS) are protocols used to authenticate data transfers between servers and external systems such as browsers.

SSL certificates are needed in order to secure your website using HTTPS. We won’t get too in-depth about the difference between TLS vs SSL since it’s a minor one. The terms are often used interchangeably, so for simplicity’s sake, we’ll use “SSL” to refer to both.

With that out of the way, an SSL handshake is the first step in the process of establishing an HTTPS connection. To authenticate and establish the connection, the user’s browser and the website’s server must go through a series of checks (the handshake), which establish the HTTPS connection parameters.

Let us explain: the client (typically the browser) sends a request for a secure connection to the server. After the request is sent, the server sends a public key to your computer and checks that key against a list of certificates. The computer then generates a key and encrypts it, using the public key sent from the server.

To make a long story short, without the SSL handshake, a secure connection won’t be made. This can pose a significant security risk. Plus, there are a lot of moving parts involved in the process.

That means there are many different opportunities for something to go wrong and cause a handshake failure, or even lead to the “your connection is not private” error, causing visitors to leave.

Confronted with the ‘SSL Handshake Failed’ error? 🤝 Get a grip on how to solve it with these 5 methods ⤵️Click to Tweet

Understanding What Causes SSL Handshake Failures

An SSL Handshake Failure or Error 525 means that the server and browser were unable to establish a secure connection. This can happen for a variety of reasons.

Generally, an Error 525 means that the SSL handshake between a domain using Cloudflare and the origin web server failed:

ssl handshake failed error

However, it’s also important to understand that SSL errors can happen on the client-side or the server-side. Common causes of SSL errors on the client-side include:

  • The wrong date or time on the client device.
  • An error with the browser configuration.
  • A connection that is being intercepted by a third party.

Some server-side causes include:

  • A cipher suite mismatch.
  • A protocol used by the client that isn’t supported by the server.
  • A certificate that is incomplete, invalid, or expired.

Typically, if the SSL handshake fails, the issue can be attributed to something wrong with the website or server and their SSL configurations.

How to Fix the SSL Handshake Failed Error (5 Methods)

There are several potential causes behind the “SSL Handshake Failed” error. So there’s no simple answer when it comes to how you should fix it.

Fortunately, there are a handful of methods you can use to begin exploring potential issues and resolving them one by one. Let’s take a look at five strategies you can use to try and fix the SSL Handshake Failed error.

1. Update Your System Date and Time

Let’s start with one of the more unlikely causes, but one that is incredibly easy to correct if it is the problem: your computer’s clock.

If your system is using the wrong date and time, that may interrupt the SSL handshake. When the system clock is different than the actual time, for example, if it’s set too far into the future, it can interfere with the SSL certificate verification.

Your computer’s clock might have been set incorrectly due to human error or simply due to a glitch in your settings. Whatever the reason, it’s a good idea to check and make sure your system time is correct, and update it if it’s not.

Of course, if your clock is showing the correct information, it’s safe to assume that this isn’t the source of the “SSL Handshake Failed” issue.

2. Check to See If Your SSL Certificate Is Valid

Expiration dates are placed on SSL certificates, to help make sure their validation information remains accurate. Generally, the validity of these certificates lasts for anywhere between six months and two years.

If an SSL certificate is revoked or expired, the browser will detect this and be unable to complete the SSL handshake. If it’s been more than a year or so since you installed an SSL certificate on your website, it might be time to reissue it.

To view the status of your SSL certificate, you can use an SSL certificate checker tool such as the one offered by Qualys:

qualys labs

The SSL Server Test tool on the Qualys website

This tool is both reliable and free to use. All you need to do is input your domain name into the Hostname field, and then click on Submit. Once the checker is done analyzing your site’s SSL configuration, it will present you with some results:

ssl certificate status

The results page of the Qualys SSL checker tool

On this page, you can find out if your certificate is still valid and see if it has been revoked for any reason.

In either case, updating your SSL certificate should resolve the handshake error (and is vital for keeping your site and your WooCommerce store secure).

3. Configure Your Browser for the Latest SSL/TLS Protocol Support

Sometimes the best way to determine the root cause of an issue is by process of elimination. As we mentioned earlier, the SSL handshake failure can often occur due to a browser misconfiguration.

The quickest way to determine whether a particular browser is the problem is to try switching to a different one. This can at least help narrow down the problem. You may also try disabling any plugins and resetting your browser back to its default settings.

Another potential browser-related issue is a protocol mismatch. For example, if the server only supports TLS 1.2, but the browser is only configured for TLS 1.0 or TLS 1.1, there’s no mutually-supported protocol available. This will inevitably lead to an SSL handshake failure.

How you can check to see if this problem is occurring varies based on the browser you’re using. As an example, we’ll look at how the process works in Chrome. First, open your browser and go to Settings > Advanced. This will expand a number of menu options.

Under the System section, click on Open your computer’s proxy settings:

proxy settings

The system settings page in Google Chrome

This will open up a new window. Next, select the Advanced tab. Under the Security section, check to see if the box next to Use TLS 1.2 is selected. If not, check that option:

Fix "ssl handshake failed" error: ssl tls settings

The Internet Properties advanced settings in Windows

It’s also recommended that you uncheck the boxes for SSL 2.0 and SSL 3.0.

The same applies to TLS 1.0 and TLS 1.1 since they are being phased out. When you’re done, click on the OK button, and check to see if the handshake error has been resolved.

Note that if you’re using Apple Safari or Mac OS there isn’t an option to enable or disable SSL protocols. TLS 1.2 is automatically enabled by default. If you’re using Linux, you can refer to the Red Hat guide on TLS hardening.

4. Verify That Your Server Is Properly Configured to Support SNI

It’s also possible that the SSL handshake failure is being caused by improper Server Name Indication (SNI) configuration. The SNI is what enables a web server to securely host several TLS certificates for one IP address.

Each website on a server has its own certificate. However, if the server isn’t SNI-enabled, that can result in an SSL handshake failure, because the server may not know which certificate to present.

There are a few ways to check and see whether a site requires SNI. One option is to use Qualys’ SSL Server Test, which we discussed in the previous section. Input your site’s domain name, and then click on the Submit button.

On the results page, look for a message that reads “This site works only in browsers with SNI support”:

browser sni support

The summary results page of the Qualys SSL checker tool

Another approach for detecting if a server is using SNI is to browse the server names in the ‘ClientHello’ message. This is a more technical process, but it can offer a lot of information.

It involves checking the extended hello header for a ‘server_name’ field, to see if the correct certifications are presented.

If you’re familiar with using tools such as the OpenSSL toolkit and Wireshark, you might find this method preferable. You can use openssl s_client with and without the -servername option:

# without SNI
 $ openssl s_client -connect host:port 

 # use SNI
 $ openssl s_client -connect host:port -servername host

If you get two different certificates with the same name, it means that the SNI is supported and properly configured.

However, if the output in the returned certificates is different, or the call without SNI cannot establish an SSL connection, it indicates that SNI is required but not correctly configured. Resolving this issue may require switching to a dedicated IP address.

5. Make Sure the Cipher Suites Match

If you still haven’t been able to identify the cause of the SSL handshake failure, it might be due to a cipher suite mismatch. In case you’re unfamiliar with the term, ‘cipher suites’ refer to a set of algorithms, including ones for key exchange, bulk encryption, and message authentication code, that can be used for securing SSL and TLS network connections.

If the cipher suites that a server uses don’t support or match what’s used by Cloudflare, that can result in an “SSL Handshake Failed” error.

When it comes to figuring out whether there is a cipher suite mismatch, Qualys’ SSL Server Test proves yet again to be a useful tool.

When you input your domain and click on Submit, you’ll see a summary analysis page. You can find the cipher information under the Cipher Suites section:

qualys cipher suites

The Cipher Suites section in a Qualys SSL report

You can use this page to discover which ciphers and protocols the server supports. You’ll want to look out for any that display the ‘weak’ status. In addition, this section also details the specific algorithms for the cipher suites.

To correct this issue, you can compare the results against what your browser supports by using the Qualys SSL/TLS Capabilities of Your Browser tool. For more extensive information and guidance about cipher suites, we also recommend checking out the ComodoSSLStore guide.

Confused by the ‘SSL Handshake Failed’ error message? This guide explains what it is and, most importantly, 5 ways to fix it 🙌Click to Tweet

Summary

One of the most perplexing yet common types of SSL-related problems is the “SSL Handshake Failed” error. Dealing with this error can be stressful since it has many potential causes, including both client- and server-side issues.

However, there are some reliable solutions you can use to identify the problem and resolve it. Here are five ways you can use to fix the SSL Handshake Failed error:

  1. Update your system date and time.
  2. Check to see if your SSL certificate is valid (and reissue it if necessary).
  3. Configure your browser to support the latest TLS/SSL versions.
  4. Verify that your server is properly configured to support SNI.
  5. Make sure the cipher suites match.

Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275+ PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Installing a Secure Sockets Layer (SSL) certificate on your WordPress site enables it to use HTTPS to ensure secure connections. Unfortunately, there are a variety of things that can go wrong in the process of confirming a valid SSL certificate and making a connection between your site’s server and a visitor’s browser.

If you’ve encountered an “SSL Handshake Failed” error message and are confused as to what it means, you’re not alone. It’s a common error that doesn’t tell you much on its own. While this can be a frustrating experience, the good news is that there are simple steps you can take to resolve the issue.

In this post, we’ll explain what the SSL Handshake Failed error is and what causes it. Then we’ll provide you with several methods you can use to fix it.

Let’s get started!

An Introduction to the SSL Handshake

Before we dig deeper into what causes a TLS or SSL handshake failure, it’s helpful to understand what the TLS/SSL handshake is. Secure Sockets Layer (SSL) and Transport Layer Security (TLS) are protocols used to authenticate data transfers between servers and external systems such as browsers.

SSL certificates are needed in order to secure your website using HTTPS. We won’t get too in-depth about the difference between TLS vs SSL since it’s a minor one. The terms are often used interchangeably, so for simplicity’s sake, we’ll use “SSL” to refer to both.

With that out of the way, an SSL handshake is the first step in the process of establishing an HTTPS connection. To authenticate and establish the connection, the user’s browser and the website’s server must go through a series of checks (the handshake), which establish the HTTPS connection parameters.

Let us explain: the client (typically the browser) sends a request for a secure connection to the server. After the request is sent, the server sends a public key to your computer and checks that key against a list of certificates. The computer then generates a key and encrypts it, using the public key sent from the server.

To make a long story short, without the SSL handshake, a secure connection won’t be made. This can pose a significant security risk. Plus, there are a lot of moving parts involved in the process.

That means there are many different opportunities for something to go wrong and cause a handshake failure, or even lead to the “your connection is not private” error, causing visitors to leave.

Confronted with the ‘SSL Handshake Failed’ error? 🤝 Get a grip on how to solve it with these 5 methods ⤵️Click to Tweet

Understanding What Causes SSL Handshake Failures

An SSL Handshake Failure or Error 525 means that the server and browser were unable to establish a secure connection. This can happen for a variety of reasons.

Generally, an Error 525 means that the SSL handshake between a domain using Cloudflare and the origin web server failed:

ssl handshake failed error

However, it’s also important to understand that SSL errors can happen on the client-side or the server-side. Common causes of SSL errors on the client-side include:

  • The wrong date or time on the client device.
  • An error with the browser configuration.
  • A connection that is being intercepted by a third party.

Some server-side causes include:

  • A cipher suite mismatch.
  • A protocol used by the client that isn’t supported by the server.
  • A certificate that is incomplete, invalid, or expired.

Typically, if the SSL handshake fails, the issue can be attributed to something wrong with the website or server and their SSL configurations.

How to Fix the SSL Handshake Failed Error (5 Methods)

There are several potential causes behind the “SSL Handshake Failed” error. So there’s no simple answer when it comes to how you should fix it.

Fortunately, there are a handful of methods you can use to begin exploring potential issues and resolving them one by one. Let’s take a look at five strategies you can use to try and fix the SSL Handshake Failed error.

1. Update Your System Date and Time

Let’s start with one of the more unlikely causes, but one that is incredibly easy to correct if it is the problem: your computer’s clock.

If your system is using the wrong date and time, that may interrupt the SSL handshake. When the system clock is different than the actual time, for example, if it’s set too far into the future, it can interfere with the SSL certificate verification.

Your computer’s clock might have been set incorrectly due to human error or simply due to a glitch in your settings. Whatever the reason, it’s a good idea to check and make sure your system time is correct, and update it if it’s not.

Of course, if your clock is showing the correct information, it’s safe to assume that this isn’t the source of the “SSL Handshake Failed” issue.

2. Check to See If Your SSL Certificate Is Valid

Expiration dates are placed on SSL certificates, to help make sure their validation information remains accurate. Generally, the validity of these certificates lasts for anywhere between six months and two years.

If an SSL certificate is revoked or expired, the browser will detect this and be unable to complete the SSL handshake. If it’s been more than a year or so since you installed an SSL certificate on your website, it might be time to reissue it.

To view the status of your SSL certificate, you can use an SSL certificate checker tool such as the one offered by Qualys:

qualys labs

The SSL Server Test tool on the Qualys website

This tool is both reliable and free to use. All you need to do is input your domain name into the Hostname field, and then click on Submit. Once the checker is done analyzing your site’s SSL configuration, it will present you with some results:

ssl certificate status

The results page of the Qualys SSL checker tool

On this page, you can find out if your certificate is still valid and see if it has been revoked for any reason.

In either case, updating your SSL certificate should resolve the handshake error (and is vital for keeping your site and your WooCommerce store secure).

3. Configure Your Browser for the Latest SSL/TLS Protocol Support

Sometimes the best way to determine the root cause of an issue is by process of elimination. As we mentioned earlier, the SSL handshake failure can often occur due to a browser misconfiguration.

The quickest way to determine whether a particular browser is the problem is to try switching to a different one. This can at least help narrow down the problem. You may also try disabling any plugins and resetting your browser back to its default settings.

Another potential browser-related issue is a protocol mismatch. For example, if the server only supports TLS 1.2, but the browser is only configured for TLS 1.0 or TLS 1.1, there’s no mutually-supported protocol available. This will inevitably lead to an SSL handshake failure.

How you can check to see if this problem is occurring varies based on the browser you’re using. As an example, we’ll look at how the process works in Chrome. First, open your browser and go to Settings > Advanced. This will expand a number of menu options.

Under the System section, click on Open your computer’s proxy settings:

proxy settings

The system settings page in Google Chrome

This will open up a new window. Next, select the Advanced tab. Under the Security section, check to see if the box next to Use TLS 1.2 is selected. If not, check that option:

Fix "ssl handshake failed" error: ssl tls settings

The Internet Properties advanced settings in Windows

It’s also recommended that you uncheck the boxes for SSL 2.0 and SSL 3.0.

The same applies to TLS 1.0 and TLS 1.1 since they are being phased out. When you’re done, click on the OK button, and check to see if the handshake error has been resolved.

Note that if you’re using Apple Safari or Mac OS there isn’t an option to enable or disable SSL protocols. TLS 1.2 is automatically enabled by default. If you’re using Linux, you can refer to the Red Hat guide on TLS hardening.

4. Verify That Your Server Is Properly Configured to Support SNI

It’s also possible that the SSL handshake failure is being caused by improper Server Name Indication (SNI) configuration. The SNI is what enables a web server to securely host several TLS certificates for one IP address.

Each website on a server has its own certificate. However, if the server isn’t SNI-enabled, that can result in an SSL handshake failure, because the server may not know which certificate to present.

There are a few ways to check and see whether a site requires SNI. One option is to use Qualys’ SSL Server Test, which we discussed in the previous section. Input your site’s domain name, and then click on the Submit button.

On the results page, look for a message that reads “This site works only in browsers with SNI support”:

browser sni support

The summary results page of the Qualys SSL checker tool

Another approach for detecting if a server is using SNI is to browse the server names in the ‘ClientHello’ message. This is a more technical process, but it can offer a lot of information.

It involves checking the extended hello header for a ‘server_name’ field, to see if the correct certifications are presented.

If you’re familiar with using tools such as the OpenSSL toolkit and Wireshark, you might find this method preferable. You can use openssl s_client with and without the -servername option:

# without SNI
 $ openssl s_client -connect host:port 

 # use SNI
 $ openssl s_client -connect host:port -servername host

If you get two different certificates with the same name, it means that the SNI is supported and properly configured.

However, if the output in the returned certificates is different, or the call without SNI cannot establish an SSL connection, it indicates that SNI is required but not correctly configured. Resolving this issue may require switching to a dedicated IP address.

5. Make Sure the Cipher Suites Match

If you still haven’t been able to identify the cause of the SSL handshake failure, it might be due to a cipher suite mismatch. In case you’re unfamiliar with the term, ‘cipher suites’ refer to a set of algorithms, including ones for key exchange, bulk encryption, and message authentication code, that can be used for securing SSL and TLS network connections.

If the cipher suites that a server uses don’t support or match what’s used by Cloudflare, that can result in an “SSL Handshake Failed” error.

When it comes to figuring out whether there is a cipher suite mismatch, Qualys’ SSL Server Test proves yet again to be a useful tool.

When you input your domain and click on Submit, you’ll see a summary analysis page. You can find the cipher information under the Cipher Suites section:

qualys cipher suites

The Cipher Suites section in a Qualys SSL report

You can use this page to discover which ciphers and protocols the server supports. You’ll want to look out for any that display the ‘weak’ status. In addition, this section also details the specific algorithms for the cipher suites.

To correct this issue, you can compare the results against what your browser supports by using the Qualys SSL/TLS Capabilities of Your Browser tool. For more extensive information and guidance about cipher suites, we also recommend checking out the ComodoSSLStore guide.

Confused by the ‘SSL Handshake Failed’ error message? This guide explains what it is and, most importantly, 5 ways to fix it 🙌Click to Tweet

Summary

One of the most perplexing yet common types of SSL-related problems is the “SSL Handshake Failed” error. Dealing with this error can be stressful since it has many potential causes, including both client- and server-side issues.

However, there are some reliable solutions you can use to identify the problem and resolve it. Here are five ways you can use to fix the SSL Handshake Failed error:

  1. Update your system date and time.
  2. Check to see if your SSL certificate is valid (and reissue it if necessary).
  3. Configure your browser to support the latest TLS/SSL versions.
  4. Verify that your server is properly configured to support SNI.
  5. Make sure the cipher suites match.

Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275+ PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

SSL Handshake Failed error occurs when the client or server fails to establish a secure connection.

Has your SSL handshake failed? For someone who isn’t quite adept in technology, the term ‘SSL handshake’ might seem cryptic or out of the context. If you are in that zone and know nothing about why this error is popping up on your system, then read until the end.

clickssl promotional blog post banner

In this article, we shall not only discuss what an SSL handshake is, but we shall also delve deeper into why this error shows up and what you can do to fix it.

What is an SSL handshake?

The SSL handshake involves algorithm agreement, certificate exchange, and the exchange of keys using the shared algorithm. So, the ‘SSL handshake’ is the name given to a securely devised process that helps encrypt client-server communication through cryptographic keys. These keys are exchanged between the server and the client using one out of the two shared algorithms that both the server and the client mutually agreed upon. So, if any glitch occurs during this process, then the ‘SSL handshake failed’ error shows up.

Why does the ‘SSL handshake failed’ error occur?

An SSL handshake error, also known as error 525 occurs when the two endpoints (server and client) are unable to establish a secure connection. This can happen due to several issues, which might be on the server side or the client side. If you are experiencing this error, there is not much to worry about and no matter what’s causing it, we’ll help you fix it in no time. Let us now discuss some ways in which you can fix the SSL handshake error.

How to Fix the “SSL Handshake Failed” Error?

#1. Check your system’s time and date

Before you try any other fix for your SSL handshake error, we strongly recommend that you try correcting your system’s date and time. Silly as it may seem, this works for most people experiencing this sort of error. So, don’t undermine the power of your system’s date and time setting, which might be wrong due to many reasons.

It could be wrong due to pure neglect, a software glitch caused by malware, or simply because you are using a server located in another time zone through a VPN. If you are using a VPN, then it is recommended that you configure the date and time according to the server’s time zone. This refers to the date and time of the location in which the server is located, and not your physical location.

Windows user can reset the date and time in the following manner:

  • Click on the ‘Windows’ button.
  • Type ‘Date and Time Settings’ and choose the relevant option.
  • If you wish to set the time automatically, toggle the ‘set time automatically’ button.
  • If you are using a VPN or wish to set the time manually for any other reason, click on the ‘Set the date and time manually’ option.

date and time setup in windows

On Mac, the same can be done by navigating to ‘Menu’ and then to ‘System Preferences’. You will find similar settings for all other Operating Systems.

#2. Update your Web Browser

At all times, you must keep your Operating System and applications up to date. This alone can prevent many errors, including the ‘SSL handshake failed’ error. Chrome users can check that by opening the Chrome browser and clicking on the three vertical dots in the top-right hand corner. Next, click on ‘More Tools’ and if your Chrome browser needs an update, then you’ll find one here. If you don’t, it only means that your Chrome browser is up to date.

#3. Deactivate recently installed plugins or extensions

Most browser plugins and extensions come from unknown developers and could very well be packed with malicious code. So, if you recently installed one of those and have been experiencing the SSL handshake error, then try uninstalling it and clearing your cache and cookies. After you’ve done that, try reconnecting to the same website and check if you can now establish a secure connection.

Chrome users can uninstall the extension by following the below mentioned steps:

  • Click on the three vertical dots on the top-right corner
  • Click on ‘Settings’
  • Select ‘Extensions’
  • Choose the extension you recently installed and click on remove

google chrome extension setting

#4. Protocol Mismatch

Many people face the SSL handshake issue due to a protocol mismatch between the server and the client. Basically, there are multiple versions of the SSL/TLS protocol available and for a successful handshake, it is essential that the web server and the browser support the same version.

Often, the SSL handshake error shows up when the server runs on a protocol version that is much higher than that of the client computer. For instance, if the server uses the TLS 1.3 version but the browser’s using the TLS 1.1, then the SSL handshake is likely to fail because servers do not support previous versions. You can fix this by resetting your browser to its default settings and using it without any extensions.

To reset the browser settings to default on your Chrome browser, click on the three vertical dots on the top-right hand corner, choose ‘Settings’ and then ‘System’. Finally, click on the ‘reset settings to original default’ option and you are done.

reset settings to original defaults in google chrome

#5. Expired Certificate

You could be facing the handshake issue simply because you are trying to access a website that does not have a valid SSL certificate. Use our free SSL Certificate checker tool to validate your SSL certificate.

Conclusion:

We have discussed some of the most effective solutions for the SSL handshake problem, which might occur due to the browser or the system settings. In most cases, correcting the time and date settings or removing the trouble-causing extensions from the browser solves the issue.

For server-related concerns, it is only the website owner or administrator who can fix the ‘SSL handshake failed’ problem. Some of the common server-side issues are an invalid SSL certificate, a free SSL certificate from a fraudulent website, problems with the cipher suite, and incorrect installation of the SSL Certificate. In that case, it is recommended that you contact the website owner or administrator for an effective resolution.

Recommended Reading:

  • ERR_SSL_PROTOCOL_ERROR
  • NET::ERR_CERT_COMMON_NAME_INVALID
  • ERR_SSL_VERSION_OR_CIPHER_MISMATCH
  • ERR_SSL_VERSION_INTERFERENCE
  • ERR_BAD_SSL_CLIENT_AUTH_CERT

I use following code to try to establish a connection to a remote host.

The client must authenticate with a self signed certificate to be able to create a valid SSL connection:

QRemoteProxyCommunication::QRemoteProxyCommunication(QObject *parent) : QObject(parent) {
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    QNetworkRequest request;

    QFile certFile("/path/to/file/clientcert.p12");
    certFile.open(QFile::ReadOnly);
    QSslCertificate certificate;
    QSslKey key;
    QList<QSslCertificate> importedCerts;

    bool imported = QSslCertificate::importPkcs12(&certFile, &key, &certificate, &importedCerts, QByteArray::fromStdString(""));
    qDebug() << "Imported: " << imported;

    QSslConfiguration config = request.sslConfiguration();

    config.setCaCertificates(importedCerts);
    config.setProtocol(QSsl::AnyProtocol);
    config.setPeerVerifyMode(QSslSocket::VerifyNone);
    request.setSslConfiguration(config);
    request.setUrl(QUrl("https://www.url.com"));
    reply = manager->get(request);;

    qDebug() << " Certs: " << certificate;

    qDebug() << reply->error();
    qDebug() << reply->errorString();

    connect(reply, SIGNAL(readyRead()), this, SLOT(replyReadyRead()));
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(replyNetworkError(QNetworkReply::NetworkError)));
    connect(manager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>)),
            this, SLOT(errors(QNetworkReply*, const QList<QSslError>)));
    connect(manager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>)),
            this, SLOT(errors(QNetworkReply*, const QList<QSslError>)));

}

void QRemoteProxyCommunication::replyNetworkError(QNetworkReply::NetworkError code) {

    qDebug() << "Network error => " << code;
}

But I always get the error message:

Network error => QNetworkReply::NetworkError(SslHandshakeFailedError) in replyNetworkError SLOT.

Furthermore the slot errors is not invoked.

The line QSslCertificate::importPkcs12(&certFile, &key, &certificate, &importedCerts, QByteArray::fromStdString("")); returns true.

If I add the p12 certificate file within Chrome Browser and try to open the host it is working fine.

Furthermore if I try to call request.setUrl(QUrl("https://www.test.de")); the readyRead() signal is invoked and I can read the response content.

What`s wrong with my implementation?

  1. 1. QNetworkReply::ConnectionRefusedError и QNetworkReply::RemoteHostClosedError
  2. 2. QNetworkReply::HostNotFoundError
  3. 3. QNetworkReply::TimeoutError
  4. 4. QNetworkReply::OperationCanceledError
  5. 5. QNetworkReply::SslHandshakeFailedError
  6. 6. QNetworkReply::TemporaryNetworkFailureError и QNetworkReply::NetworkSessionFailedError
  7. 7. QNetworkReply::BackgroundRequestNotAllowedError
  8. 8. QNetworkReply::TooManyRedirectsError и QNetworkReply::InsecureRedirectError
  9. 9. Ошибки QNetworkReply::Proxy*
  10. 10. QNetworkReply::ContentAccessDenied
  11. 11. QNetworkReply::AuthenticationRequiredError
  12. 12. QNetworkReply::ContentReSendError
  13. 13. QNetworkReply::ContentConflictError
  14. 14. QNetworkReply::ContentGoneError
  15. 15. QNetworkReply::InternalServerError
  16. 16. QNetworkReply::OperationNotImplementedError
  17. 17. QNetworkReply::ProtocolUnknownError
  18. 18. QNetworkReply::ServiceUnavailableError
  19. 19. QNetworkReply::ProtocolInvalidOperationError
  20. 20. QNetworkReply::UnknownNetworkError
  21. 21. QNetworkReply::UnknownProxyError
  22. 22. Ошибки QNetworkReply::UnknownContentError,QNetworkReply::ProtocolFailure, QNetworkReply::UnknownServerError
  23. 23. Пример с выводом ошибки в qDebug

В одном из уроков была представлена работа с

QNetworkAccessManager

для получения содержимого страницы с сайта по протоколу

http.

Там была сделана проверка на наличие ошибок, но не были даны пояснения, какие могут быть ошибки. Для этого класс

QNetworkReply

предоставляет

enum NetworkError

, в котором перечислены коды возможных ошибок.

В случае успешного выполнения возвращается

NoError

, равный

0

.

В противном случае возвращается код ошибки из кодов, представленных ниже:


Константа Значение Описание
QNetworkReply::ConnectionRefusedError
1
Удалённый сервер отклонил соединение (сервер не принимает запросы)
QNetworkReply::RemoteHostClosedError
2
удаленный сервер закрыл соединение преждевременно, до того, как весь ответ был получен и обработан
QNetworkReply::HostNotFoundError
3
удаленный хост не был найден (недействительное имя хоста)
QNetworkReply::TimeoutError
4
подключение к удаленному серверу истекло
QNetworkReply::OperationCanceledError
5
операция была отменена через вызов abort() или close() до того, как была завершена.
QNetworkReply::SslHandshakeFailedError
6
Подключение по SSL/TLS не удалось, шифрованный канал не может быть. Должен испускаться сигнал sslErrors().
QNetworkReply::TemporaryNetworkFailureError
7
соединение было нарушено из-за отключения от сети, однако система инициировала роуминг к другой точке доступа. Запрос должен быть повторно и будет обработан, как только соединение будет восстановлено.
QNetworkReply::NetworkSessionFailedError
8
соединение было нарушено из-за отключения от сети или невозможности запуска сети.
QNetworkReply::BackgroundRequestNotAllowedError
9
запрос в настоящее время не допускается из-за политики платформы.
QNetworkReply::TooManyRedirectsError
10
количество редиректов превысило допустимый лимит. Лимит по умолчанию установлен на 50 редиректов через QNetworkRequest::setMaxRedirectsAllowed().
QNetworkReply::InsecureRedirectError
11
во время обработки редиректов, API доступа по сети обнаружило редирект с  шифрованного протокола (https) на не шифрованный (http)
QNetworkReply::ProxyConnectionRefusedError
101
в подключении к прокси-серверу было отказано (прокси-сервер не принимает запросы)
QNetworkReply::ProxyConnectionClosedError
102
прокси-сервер закрыл соединение преждевременно, до того, как весь ответ был получен и обработан
QNetworkReply::ProxyNotFoundError
103
прокси-хост не был найден (недействительное имя прокси хоста)
QNetworkReply::ProxyTimeoutError
104
подключение к прокси-серверу истекло или прокси-сервер не ответил вовремя на отправленный запрос
QNetworkReply::ProxyAuthenticationRequiredError
105
прокси-сервер требует аутентификации для того, чтобы удовлетворить запрос, но не принял каких-либо предложенных учётных данных (если таковые имеются)
QNetworkReply::ContentAccessDenied
201
в доступе к удаленному контенту было отказано (по аналогии с ошибкой HTTP 401)
QNetworkReply::ContentOperationNotPermittedError
202
Запрошенная операция на удаленное содержимое не допускается
QNetworkReply::ContentNotFoundError
203
удаленный контент не был найден на сервере (аналогично ошибке HTTP 404)
QNetworkReply::AuthenticationRequiredError
204
удаленный сервер требует аутентификации, чтобы предоставить контент, но предоставленные учетные данные не были приняты (если таковые имеются)
QNetworkReply::ContentReSendError
205
запрос необходимо отправить повторно, но это не удалось, например, потому что загрузка данных не может быть прочитана во второй раз.
QNetworkReply::ContentConflictError
206
запрос не может быть завершен из-за конфликта с текущим состоянием ресурса.
QNetworkReply::ContentGoneError
207
запрошенный ресурс больше не доступен на сервере.
QNetworkReply::InternalServerError
401
Сервер столкнулся с непредвиденным условием, которое не позволяет ему выполнить запрос.
QNetworkReply::OperationNotImplementedError
402
сервер не поддерживает функциональные возможности, необходимые для выполнения запроса.
QNetworkReply::ServiceUnavailableError
403
сервер не может обработать запрос в данный момент.
QNetworkReply::ProtocolUnknownError
301
Network Access API не может удовлетворить запрос, потому что протокол не известен
QNetworkReply::ProtocolInvalidOperationError
302
запрошенная операция недопустима для этого протокола
QNetworkReply::UnknownNetworkError
99
была обнаружена неизвестная ошибка сети
QNetworkReply::UnknownProxyError
199
была обнаружена неизвестная ошибка прокси
QNetworkReply::UnknownContentError
299
была обнаружена неизвестная ошибка, связанная с удаленным содержимым
QNetworkReply::ProtocolFailure
399
был обнаружен сбой в протоколе (ошибка синтаксического анализа, недействительные или неожиданные ответы и т.д.)
QNetworkReply::UnknownServerError
499
была обнаружена неизвестная ошибка, связанная с ответом сервера

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

QNetworkReply::ConnectionRefusedError и QNetworkReply::RemoteHostClosedError

Если говорить об интерпретации данных ошибок, то наиболее ярким примером для меня является подключение по SSH к другому хосту. Смысл ошибок в том, что в первом случае сервер нас не пускает, а во втором случае соединение могло быть закрыто по истечению определённого периода времени.

Также ошибка ConnectionRefusedError может возникать в случаях, когда на определённом порту ПК просто нет службы, которая могла бы обработать запрос.

QNetworkReply::HostNotFoundError

Пожалуй довольно понятная ошибка, которая обозначает, что вы просто ввели неверный ip адрес или домен, с которого пытаетесь получить данные. Также, такая ошибка может возникнуть в том случае, если домен перестал быть доступен в сети. Данная ошибка аналогична ошибке номер

105 —

ERR_NAME_NOT_RESOLVED (HTTP).

QNetworkReply::TimeoutError

Превышен интервал ожидания. Наиболее близкое сравнение — это использование протокола ICMP, проверка доступности узла в сети, когда производим его ping. То есть узел в сети вроде бы и есть, но он не отвечает.

QNetworkReply::OperationCanceledError

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

QNetworkAccessManager.

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

QNetworkReply::SslHandshakeFailedError

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

QNetworkReply::TemporaryNetworkFailureError и QNetworkReply::NetworkSessionFailedError

Возникновение данных ошибок может быть вызвано любой неполадкой в сети вплоть до падения физического подключения к сети. Проверять подключения можно через класс

QNetworkInterface.

Класс

QNetworkInterface

имеет статический метод

QList

QNetworkInterface::allInterfaces()

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

Virtual Box.

Тут к слову возникает очень интересный момент, когда ведётся разработка программного обеспечения, которое должно работать по сети, и при этом у разработчика имеется виртуальная машина на борту, особенно если она запущена, то необходимо учитывать этот момент, поскольку программа может пытаться получить данные через соединение с виртуальной машиной, то есть будет считать что сеть доступна, хотя разработчик будет тестировать User Case при отключённом соединении. Впрочем, даже выключенная виртуальная машина будет вызывать некоторые проблемы, поскольку соединение будет активно, хотя Link и не будет поднят.

Поэтому, чтобы понять, что не так, при получении ошибок

QNetworkReply::TemporaryNetworkFailureErro

r и

QNetworkReply::NetworkSessionFailedError

придётся протестировать интерфейсы ПК на предмет активности:

QNetworkInterface::IsUp

и

QNetworkInterface::IsRunning.

QNetworkReply::BackgroundRequestNotAllowedError

А вот эта ошибка зависит непосредственно от политик платформы, для которой разрабатывается приложение. Например, если под некоторым абстрактным Android устройством запрещён обмен информацией по сети в энергосберегающем режиме, то в данном режиме мы будем получать именно эту ошибку, при попытке обмена информацией.

QNetworkReply::TooManyRedirectsError и QNetworkReply::InsecureRedirectError

А вот эти ошибки из разряда новенького в Qt 5.6. Теперь можно отслеживать превышения количества редиректов со страниц сайтов, а также редиректы со страниц с шифрованием https на страницы без шифрования. Что может быть полезно для разработки программного обеспечения для анализа сайтов.

Без дополнительных настроек данные ошибки как правило не возникают. Дело в том, что когда задаётся

QNetworkRequest

и в него не устанавливаются флаги конфигурации, то при попытке запроса страницы с сайта, с которой осуществляется редирект, не будет происходить перехода на новый url, а в

QNetworkReply

не будет никакого полезного контента. Поэтому потребуется установить в

QNetworkRequest

флаг

QNetworkRequest::FollowRedirectsAttribute,

тогда QNetworkAccessManager будет переходить по редиректам, пока не получит итоговую страницу или не превысит ограничение на количество переходов. По умолчанию количество переходов ограничено 50-ю.

Установка атрибута может производиться следующим образом:

QNetworkRequest request;  
request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, QVariant(true));

Что касается

QNetworkReply::InsecureRedirectError,

то смысл заключается в том, чтобы отследить редирект на небезопасный протокол.

Ошибки QNetworkReply::Proxy*

Следующие пять ошибок аналогичны по своему характеру ошибкам подключения к серверам без проксирования.

QNetworkReply::ContentAccessDenied

В документации сказано, что данная ошибка аналогична ошибке 401 в HTTP, то есть требуется авторизация, но полагаю, что данная ошибка может возникать и в случаях получения кода 403 и 407. Ошибка 407 аналогична ошибке 401, но используется для прокси-сервера. А ошибка 403 является порождающей для ошибок 401 и 407.

QNetworkReply::AuthenticationRequiredError

Данная ошибка характерна для HTTP протокола. Дело в том, что http протокол поддерживает схемы проверки подлинности. В данном случае необходимо посылать запрос на сервер с установкой логина и пароля. Замечу, что это напрямую означает то, что Вы можете написать приложение на Qt, которое будет аутентифицироваться на сайтах и выполнять определённые действия на сайте уже в авторизованном режиме, то есть можно написать и бота для работы на сайте.

Решение проблемы заключается в том, чтобы установить логин и пароль пользователя в  QAuthenticator, который будет подмешивать учётные данные к запросу. Причем делаться это будет в автоматическом режиме по сигналу

QNetworkAccessManager::authenticationRequired,

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

connect(&m_manager,&QNetworkAccessManager::authenticationRequired,
        [this](QNetworkReply *rep, QAuthenticator* auth){
            auth->setUser("username");
            auth->setPassword("passwordd");
        });

QNetworkReply::ContentReSendError

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

QNetworkReply::ContentConflictError

Данная ошибка соответствует ошибке

409 Confilct

в протоколе HTTP.

QNetworkReply::ContentGoneError

Данная ошибка соответствует ошибке

410 Gone (Удалён)

в протоколе HTTP.

QNetworkReply::InternalServerError

Данная ошибка соответствует ошибке

500 Internal Server Error (Внутренняя ошибка сервера)

в протоколе http.

QNetworkReply::OperationNotImplementedError

Данная ошибка соответствует ошибке

501 Not Implemented (Не реализовано)

в протоколе http. Возникает такая тогда, когда Вы пытаетесь выполнить, например, запрос POST к URL, по которому сервер обрабатывает только GET запросы.

Такое поведение можно встретить, например, в

Django

проекте. Если запрос не реализован, то сервер с Django отправит пустую страницу на POST запрос с данным кодом.

QNetworkReply::ProtocolUnknownError

Такая ошибка, как

QNetworkReply::ProtocolUnknownError,

может возникнуть из-за того, что в запрос был передан url без указания типа протокола, то есть вместо


http://www.example.com

было передано


//www.example.com

Такая проблема может возникнуть в том случае, если вы парсите страницы и извлекаете url изображений. Например, на данном сайте адреса всех изображений в статьях выглядят следующим образом


/media/uploads/2017/02/03/testquickwidget.jpg

То есть не указывается протокол и домен сайта. Поэтому если Вы извлечёте все адреса изображений со страницы, то не сможете скачать изображения без дополнительной обработки, а именно без подстановки домена и протокола в начале строки, получив данную ошибку.

QNetworkReply::ServiceUnavailableError

Соответствует ошибке

503 Service Unavailable («сервис недоступен»)

в протоколе http

QNetworkReply::ProtocolInvalidOperationError

В данном случае протокол определён, но точное соответствие ошибке из протокола http не прослеживается, относительно других протоколов также может быть что угодно.

QNetworkReply::UnknownNetworkError

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

502 Bad Gateway («плохой, ошибочный шлюз»)

в протоколу http

QNetworkReply::UnknownProxyError

Также может быть ошибка 502, но уже в варианте с прокси-сервером

Ошибки QNetworkReply::UnknownContentError,QNetworkReply::ProtocolFailure, QNetworkReply::UnknownServerError

С данными ошибками затрудняюсь найти рабочее соответствие, буду рад подсказке, если кто сталкивался.

Пример с выводом ошибки в qDebug

Можно проверять ошибку по сигналу завершения запроса от

QNetworkAccessManager

в слоте, который подключается для обработки результата запроса.

manager = new QNetworkAccessManager(this);
connect(manager, &QNetworkAccessManager::finished, this, &Downloader::onResult);

В данном случае имеется класс-обёртка над классом

QNetworkAccessManager

с названием

Downloader

. У этого класса имеется слот

onResult

, который в свою очередь отвечает за обработку результата ответа

QNetworkAccessManager

.

void Downloader::onResult(QNetworkReply *reply)
{
    // Если в процессе получения данных произошла ошибка
    if(reply->error()){
        // Сообщаем об этом и показываем информацию об ошибках
        qDebug() << "ERROR";
        // Здесь получаем один из enum NetworkError, то есть код ошибки
        qDebug() << reply->error();
    } else {
        // ToDo something
    }
}

In my experience in using Qt, I find it would be hard to make a business app without the help of Qt experts. In other words, you need to buy their commercial license in order to get their support, and you definitely need their support in the course of developing a business app. Of course, you do not need any help if you write a program with some buttons on the window to click and pop up a “Hello world” dialog. You will find Qt is easy to use and keep using it until you develop an app that sells.

If you use QNetworkAccessManager to fetch a https url, you may fail with the SslHandshakeFailedError error “the SSL/TLS handshake failed and the encrypted channel could not be established. The sslErrors() signal should have been emitted.”  You can connect a slot to the error(QNetworkReply::NetworkError) signal of QNetworkReply to catch this error. The error code is QNetworkReply::NetworkError(6). This error is obviously related to SSL. Qt uses openssl to do the SSL stuff. But that error has nothing to do with the opensll lib(ssleay32.dll/libeay32.dll). The error seems related to the version compatibility of SSL such as the client uses SSLV2 but the website only supports SSLV3 and later versions. But the fact is the same program can connect to the https site successfully on Windows 10 but fails to connect the same website on Windows8 or Windows 7. If you connect a slot to the sslErrors(QList<QSslError>) signal of QNetworkReply to catch the SSL error, you will find the error is QSslError::NoError so there’s no error actually. You can verify the SSL configuration and the certificate of the website is good by visiting the website in a browser. If you try to ignore the SSL error by connecting the sslErrors(QList<QSslError>) signal of QNetworkReply to its slot ignoreSslErrors(), you will find the problem persists. So how to fix this problem or Qt bug? You should take 2 steps in order to fix this SslHandshakeFailedError .

First, you set the peer verify mode to None for the request:

QSslConfiguration conf = request.sslConfiguration();
conf.setPeerVerifyMode(QSslSocket::VerifyNone);
request.setSslConfiguration(conf);

Even you do not require to verify the certificate of the server, the SSL error(QSslError::NoError) still occurs. So,

The next step is to ignore the error by connecting the QNetworkReply’s sslErrors(QList<QSslError>) signal to its ignoreSslErrors() slot.

Note that both steps are needed.

Reference: https://stackoverflow.com/questions/21636728/qt-ssl-handshake-failed

Liked it? Take a second to support My Programming Notes on Patreon!

The program needs to access a cgi program through HTTPS, and an error occurs: QNetworkReply::SslHandshakeFailedError

Wireshark grabbed the package that accesses the page through IE and executes the program to access the page, and there is no obvious difference. But when using IE to access, it will prompt certificationerror, you need to choose to continue to access this page.

After some searching and trying, I found that the problem was solved after setting the peerverify mode in QSslConfiguration to QSslSocket::VerfifyNone. The default mode isAutoVerifyPeer. The description on QtAssistant is:

enum QSslSocket::PeerVerifyMode

Describes the peer verification modes for QSslSocket.The default mode is AutoVerifyPeer, which selects an appropriatemode depending on the socket’s QSocket::SslMode.

Constant Value Description
QSslSocket::VerifyNone 0 QSslSocket willnot request a certificate from the peer. You can set this mode ifyou are not interested in the identity of the other side of theconnection. The connection will still be encrypted, and your socketwill still send its local certificate to the peer if it’srequested.
QSslSocket::QueryPeer 1 QSslSocket willrequest a certificate from the peer, but does not require thiscertificate to be valid. This is useful when you want to displaypeer certificate details to the user without affecting the actualSSL handshake. This mode is the default for servers.
QSslSocket::VerifyPeer 2 QSslSocket willrequest a certificate from the peer during the SSL handshake phase,and requires that this certificate is valid. Onfailure, QSslSocket willemit theQSslSocket::sslErrors()signal. This mode is the default for clients.
QSslSocket::AutoVerifyPeer 3 QSslSocket willautomatically use QueryPeer for server sockets and VerifyPeer forclient sockets.

This enum was introduced or modified in Qt 4.4.

See also QSslSocket::peerVerifyMode().

       manager= new QNetworkAccessManager;
       QNetworkRequest request;

       QString url = tr("https://username:[email protected]%1%2").arg(curEnb.enbIp).arg(cgiPathMap["ENABLESSH"]);
       request.setUrl(QUrl(url));

       QSslConfiguration config =QSslConfiguration::defaultConfiguration();
       config.setProtocol(QSsl::TlsV1);
       config.setPeerVerifyMode(QSslSocket::VerifyNone);
       request.setSslConfiguration(config);

       if(enableDebug)
       {
           logTab->append(tr("QNetworkRequest::Attribute"));
           parseNetRequestAttribute(&request);
       }

       reply = manager->get(request);
       if(enableDebug)
       {
           logTab->append(tr("GET%1").arg(reply->url().toString()));
       }

       connect(manager, SIGNAL(finished(QNetworkReply*)), this,SLOT(onNetManagerFinished(QNetworkReply*)));
       connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this,SLOT(onNetReplyError(QNetworkReply::NetworkError)));
       connect(reply, SIGNAL(sslErrors(QList&)), this,SLOT(onNetReplySshErrors(QList&)));

  1. Default getting SslHandshakeFailedError with invoking https request how debug it?

    Hello
    my Qt client give me SslHandshakeFailedError error’s , how can i know what exactly whent wrong , i was reading about QNetworkReply::sslErrors but i have no idea how to invoke this .
    more info :
    i have simple application that making https request (my case facebook api) untill today every thing was working fine since today my main development pc give me this errors from ssl global error is SslHandshakeFailedError :
    The issuer certificate of a locally looked up certificate could not be found
    The root CA certificate is not trusted for this purpose

    but when i run the code in other pc every thing is working fine , how can i know which side is blocking me if this is the problem , maybe its something else …

    Last edited by umen; 3rd May 2011 at 13:10.


Installing a Secure Sockets Layer (SSL) certificate on your WordPress site enables it to use HTTPS to ensure secure connections. Unfortunately, there are a variety of things that can go wrong in the process of confirming a valid SSL certificate and making a connection between your site’s server and a visitor’s browser.

If you’ve encountered an “SSL Handshake Failed” error message and are confused as to what it means, you’re not alone. It’s a common error that doesn’t tell you much on its own. While this can be a frustrating experience, the good news is that there are simple steps you can take to resolve the issue.

In this post, we’ll explain what the SSL Handshake Failed error is and what causes it. Then we’ll provide you with several methods you can use to fix it.

Let’s get started!

An Introduction to the SSL Handshake

Before we dig deeper into what causes a TLS or SSL handshake failure, it’s helpful to understand what the TLS/SSL handshake is. Secure Sockets Layer (SSL) and Transport Layer Security (TLS) are protocols used to authenticate data transfers between servers and external systems such as browsers.

SSL certificates are needed in order to secure your website using HTTPS. We won’t get too in-depth about the difference between TLS vs SSL since it’s a minor one. The terms are often used interchangeably, so for simplicity’s sake, we’ll use “SSL” to refer to both.

With that out of the way, an SSL handshake is the first step in the process of establishing an HTTPS connection. To authenticate and establish the connection, the user’s browser and the website’s server must go through a series of checks (the handshake), which establish the HTTPS connection parameters.

Let us explain: the client (typically the browser) sends a request for a secure connection to the server. After the request is sent, the server sends a public key to your computer and checks that key against a list of certificates. The computer then generates a key and encrypts it, using the public key sent from the server.

To make a long story short, without the SSL handshake, a secure connection won’t be made. This can pose a significant security risk. Plus, there are a lot of moving parts involved in the process.

That means there are many different opportunities for something to go wrong and cause a handshake failure, or even lead to the “your connection is not private” error, causing visitors to leave.

Confronted with the ‘SSL Handshake Failed’ error? 🤝 Get a grip on how to solve it with these 5 methods ⤵️Click to Tweet

Understanding What Causes SSL Handshake Failures

An SSL Handshake Failure or Error 525 means that the server and browser were unable to establish a secure connection. This can happen for a variety of reasons.

Generally, an Error 525 means that the SSL handshake between a domain using Cloudflare and the origin web server failed:

ssl handshake failed error

However, it’s also important to understand that SSL errors can happen on the client-side or the server-side. Common causes of SSL errors on the client-side include:

  • The wrong date or time on the client device.
  • An error with the browser configuration.
  • A connection that is being intercepted by a third party.

Some server-side causes include:

  • A cipher suite mismatch.
  • A protocol used by the client that isn’t supported by the server.
  • A certificate that is incomplete, invalid, or expired.

Typically, if the SSL handshake fails, the issue can be attributed to something wrong with the website or server and their SSL configurations.

How to Fix the SSL Handshake Failed Error (5 Methods)

There are several potential causes behind the “SSL Handshake Failed” error. So there’s no simple answer when it comes to how you should fix it.

Fortunately, there are a handful of methods you can use to begin exploring potential issues and resolving them one by one. Let’s take a look at five strategies you can use to try and fix the SSL Handshake Failed error.

1. Update Your System Date and Time

Let’s start with one of the more unlikely causes, but one that is incredibly easy to correct if it is the problem: your computer’s clock.

If your system is using the wrong date and time, that may interrupt the SSL handshake. When the system clock is different than the actual time, for example, if it’s set too far into the future, it can interfere with the SSL certificate verification.

Your computer’s clock might have been set incorrectly due to human error or simply due to a glitch in your settings. Whatever the reason, it’s a good idea to check and make sure your system time is correct, and update it if it’s not.

Of course, if your clock is showing the correct information, it’s safe to assume that this isn’t the source of the “SSL Handshake Failed” issue.

2. Check to See If Your SSL Certificate Is Valid

Expiration dates are placed on SSL certificates, to help make sure their validation information remains accurate. Generally, the validity of these certificates lasts for anywhere between six months and two years.

If an SSL certificate is revoked or expired, the browser will detect this and be unable to complete the SSL handshake. If it’s been more than a year or so since you installed an SSL certificate on your website, it might be time to reissue it.

To view the status of your SSL certificate, you can use an SSL certificate checker tool such as the one offered by Qualys:

qualys labs

The SSL Server Test tool on the Qualys website

This tool is both reliable and free to use. All you need to do is input your domain name into the Hostname field, and then click on Submit. Once the checker is done analyzing your site’s SSL configuration, it will present you with some results:

ssl certificate status

The results page of the Qualys SSL checker tool

On this page, you can find out if your certificate is still valid and see if it has been revoked for any reason.

In either case, updating your SSL certificate should resolve the handshake error (and is vital for keeping your site and your WooCommerce store secure).

3. Configure Your Browser for the Latest SSL/TLS Protocol Support

Sometimes the best way to determine the root cause of an issue is by process of elimination. As we mentioned earlier, the SSL handshake failure can often occur due to a browser misconfiguration.

The quickest way to determine whether a particular browser is the problem is to try switching to a different one. This can at least help narrow down the problem. You may also try disabling any plugins and resetting your browser back to its default settings.

Another potential browser-related issue is a protocol mismatch. For example, if the server only supports TLS 1.2, but the browser is only configured for TLS 1.0 or TLS 1.1, there’s no mutually-supported protocol available. This will inevitably lead to an SSL handshake failure.

How you can check to see if this problem is occurring varies based on the browser you’re using. As an example, we’ll look at how the process works in Chrome. First, open your browser and go to Settings > Advanced. This will expand a number of menu options.

Under the System section, click on Open your computer’s proxy settings:

proxy settings

The system settings page in Google Chrome

This will open up a new window. Next, select the Advanced tab. Under the Security section, check to see if the box next to Use TLS 1.2 is selected. If not, check that option:

Fix "ssl handshake failed" error: ssl tls settings

The Internet Properties advanced settings in Windows

It’s also recommended that you uncheck the boxes for SSL 2.0 and SSL 3.0.

The same applies to TLS 1.0 and TLS 1.1 since they are being phased out. When you’re done, click on the OK button, and check to see if the handshake error has been resolved.

Note that if you’re using Apple Safari or Mac OS there isn’t an option to enable or disable SSL protocols. TLS 1.2 is automatically enabled by default. If you’re using Linux, you can refer to the Red Hat guide on TLS hardening.

4. Verify That Your Server Is Properly Configured to Support SNI

It’s also possible that the SSL handshake failure is being caused by improper Server Name Indication (SNI) configuration. The SNI is what enables a web server to securely host several TLS certificates for one IP address.

Each website on a server has its own certificate. However, if the server isn’t SNI-enabled, that can result in an SSL handshake failure, because the server may not know which certificate to present.

There are a few ways to check and see whether a site requires SNI. One option is to use Qualys’ SSL Server Test, which we discussed in the previous section. Input your site’s domain name, and then click on the Submit button.

On the results page, look for a message that reads “This site works only in browsers with SNI support”:

browser sni support

The summary results page of the Qualys SSL checker tool

Another approach for detecting if a server is using SNI is to browse the server names in the ‘ClientHello’ message. This is a more technical process, but it can offer a lot of information.

It involves checking the extended hello header for a ‘server_name’ field, to see if the correct certifications are presented.

If you’re familiar with using tools such as the OpenSSL toolkit and Wireshark, you might find this method preferable. You can use openssl s_client with and without the -servername option:

# without SNI
 $ openssl s_client -connect host:port 

 # use SNI
 $ openssl s_client -connect host:port -servername host

If you get two different certificates with the same name, it means that the SNI is supported and properly configured.

However, if the output in the returned certificates is different, or the call without SNI cannot establish an SSL connection, it indicates that SNI is required but not correctly configured. Resolving this issue may require switching to a dedicated IP address.

5. Make Sure the Cipher Suites Match

If you still haven’t been able to identify the cause of the SSL handshake failure, it might be due to a cipher suite mismatch. In case you’re unfamiliar with the term, ‘cipher suites’ refer to a set of algorithms, including ones for key exchange, bulk encryption, and message authentication code, that can be used for securing SSL and TLS network connections.

If the cipher suites that a server uses don’t support or match what’s used by Cloudflare, that can result in an “SSL Handshake Failed” error.

When it comes to figuring out whether there is a cipher suite mismatch, Qualys’ SSL Server Test proves yet again to be a useful tool.

When you input your domain and click on Submit, you’ll see a summary analysis page. You can find the cipher information under the Cipher Suites section:

qualys cipher suites

The Cipher Suites section in a Qualys SSL report

You can use this page to discover which ciphers and protocols the server supports. You’ll want to look out for any that display the ‘weak’ status. In addition, this section also details the specific algorithms for the cipher suites.

To correct this issue, you can compare the results against what your browser supports by using the Qualys SSL/TLS Capabilities of Your Browser tool. For more extensive information and guidance about cipher suites, we also recommend checking out the ComodoSSLStore guide.

Confused by the ‘SSL Handshake Failed’ error message? This guide explains what it is and, most importantly, 5 ways to fix it 🙌Click to Tweet

Summary

One of the most perplexing yet common types of SSL-related problems is the “SSL Handshake Failed” error. Dealing with this error can be stressful since it has many potential causes, including both client- and server-side issues.

However, there are some reliable solutions you can use to identify the problem and resolve it. Here are five ways you can use to fix the SSL Handshake Failed error:

  1. Update your system date and time.
  2. Check to see if your SSL certificate is valid (and reissue it if necessary).
  3. Configure your browser to support the latest TLS/SSL versions.
  4. Verify that your server is properly configured to support SNI.
  5. Make sure the cipher suites match.

Ошибка продления лицензии — Метод GetLicense завершился с ошибкой: 6 (SslHandshakeFailedError)

30 сентября истёк срок действия корневого сертификата IdenTrust DST Root CA X3 Let’s Encrypt

Если у вас после 30 сентября появляется ошибка SslHandshakeFailedError обновления лицензии на IP-приёмнике, то, скорее всего, в вашей операционной системе не установлены обновлённые сертификаты. Для проверки пройдите по ссылке на сайт Let’s Encrypt.

Если на странице вы видите предупреждения безопасности, то вам необходимо добавить сертификат ISRG Root X1 в корневые доверенные сертификаты.

Скачать сертификат:

  • страница сертификатов Let’s Encrypt
  • напрямую с сайта Let’s Encrypt
  • с нашего сайта

Следующим шагом необходимо установить сертификат.

Установка сертификата

Открываем скачанный сертификат кликом мыши:

Установка корневого сертификата шаг 1

Жмём установить сертификат…

Установка корневого сертификата шаг 2

Установим для текущего пользователя, жмём далее

Установка корневого сертификата шаг 3

Выбираем «Поместить все сертификаты в следующее хранилище» и нажимаем далее

Установка корневого сертификата шаг 4

Выбираем «Доверенные корневые центры сертификации»

Далее

Готово

Затем повторяем те же шаги для «Локальный компьютер»

На этом установка сертификата закончена.

Перезапуск IP-приёмника

  • Завершаем работу IP-приёмника
  • Удаляем из папки IP-приёмника C:Program Files (x86)NPO PionerIP-приёмник Барьер файлы private.pem и public.pem
  • Запускаем IP-приёмник
  • В настройках на вкладке лицензия, проверяем что лицензия успешна получена

Действительность должна быть «Да», время получения — текущее время.

Если ничего не получилось

Если эта статья не помогла и получить лицензию так и не удалось, вам необходимо обратится в техподдержку.

Понравилась статья? Поделить с друзьями:
  • Как найти сайт на который уже заходил
  • Индекс находится вне границ массива как исправить паскаль
  • Как найти окрестность функции
  • Нашли собаку с клеймом как найти хозяина
  • Что делать если корни светлее чем концы как исправить