Nginx ssl ошибка

I have to add ssl (https) for a website, I was given a SSL.CSR and a SSL.KEY file. I ‘dos2unix’ed them (because they have trailing ^M) and copied them to the server(CSR -> mywebsite.crt, KEY -> mywebsite.key). I did the following modification to nginx.conf:

@@ -60,8 +60,13 @@
        }

     server {
-       listen       80;
+       listen       443;
         server_name  ...;
+       ssl                 on;
+       ssl_certificate     mywebsite.crt;
+       ssl_certificate_key mywebsite.key;
+       ssl_session_cache   shared:SSL:10m;
+       ssl_session_timeout 10m;
        # Set the max size for file uploads to 500Mb

        client_max_body_size 500M;

Error happens when I restart nginx:

nginx: [emerg] PEM_read_bio_X509_AUX("/etc/nginx/mywebsite.crt") failed (SSL: error:0906D06C:PEM routines:PEM_read_bio:no start line:Expecting: TRUSTED CERTIFICATE)

I figure it’s because the first line of mywebsite.crt file contains ‘REQUEST’, so I remove ‘REQUEST’ from the first and last of the lines, and restart nginx again, and hit another error:

nginx: [emerg] PEM_read_bio_X509_AUX("/etc/nginx/mywebsite.crt") failed (SSL: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag error:0D06C03A:asn1 encoding routines:ASN1_D2I_EX_PRIMITIVE:nested asn1 error error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:Field=algorithm, Type=X509_ALGOR error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:Field=signature, Type=X509_CINF error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:Field=cert_info, Type=X509 error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib)

Any idea?

I’m trying to configure HTTPS for nginx on Ubuntu 16.04. I’ve already set it up with listen 443 ssl statements, and told it where to find the certificate and private key files. After that I restarted the server with sudo service nginx restart.

Now when I curl https://my_ip_address, I get the following message:

curl: (35) gnutls_handshake() failed: Handshake failed

I’ve checked the two log files I know about, /var/log/nginx/access.log and /var/log/nginx/error.log; but it doesn’t show any trace of anything from the request.

My question: Does anything get logged when the SSL handshake fails? If so where? In general, how to I troubleshoot problems like this, where there is an error in the SSL protocol before the HTTP request is sent to, or extracted by the server?

EDIT: I got it to work by removing the following lines from my config:

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
ssl_ecdh_curve secp384r1;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;

Update: The ssl_ecdh_curve secp384r1; line seemed to be causing the problem. Without it, everything works fine, but with it, the SSL handshake fails. Curiously, the error message is that there is «no shared cipher». I’m not sure what it does, so I just removed it. I also removed the ssl_stapling stuff because I don’t know what it is for, and it was creating its own error messages


0

2

nginx 1.6.2, самоподписанные сертификаты сервера и клиента, openssl проверку проходят:

$ openssl verify -CAfile server/server.crt client01.crt 
client01.crt: C = RU, ST = Moscow, L = Moscow, O = Companyname, OU = User, CN = etc, emailAddress = support@site.com
error 18 at 0 depth lookup:self signed certificate
OK

А при запросе nginx отвечает ошибкой 400 The SSL certificate error

В логах сервера:

2016/04/22 11:16:20 [info] 1465#0: *35 client SSL certificate verify error: (18:self signed certificate) wh
ile reading client request headers, client: 192.168.2.11, server: _, request: "GET /test HTTP/1.1", host: "
192.168.2.6"                                                                                               
2016/04/22 11:16:20 [debug] 1465#0: *35 http finalize request: 495, "/test?" a:1, c:1                      
2016/04/22 11:16:20 [debug] 1465#0: *35 event timer del: 8: 1461313040230                                  
2016/04/22 11:16:20 [debug] 1465#0: *35 http special response: 495, "/test?"                               
2016/04/22 11:16:20 [debug] 1465#0: *35 http set discard body                                              
2016/04/22 11:16:20 [debug] 1465#0: *35 echo header filter, uri "/test?"                                   
2016/04/22 11:16:20 [debug] 1465#0: *35 xslt filter header                                                 
2016/04/22 11:16:20 [debug] 1465#0: *35 posix_memalign: 0000000001F02580:4096 @16                          
2016/04/22 11:16:20 [debug] 1465#0: *35 HTTP/1.1 400 Bad Request

Настройки nginx:

server {
    listen 443 ssl;
    listen [::]:443 ssl;

    ssl on;
    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.nopass.key;
    ssl_client_certificate /etc/nginx/ssl/ca.crt;
    ssl_verify_client on;

    location {
        proxy_pass  http://192.168.2.6:9080;
    }
}

Я правильно понимаю, что серверу не нравится то, что сертификат самоподписанный? Как разрешить?

Popular browsers like Google Chrome, Mozilla Firefox, etc need SSL for websites.

Therefore, website owners have to migrate their websites from HTTP to HTTPS.

Often wrong migration steps result in an Nginx SSL connection refused error.

At Bobcares, we help customers in setting up Nginx SSL as a part of our Server Management Services.

Today let’s have a deep check on this error and the way our Support Engineers fix it.

What is the Nginx SSL connection refused error?

Have a vague idea about the error? Let’s make it clear.

As we all know, the Hypertext Transport Protocol aka HTTP fetch pages from the server and display on the browser.

HTTP/2 is the new version of the HTTP protocol and offers high transfer speed.

However, due to security reasons, popular browsers discard older protocols and only support HTTP/2 for HTTPS connections.

Usually, the default listening port in the Nginx server is the standard HTTP port 80. But HTTP/2 only supports HTTPS connections, that require port 443 open in the server.

Therefore when the server does not listen to 443, it shows connection refused error.

How do we fix the error?

Usually, the fix for SSL connection refused error involves opening port 443 in the Nginx configuration file. Let’s see how our Support Engineers provide an appropriate fix to this problem.

Firstly, we check the status of port 443 in the server using the netstat command,

netstat -plan | grep :443

On finding it closed, we open the port 443 in the firewall. Here again, different firewalls follow different commands to open a port.

For instance, to open port 443 in iptables, we use the command:

iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Similarly, in the CentOS server, to open port in firewalld, we use,

firewall-cmd --permanent --zone=public --add-port=443/tcp

Next, we edit the Nginx configuration file /etc/nginx/nginx.conf and add,

listen 443 ssl http/2 default_server;
listen [::]:80 default_server;

It will add 443 as the listening port in the Nginx server and thus enables HTTPS connections.
Finally, when Nginx listens on port 443, it looks like,

[root@xxx ~]# netstat -lpan | grep :443
tcp 0 0 1xx.2x.111.23:443 0.0.0.0:* LISTEN 11978/nginx
tcp 0 0 1xx.2x.111.22:443 0.0.0.0:* LISTEN 11978/nginx
tcp 0 0 1xx.2x.111.19:443 0.0.0.0:* LISTEN 11978/nginx

[Still stuck with Nginx SSL errors? We can solve it in a jiffy.]

Conclusion

In short, the Nginx SSL connection refused error mainly occur due to Nginx’s misconfigurations. Today’s write-up showed how our Support Engineers fix the SSL connection refused error in Nginx servers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Недавно, у меня истек сертификат и пришлось заказывать новый и затем устанавливать на хостинг с Nginx. В этом процессе я столкнулся с несколькими проблемами, которые я опишу ниже, может кому то это поможет избежать подобных проблем.
И так первым делом я заказал новый сертификат у провайдера. Мне пообещали что он будет выпущен в течение 3 дней – 7 дней. Но прошло 7 дней а сертификата все нет и нет и каких либо сообщений об ошибках я то же ни получал. Я начал выяснять в чем может быть проблема. Обращение в тех. поддержку провайдера не помогло. Пришлось потратить несколько дней на поиск проблемы. Оказалось что если в доменной зоне существует хотя бы одна DNS запись типа CAA то сертификат может выдать только тот провайдер который прописан в этой записи. Я совсем забыл что год назад я создал эту запись для другого провайдера. В итоге создал новую запись CAA для нового провайдера, и сертификат пришел в течение дня по электронной почте.
Далее все просто, первым делом создадим текстовый файл your_domain.crt, который будет объединять три сертификата (сам SSL-сертификат, корневой и промежуточный сертификаты) в один файл. Поочередно скопируем и вставим в созданный документ каждый сертификат из электронного письма. После вставки всех сертификатов файл должен иметь вид:

-----BEGIN CERTIFICATE-----
#Ваш сертификат#
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
#Промежуточный сертификат#
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
#Корневой сертификат#
-----END CERTIFICATE-----

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

nginx: [emerg] SSL_CTX_use_PrivateKey_file(“/etc/ssl/your_domain.key”) failed (SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch)

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

Получить modulus закрытого ключа (передав его через md5sum) можно следующей командой:

$ sudo openssl rsa -modulus -in /etc/ssl/your_domain.key -noout | md5sum
d41d8cd54f00b204e9800978ecf8427e  -

И сравнить его с modulus из сертификата:

$ sudo openssl x509 -modulus -in /etc/ssl/your_domain.crt -noout | md5sum
f3a2f9186fcdcdf0d2235236f2ee9a26  -

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

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

server {

    listen 443 ssl;

    server_name your_domain.com;
    ssl_certificate /etc/ssl/your_domain.crt;
    ssl_certificate_key /etc/ssl/your_domain.key;
}

Я это обычно не использую более расширенные настройки SSL, но если вы хотите дополнительно оптимизировать работу Nginx HTTPS-сервера, можно внести следующие настройки. SSL-операции задействуют дополнительные ресурсы сервера. Чтобы снизить количество операций, можно повторно использовать параметры SSL-сессий. Они хранятся в кеше SSL-сессий. Можно задать тип кеша (в примере это shared-кеш, разделяемый между всеми рабочими процессами) и его размер в байтах (в 1 Мб кеша помещается около 4000 сессий) с помощью директивы ssl_session_cache. Также можно увеличить таймаут кеша (время, в течение которого клиент повторно использует параметры сессии) директивой ssl_session_timeout: по умолчанию он равен 5 минутам. Можно настроить время работы одного keepalive-соединения с помощью директивы keepalive_timeout.

ssl_session_cache   shared:SSL:10m;

ssl_session_timeout 10m;

keepalive_timeout 70;

Можно дополнительно указать протоколы SSL, которые поддерживает сервер:

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

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

ssl_prefer_server_ciphers on;

Чтобы уменьшить время загрузки страниц у пользователей сайта, нужно разрешить серверу прикреплять OCSP-ответы для валидации сертификата. При этом необходимо указать путь к файлу корневого сертификата и DNS-сервер. Для этого создайте файл ca.crt и скопируйте в него содержимое корневого сертификата. Загрузите этот файл на сервер в директорию, где хранятся ранее созданные файлы. В нашем примере это /etc/ssl/. Затем добавьте в конфигурационном файле в секции server{} строки:

ssl_stapling on;

ssl_trusted_certificate /etc/ssl/ca.crt;

resolver 8.8.8.8;

Ну и в конце правок конечно же не забываем перезагрузить сервер Nginx:

$ sudo /etc/init.d/nginx restart

Была ли вам полезна эта статья?

Понравилась статья? Поделить с друзьями:
  • Ngentask exe ошибка приложения
  • Ng 0853 canon ошибка
  • Nfsc exe ошибка при запуске приложения 0xc000007b
  • Nfs16 ошибка msvcp100 dll
  • Nfs16 ошибка 0xc000007b