Ssl error unable to verify the first certificate nginx

nginx проблемы с авторизацией по сертификату nginx 1.6.2, самоподписанные сертификаты сервера и клиента, openssl проверку проходят: А при запросе nginx отвечает ошибкой 400 The SSL certificate error В логах сервера: Я правильно понимаю, что серверу не нравится то, что сертификат самоподписанный? Как разрешить? Вот это результата не дало: Работает с ssl_verify_client optional_no_ca; , но […]

Содержание

  1. nginx проблемы с авторизацией по сертификату
  2. Может кому пригодится
  3. Module ngx_http_ssl_module
  4. Example Configuration
  5. Directives
  6. Error Processing
  7. Embedded Variables

nginx проблемы с авторизацией по сертификату

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

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

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

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

Вот это результата не дало:

Работает с ssl_verify_client optional_no_ca; , но результат не тот, что хотелось бы $ssl_client_verify=’FAILED’

Есть возможность получить сертификат от LetsEncrypt?

Перепроверь сертификаты: клиентский должен быть подписан ключом CA:

Если считаешь, что всё ок — покажи их.

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

Может кому пригодится

До этого момента подразумевается, что у вас уже есть nginx с fast cgi и mod ssl и вам нужно исправить (400 Bad Request No required SSL certificate was sent) и ошибки подобные (error 18 at 0 depth lookup:self signed certificate OK ) и ошибок с не достоверным сертификатом без доступа к ресурсу (NET::ERR_CERT_INVALID).

Источник

Module ngx_http_ssl_module

The ngx_http_ssl_module module provides the necessary support for HTTPS.

This module is not built by default, it should be enabled with the —with-http_ssl_module configuration parameter.

Example Configuration

To reduce the processor load it is recommended to

  • set the number of worker processes equal to the number of processors,
  • enable keep-alive connections,
  • enable the shared session cache,
  • disable the built-in session cache,
  • and possibly increase the session lifetime (by default, 5 minutes):

Directives

Syntax: ssl on | off ;
Default:
Context: http , server

This directive was made obsolete in version 1.15.0. The ssl parameter of the listen directive should be used instead.

Syntax: ssl_buffer_size size ;
Default:
Context: http , server

This directive appeared in version 1.5.9.

Sets the size of the buffer used for sending data.

By default, the buffer size is 16k, which corresponds to minimal overhead when sending big responses. To minimize Time To First Byte it may be beneficial to use smaller values, for example:

Syntax: ssl_certificate file ;
Default:
Context: http , server

Specifies a file with the certificate in the PEM format for the given virtual server. If intermediate certificates should be specified in addition to a primary certificate, they should be specified in the same file in the following order: the primary certificate comes first, then the intermediate certificates. A secret key in the PEM format may be placed in the same file.

Since version 1.11.0, this directive can be specified multiple times to load certificates of different types, for example, RSA and ECDSA:

Only OpenSSL 1.0.2 or higher supports separate certificate chains for different certificates. With older versions, only one certificate chain can be used.

Since version 1.15.9, variables can be used in the file name when using OpenSSL 1.0.2 or higher:

Note that using variables implies that a certificate will be loaded for each SSL handshake, and this may have a negative impact on performance.

The value data : $variable can be specified instead of the file (1.15.10), which loads a certificate from a variable without using intermediate files. Note that inappropriate use of this syntax may have its security implications, such as writing secret key data to error log.

It should be kept in mind that due to the HTTPS protocol limitations for maximum interoperability virtual servers should listen on different IP addresses.

Syntax: ssl_certificate_key file ;
Default:
Context: http , server

Specifies a file with the secret key in the PEM format for the given virtual server.

The value engine : name : id can be specified instead of the file (1.7.9), which loads a secret key with a specified id from the OpenSSL engine name .

The value data : $variable can be specified instead of the file (1.15.10), which loads a secret key from a variable without using intermediate files. Note that inappropriate use of this syntax may have its security implications, such as writing secret key data to error log.

Since version 1.15.9, variables can be used in the file name when using OpenSSL 1.0.2 or higher.

Syntax: ssl_ciphers ciphers ;
Default:
Context: http , server

Specifies the enabled ciphers. The ciphers are specified in the format understood by the OpenSSL library, for example:

The full list can be viewed using the “ openssl ciphers ” command.

The previous versions of nginx used different ciphers by default.

Syntax: ssl_client_certificate file ;
Default:
Context: http , server

Specifies a file with trusted CA certificates in the PEM format used to verify client certificates and OCSP responses if ssl_stapling is enabled.

The list of certificates will be sent to clients. If this is not desired, the ssl_trusted_certificate directive can be used.

Syntax: ssl_conf_command name value ;
Default:
Context: http , server

This directive appeared in version 1.19.4.

Sets arbitrary OpenSSL configuration commands.

The directive is supported when using OpenSSL 1.0.2 or higher.

Several ssl_conf_command directives can be specified on the same level:

These directives are inherited from the previous configuration level if and only if there are no ssl_conf_command directives defined on the current level.

Note that configuring OpenSSL directly might result in unexpected behavior.

Syntax: ssl_crl file ;
Default:
Context: http , server

This directive appeared in version 0.8.7.

Specifies a file with revoked certificates (CRL) in the PEM format used to verify client certificates.

Syntax: ssl_dhparam file ;
Default:
Context: http , server

This directive appeared in version 0.7.2.

Specifies a file with DH parameters for DHE ciphers.

By default no parameters are set, and therefore DHE ciphers will not be used.

Prior to version 1.11.0, builtin parameters were used by default.

Syntax: ssl_early_data on | off ;
Default:
Context: http , server

This directive appeared in version 1.15.3.

Enables or disables TLS 1.3 early data.

Requests sent within early data are subject to replay attacks. To protect against such attacks at the application layer, the $ssl_early_data variable should be used.

The directive is supported when using OpenSSL 1.1.1 or higher (1.15.4) and BoringSSL.

Syntax: ssl_ecdh_curve curve ;
Default:
Context: http , server

This directive appeared in versions 1.1.0 and 1.0.6.

Specifies a curve for ECDHE ciphers.

When using OpenSSL 1.0.2 or higher, it is possible to specify multiple curves (1.11.0), for example:

The special value auto (1.11.0) instructs nginx to use a list built into the OpenSSL library when using OpenSSL 1.0.2 or higher, or prime256v1 with older versions.

Prior to version 1.11.0, the prime256v1 curve was used by default.

When using OpenSSL 1.0.2 or higher, this directive sets the list of curves supported by the server. Thus, in order for ECDSA certificates to work, it is important to include the curves used in the certificates.

Syntax: ssl_ocsp on | off | leaf ;
Default:
Context: http , server

This directive appeared in version 1.19.0.

Enables OCSP validation of the client certificate chain. The leaf parameter enables validation of the client certificate only.

For the OCSP validation to work, the ssl_verify_client directive should be set to on or optional .

To resolve the OCSP responder hostname, the resolver directive should also be specified.

Syntax: ssl_ocsp_cache off | [ shared : name : size ];
Default:
Context: http , server

This directive appeared in version 1.19.0.

Sets name and size of the cache that stores client certificates status for OCSP validation. The cache is shared between all worker processes. A cache with the same name can be used in several virtual servers.

The off parameter prohibits the use of the cache.

Syntax: ssl_ocsp_responder url ;
Default:
Context: http , server

This directive appeared in version 1.19.0.

Overrides the URL of the OCSP responder specified in the “Authority Information Access” certificate extension for validation of client certificates.

Only “ http:// ” OCSP responders are supported:

Syntax: ssl_password_file file ;
Default:
Context: http , server

This directive appeared in version 1.7.3.

Specifies a file with passphrases for secret keys where each passphrase is specified on a separate line. Passphrases are tried in turn when loading the key.

Syntax: ssl_prefer_server_ciphers on | off ;
Default:
Context: http , server

Specifies that server ciphers should be preferred over client ciphers when using the SSLv3 and TLS protocols.

Syntax: ssl_protocols [ SSLv2 ] [ SSLv3 ] [ TLSv1 ] [ TLSv1.1 ] [ TLSv1.2 ] [ TLSv1.3 ];
Default:
Context: http , server

Enables the specified protocols.

The TLSv1.1 and TLSv1.2 parameters (1.1.13, 1.0.12) work only when OpenSSL 1.0.1 or higher is used.

The TLSv1.3 parameter (1.13.0) works only when OpenSSL 1.1.1 or higher is used.

Syntax: ssl_reject_handshake on | off ;
Default:
Context: http , server

This directive appeared in version 1.19.4.

If enabled, SSL handshakes in the server block will be rejected.

For example, in the following configuration, SSL handshakes with server names other than example.com are rejected:

Syntax: ssl_session_cache off | none | [ builtin [: size ]] [ shared : name : size ];
Default:
Context: http , server

Sets the types and sizes of caches that store session parameters. A cache can be of any of the following types:

off the use of a session cache is strictly prohibited: nginx explicitly tells a client that sessions may not be reused. none the use of a session cache is gently disallowed: nginx tells a client that sessions may be reused, but does not actually store session parameters in the cache. builtin a cache built in OpenSSL; used by one worker process only. The cache size is specified in sessions. If size is not given, it is equal to 20480 sessions. Use of the built-in cache can cause memory fragmentation. shared a cache shared between all worker processes. The cache size is specified in bytes; one megabyte can store about 4000 sessions. Each shared cache should have an arbitrary name. A cache with the same name can be used in several virtual servers. It is also used to automatically generate, store, and periodically rotate TLS session ticket keys (1.23.2) unless configured explicitly using the ssl_session_ticket_key directive.

Both cache types can be used simultaneously, for example:

but using only shared cache without the built-in cache should be more efficient.

Syntax: ssl_session_ticket_key file ;
Default:
Context: http , server

This directive appeared in version 1.5.7.

Sets a file with the secret key used to encrypt and decrypt TLS session tickets. The directive is necessary if the same key has to be shared between multiple servers. By default, a randomly generated key is used.

If several keys are specified, only the first key is used to encrypt TLS session tickets. This allows configuring key rotation, for example:

The file must contain 80 or 48 bytes of random data and can be created using the following command:

Depending on the file size either AES256 (for 80-byte keys, 1.11.8) or AES128 (for 48-byte keys) is used for encryption.

Syntax: ssl_session_tickets on | off ;
Default:
Context: http , server

This directive appeared in version 1.5.9.

Enables or disables session resumption through TLS session tickets.

Syntax: ssl_session_timeout time ;
Default:
Context: http , server

Specifies a time during which a client may reuse the session parameters.

Syntax: ssl_stapling on | off ;
Default:
Context: http , server

This directive appeared in version 1.3.7.

Enables or disables stapling of OCSP responses by the server. Example:

For the OCSP stapling to work, the certificate of the server certificate issuer should be known. If the ssl_certificate file does not contain intermediate certificates, the certificate of the server certificate issuer should be present in the ssl_trusted_certificate file.

For a resolution of the OCSP responder hostname, the resolver directive should also be specified.

Syntax: ssl_stapling_file file ;
Default:
Context: http , server

This directive appeared in version 1.3.7.

When set, the stapled OCSP response will be taken from the specified file instead of querying the OCSP responder specified in the server certificate.

The file should be in the DER format as produced by the “ openssl ocsp ” command.

Syntax: ssl_stapling_responder url ;
Default:
Context: http , server

This directive appeared in version 1.3.7.

Overrides the URL of the OCSP responder specified in the “Authority Information Access” certificate extension.

Only “ http:// ” OCSP responders are supported:

Syntax: ssl_stapling_verify on | off ;
Default:
Context: http , server

This directive appeared in version 1.3.7.

Enables or disables verification of OCSP responses by the server.

For verification to work, the certificate of the server certificate issuer, the root certificate, and all intermediate certificates should be configured as trusted using the ssl_trusted_certificate directive.

Syntax: ssl_trusted_certificate file ;
Default:
Context: http , server

This directive appeared in version 1.3.7.

Specifies a file with trusted CA certificates in the PEM format used to verify client certificates and OCSP responses if ssl_stapling is enabled.

In contrast to the certificate set by ssl_client_certificate, the list of these certificates will not be sent to clients.

Syntax: ssl_verify_client on | off | optional | optional_no_ca ;
Default:
Context: http , server

Enables verification of client certificates. The verification result is stored in the $ssl_client_verify variable.

The optional parameter (0.8.7+) requests the client certificate and verifies it if the certificate is present.

The optional_no_ca parameter (1.3.8, 1.2.5) requests the client certificate but does not require it to be signed by a trusted CA certificate. This is intended for the use in cases when a service that is external to nginx performs the actual certificate verification. The contents of the certificate is accessible through the $ssl_client_cert variable.

Syntax: ssl_verify_depth number ;
Default:
Context: http , server

Sets the verification depth in the client certificates chain.

Error Processing

The ngx_http_ssl_module module supports several non-standard error codes that can be used for redirects using the error_page directive:

495 an error has occurred during the client certificate verification; 496 a client has not presented the required certificate; 497 a regular request has been sent to the HTTPS port.

The redirection happens after the request is fully parsed and the variables, such as $request_uri , $uri , $args and others, are available.

Embedded Variables

The ngx_http_ssl_module module supports embedded variables:

$ssl_alpn_protocol returns the protocol selected by ALPN during the SSL handshake, or an empty string otherwise (1.21.4); $ssl_cipher returns the name of the cipher used for an established SSL connection; $ssl_ciphers returns the list of ciphers supported by the client (1.11.7). Known ciphers are listed by names, unknown are shown in hexadecimal, for example:

The variable is fully supported only when using OpenSSL version 1.0.2 or higher. With older versions, the variable is available only for new sessions and lists only known ciphers.

The variable is deprecated, the $ssl_client_escaped_cert variable should be used instead.

Prior to version 1.11.6, the variable name was $ssl_client_i_dn .

Prior to version 1.11.6, the variable name was $ssl_client_s_dn .

Prior to version 1.11.7, the “ FAILED ” result did not contain the reason string.

The variable is supported only when using OpenSSL version 3.0 or higher. With older versions, the variable value will be an empty string.

The variable is supported only when using OpenSSL version 1.0.2 or higher. With older versions, the variable value will be an empty string.

The variable is available only for new sessions.

Источник

Open an ssl connection to site

openssl s_client -connect client-cert-missing.badssl.com:443

returns

.
.
.
---
Certificate chain
 0 s:/C=US/ST=California/L=San Francisco/O=BadSSL Fallback. Unknown subdomain or no SNI./CN=badssl-fallback-unknown-subdomain-or-no-sni
   i:/C=US/ST=California/L=San Francisco/O=BadSSL/CN=BadSSL Intermediate Certificate Authority
---
.
.
.
Verify return code: 21 (unable to verify the first certificate)

Even though the intermediate certificate is missing, browsers can still show no problems with https://client-cert-missing.badssl.com:
but tools like curl, java…. will report that they’re unable to find valid certification path to requested target.

To fix, you have two options

  • find and add the intermediate certificate that https://client-cert-missing.badssl.com use to your keystore

    # add to ubuntu keystore
    sudo cp COMODORSADomainValidationSecureServerCA.crt /usr/local/share/ca-certificates/COMODORSADomainValidationSecureServerCA.crt
    sudo update-ca-certificates
    # add to java keystore
    sudo keytool -importcert -alias COMODORSADomainValidationSecureServerCA -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -file COMODORSADomainValidationSecureServerCA.crt
  • Or update your webserver to send the full chain of certificates not just the leaf chain

    https://nginx.org/en/docs/http/configuring_https_servers.html

    Some browsers may complain about a certificate signed by a well-known certificate authority, while other browsers may accept the certificate without issues. This occurs because the issuing authority has signed the server certificate using an intermediate certificate that is not present in the certificate base of well-known trusted certificate authorities which is distributed with a particular browser. In this case the authority provides a bundle of chained certificates which should be concatenated to the signed server certificate. The server certificate must appear before the chained certificates in the combined file:

        $ cat www.example.com.crt bundle.crt > www.example.com.chained.crt
    

    The resulting file should be used in the ssl_certificate directive:

        server {
            listen              443 ssl;
            server_name         www.example.com;
            ssl_certificate     www.example.com.chained.crt;
            ssl_certificate_key www.example.com.key;
            ...
        }
    

Offline

mihmig

 


#1
Оставлено
:

3 октября 2016 г. 13:59:05(UTC)

mihmig

Статус: Активный участник

Группы: Участники

Зарегистрирован: 18.05.2016(UTC)
Сообщений: 112

Во всех примерах для включения авторизации клиента по сертификату требуется указать два параметра:

ssl_client_certificate ca.crt; — файл с доверенными сертификатами CA в формате PEM, которые используются для проверки клиентских сертификатов
ssl_verify_client on; on; — собственно, включение авторизации

Но у нас всё не как у людей — цепочка состоит из 3-х (!) удоверяющих центров…

При указании в параметре ssl_client_certificate любого (одного) сертификата УС из цепочки в логах nginx ошибка:
2016/10/03 11:37:25 [info] 2484#3632: *1 client SSL certificate verify error: (21:unable to verify the first certificate) while reading client request headers, client: 10.255.10.11, server: example.com, request: «GET / HTTP/1.1», host: «example.com»

Гугл подсказал, что нужно указать имя *.pem — файла,
но как из 3-х сертификатов ЦА сформировать файл *.pem (p7b nginx не распознаёт, онлайн сервисы сконвертировать p7b с ГОСТ-овскими сертификатами не могут)…


Вверх


Offline

mihmig

 


#2
Оставлено
:

3 октября 2016 г. 14:47:48(UTC)

mihmig

Статус: Активный участник

Группы: Участники

Зарегистрирован: 18.05.2016(UTC)
Сообщений: 112

Добавил параметр
ssl_verify_depth 4;
результат прежний:

400 Bad Request
The SSL certificate error


nginx/1.10.1

во вложении error.log и nginx.conf
nginx.conf.11013.txt (4kb) загружен 4 раз(а).
error.log (28kb) загружен 5 раз(а).


Вверх


Offline

Aleksandr G*

 


#3
Оставлено
:

3 октября 2016 г. 18:09:19(UTC)

Aleksandr G*

Статус: Активный участник

Группы: Участники

Зарегистрирован: 13.09.2016(UTC)
Сообщений: 126

Сказал(а) «Спасибо»: 8 раз
Поблагодарили: 31 раз в 27 постах

Windows: copy CA1.crt + CA2.crt + CA3.crt BUNDLE.crt
Linux: cat CA1.crt CA2.crt CA3.crt > BUNDLE.crt


Вверх


Offline

mihmig

 


#4
Оставлено
:

4 октября 2016 г. 12:16:23(UTC)

mihmig

Статус: Активный участник

Группы: Участники

Зарегистрирован: 18.05.2016(UTC)
Сообщений: 112

@Aleksandr G*
Проверил Ваш вариант — проблема не исчезла.
Догадываюсь, что это проблема не nginx-а а библиотеки openssl.
Но вот как включить расширенное протоколирование уже для openssl?


Вверх


Offline

marrow

 


#5
Оставлено
:

20 апреля 2017 г. 17:00:56(UTC)

marrow

Статус: Активный участник

Группы: Участники

Зарегистрирован: 14.06.2016(UTC)
Сообщений: 56
Мужчина
Российская Федерация

Сказал «Спасибо»: 4 раз
Поблагодарили: 3 раз в 3 постах

Аналогичная проблема.
mihmig победили проблему?

Так же пробовал объединить сертификат IntermediateCA и RooCA в один файл. Где два сертификата IntermediateCA — УЦ 1 ИС ГУС и от своего УЦ. RootCA — ГУЦ.
И указывал ssl_verify_depth 4 и ssl_verify_depth 3

Результат такой же:
400 Bad Request
The SSL certificate error

Может нам коллеги с КриптоПро помогут.


Вверх


Offline

Дмитрий Пичулин

 


#6
Оставлено
:

20 апреля 2017 г. 17:09:38(UTC)

pd

Статус: Сотрудник

Группы: Администраторы

Зарегистрирован: 16.09.2010(UTC)
Сообщений: 1,314
Откуда: КРИПТО-ПРО

Сказал(а) «Спасибо»: 28 раз
Поблагодарили: 285 раз в 239 постах

Автор: marrow Перейти к цитате

Может нам коллеги с КриптоПро помогут.

Вероятность помощи не будет равна нулю, если ясно и чётко 1) сформулировать задачу 2) описать шаги воспроизведения проблемы.

Знания в базе знаний, поддержка в техподдержке


Вверх

WWW


Offline

marrow

 


#7
Оставлено
:

20 апреля 2017 г. 17:36:41(UTC)

marrow

Статус: Активный участник

Группы: Участники

Зарегистрирован: 14.06.2016(UTC)
Сообщений: 56
Мужчина
Российская Федерация

Сказал «Спасибо»: 4 раз
Поблагодарили: 3 раз в 3 постах

Проблемную задачу описал участник выше — mihmig. Думаю, что он понятно описал.

Я добавлю:
Раньше стоял SSL сертификат от самоподписанного корневого сертификата — всё работало. Выпустил SSL сертификат от Аккредитованного УЦ, объединил сертификаты IntermediateCA и RooCA в один файл. И в конфиге /etc/nginx/conf.d/gost_ssl.conf указал следующее:
# HTTPS server
#
server {
listen 443 ssl;
server_name svs.nucrf.ru;

proxy_set_header Host $host;
# ssl_certificate /usr/local/nginx/svs.nucrf.ru.cer;
ssl_certificate /etc/nginx/keys/svs.nucrf.ru.cer;
ssl_certificate_key engine:gost_capi:svs.nucrf.ru;
ssl_client_certificate /etc/nginx/keys/cert.b64;
# ssl_client_certificate /etc/nginx/keys/zaonucpak2.b64.cer;
# ssl_certificate /etc/nginx/cert.pem;
# ssl_certificate_key /etc/nginx/cert.key;

ssl_verify_client on;
ssl_verify_depth 4;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 15m;
ssl_protocols TLSv1;

В файле cert.b64 указал сертификаты с кодировкой pem — ssl_client_certificate /etc/nginx/keys/cert.b64;
Устанавливает глубину проверки в цепочке клиентских сертификатов — ssl_verify_depth 3

После захожу на сайт, после выбора клиентского сертификата, ошибка — 400 Bad Request The SSL certificate error

Отредактировано пользователем 20 апреля 2017 г. 17:38:47(UTC)
 | Причина: Не указана


Вверх


Offline

marrow

 


#8
Оставлено
:

21 апреля 2017 г. 10:17:12(UTC)

marrow

Статус: Активный участник

Группы: Участники

Зарегистрирован: 14.06.2016(UTC)
Сообщений: 56
Мужчина
Российская Федерация

Сказал «Спасибо»: 4 раз
Поблагодарили: 3 раз в 3 постах

С такой ошибкой никто не сталкивался?


Вверх


Offline

marrow

 


#9
Оставлено
:

21 апреля 2017 г. 15:39:48(UTC)

marrow

Статус: Активный участник

Группы: Участники

Зарегистрирован: 14.06.2016(UTC)
Сообщений: 56
Мужчина
Российская Федерация

Сказал «Спасибо»: 4 раз
Поблагодарили: 3 раз в 3 постах

Решил проблему :). Я доволен.


Вверх


Offline

Дмитрий Пичулин

 


#10
Оставлено
:

24 апреля 2017 г. 10:50:23(UTC)

pd

Статус: Сотрудник

Группы: Администраторы

Зарегистрирован: 16.09.2010(UTC)
Сообщений: 1,314
Откуда: КРИПТО-ПРО

Сказал(а) «Спасибо»: 28 раз
Поблагодарили: 285 раз в 239 постах

Автор: marrow Перейти к цитате

Решил проблему :). Я доволен.

У нас не удалось воспроизвести.

Напишите решение или в чём была ошибка — будет вам благодарность.

Знания в базе знаний, поддержка в техподдержке


Вверх

WWW

Пользователи, просматривающие эту тему

Guest

Быстрый переход
 

Вы не можете создавать новые темы в этом форуме.

Вы не можете отвечать в этом форуме.

Вы не можете удалять Ваши сообщения в этом форуме.

Вы не можете редактировать Ваши сообщения в этом форуме.

Вы не можете создавать опросы в этом форуме.

Вы не можете голосовать в этом форуме.

У меня есть Nextcloud (21.0.3) и Onlyoffice Documents Server (6.3.2.2), установленные на том же сервере без докера. Я использую только nginx в качестве веб-сервера. Сертификат SSL от европейского SSL.

Nextcloud и Сервер документов имеют разные доменные имена -> cloud.xxx.com и office.xxx.com. Однако, если я пытаюсь подключить Сервер документов через приложение Nextcloud Onlyoffice, я получаю следующее сообщение об ошибке: Ошибка при попытке подключения (Ошибка в службе документов: ошибка при загрузке файла документа, который нужно преобразовать.) (версия 6.3.2.2)

Если я открываю cloud.xxx.com в своем браузере, проблем с ssl не возникает.

В файле журнала с сервера документов Onlyoffice говорится:

[2021-08-18T07:56:40.881] [ERROR] nodeJS - error downloadFile:url=https://cloud.xxx.com/apps/onlyoffice/empty?doc=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhY3Rpb24iOiJlbXB0eSJ9.OYLklS-dJKtf0drJmWQgzxPrEWCQwir10jCIM5r_SMc;attempt=3;code:UNABLE_TO_VERIFY_LEAF_SIGNATURE;connect:null;(id=conv_check_363560041_docx)
Error: unable to verify the first certificate
    at TLSSocket.onConnectSecure (_tls_wrap.js:1088:34)
    at TLSSocket.emit (events.js:198:13)
    at TLSSocket._finishInit (_tls_wrap.js:666:8)

Если я запустил openssl s_client -connect cloud.xxx.com:443

CONNECTED(00000003)
depth=0 CN = *.xxx.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 CN = *.xxx.com
verify error:num=21:unable to verify the first certificate
verify return:1
---
Certificate chain
 0 s:CN = *.xxx.com
   i:C = DE, ST = Baden-WC3BCrttemberg, L = Durmersheim, O = EUNETIC GmbH, CN = EuropeanSSL Server CA 2
---
Server certificate
-----BEGIN CERTIFICATE-----
xxxxx
xxxxx
xxxxx
-----END CERTIFICATE-----
subject=CN = *.xxx.com

issuer=C = DE, ST = Baden-WC3BCrttemberg, L = Durmersheim, O = EUNETIC GmbH, CN = EuropeanSSL Server CA 2

---
No client certificate CA names sent
Peer signing digest: SHA256
Peer signature type: RSA-PSS
Server Temp Key: X25519, 253 bits
---
SSL handshake has read 2177 bytes and written 404 bytes
Verification error: unable to verify the first certificate
---
New, TLSv1.2, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: xxxxxxxxxxxxx
    Session-ID-ctx:
    Master-Key: xxxxxxxxxxxxx
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 300 (seconds)
    TLS session ticket:
    xxxxxxxxxxxxx

    Start Time: 1629275069
    Timeout   : 7200 (sec)
    Verify return code: 21 (unable to verify the first certificate)
    Extended master secret: yes

Запустите wget https://cloud.xxx.com:

--2021-08-18 08:28:05--  https://cloud.xxx.com/
Resolving cloud.xxx.com (cloud.xxx.com)... xx.xx.xx.xx
Connecting to cloud.xxx.com (cloud.xxx.com)|xx.xx.xx.xx|:443... connected.
ERROR: cannot verify cloud.xxx.com's certificate, issued by ‘CN=EuropeanSSL Server CA 2,O=EUNETIC GmbH,L=Durmersheim,ST=Baden-W\C3\BCrttemberg,C=DE’:
  Unable to locally verify the issuer's authority.
To connect to cloud.xxx.com insecurely, use `--no-check-certificate'.

Конфигурация NGINX для Nextcloud:

 upstream php-handler {
      server 127.0.0.1:9000;
      # Depending on your used PHP version
      server unix:/var/run/php7.4-fpm.sock;
  }

  server {
      listen 80;
      server_name cloud.xxx.com;
      return 301 https://$server_name$request_uri;
  }

  server {
      listen 443 ssl;
      server_name cloud.xxx.com;

      ssl_certificate     /etc/nginx/ssl/xxx.com.crt;
          ssl_certificate_key /etc/nginx/ssl/xxx.com.key;
          ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
          ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AE>
          ssl_prefer_server_ciphers on;
          ssl_session_cache shared:SSL:10m;

      # Add headers to serve security related headers
      # The always parameter ensures that the header is set for all responses, including internally generated error responses.
      # Before enabling Strict-Transport-Security headers please read into this topic first.
      # https://www.nginx.com/blog/http-strict-transport-security-hsts-and-nginx/

      #add_header Strict-Transport-Security "max-age=15552000; includeSubDomains; preload" always;
      add_header Strict-Transport-Security max-age=63072000;
      add_header X-Content-Type-Options nosniff always;
      add_header X-Frame-Options "SAMEORIGIN" always;
      add_header X-XSS-Protection "1; mode=block" always;
      add_header X-Robots-Tag none always;
      add_header X-Download-Options noopen always;
      add_header X-Permitted-Cross-Domain-Policies none always;
      add_header Referrer-Policy 'no-referrer';

      # Path to the root of your installation
      root /var/www/nextcloud/;

      location = /robots.txt {
          allow all;
          log_not_found off;
          access_log off;
      }

      # The following 2 rules are only needed for the user_webfinger app.
      # Uncomment it if you're planning to use this app.

      #rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
      #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json last;

      location = /.well-known/carddav {
          return 301 $scheme://$host/remote.php/dav;
      }
      location = /.well-known/caldav {
          return 301 $scheme://$host/remote.php/dav;
      }

      # set max upload size
      client_max_body_size 512M;
      fastcgi_buffers 8 4K;                     # Please see note 1
      fastcgi_ignore_headers X-Accel-Buffering; # Please see note 2

      # Disable gzip to avoid the removal of the ETag header
      # Enabling gzip would also make your server vulnerable to BREACH
      # if no additional measures are done. See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=773332
      gzip off;

Я сохранил файл xxx.com.crt в / usr / local / share / ca-Certific / и запустил sudo dpkg-reconfigure ca-сертификаты после того, как wget этого не сделал. покажите мне любые ошибки.

Но в файле журнала с сервера документов Onlyoffice по-прежнему написано: « Ошибка: невозможно проверить первый сертификат ».

Может ли кто-нибудь помочь мне решить эту проблему?

1 ответ

Лучший ответ

Скорее всего, вам не хватает промежуточного сертификата в цепочке сертификатов.

Nginx не поддерживает предоставление нескольких сертификатов, как это делает apache, поэтому вам нужно связать сертификат самостоятельно.

cd /etc/nginx/ssl/
cat xxx.com.crt intermediate.crt > xxx.com-chain.crt

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

Например, сертификаты, выпущенные letsencrypt, нуждаются в двух промежуточных сертификатах в цепочке, поэтому grep '--BEGIN CERTIFICATE--' xxx.com-chain.crt | wc -l приведет к 3


0

boppy
18 Авг 2021 в 17:55

Create Private key for you

Please note the you will be prompted to enter a passphrase, please remember the passphrase you entered for a while. You will need it later.

sudo openssl genrsa -des3 -out udara.com.key 1024

Generated private key is similar to below key.

Create a certificate signing request
sudo openssl req -new -key udara.com.key -out udara.com.csr

You will be prompted for pass phrase, and other details needed to create the certificate. Enter the same passphrase you entered in the previous step.

root@udara-ThinkPad-T530: sudo openssl req -new -key udara.com.key -out udara.com.csr
Enter pass phrase for udara.com.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:LK
State or Province Name (full name) [Some-State]:Western
Locality Name (eg, city) []:COlombo
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Udara Pvt Ltd
Organizational Unit Name (eg, section) []:stratos
Common Name (e.g. server FQDN or YOUR name) []:udara.com
Email Address []:udaraliyanage@gmail.com
Remove the passphrase (Optional)

This step is optional. If passphrase is not removed, you will have to provide pass phrase everytime Nginx is restarted/started.

cp udara.com.key udara.com.key.back
sudo openssl rsa -in udara.com.key.back -out udara.com.key

udara.com.key contains the private key and pass phrase is removed from it.

Self sign the certificate
sudo openssl x509 -req -days 365 -in udara.com.csr -signkey udara.com.key -out udara.com.crt
 Install the keys to Nginx

Create a directory for ssl

	sudo mkdir /et/nginx/ssl

Copy the private key and the signed certificate to the ssl directory.

sudo cp udara.com.crt /etc/nginx/udara.com.crt
sudo cp udara.com.key /etc/nginx/udara.com.key
Configure certificates to Nginx
server {
        listen 443;
        server_name udara.com;

        root /usr/share/nginx/www;
        index index.html index.htm;

        ssl on;
        ssl_certificate /etc/nginx/ssl/udara.com.crt;
        ssl_certificate_key /etc/nginx/ssl/udara.com.key; 
}
Restart Nginx in order to apply the changes
sudo service nginx restart
Test the configurations

Locate the browser to the https://udara.com. You will see a box as below since your browser does not trust your key. Proceed by clicking “I understand the risks”

firefox-ssl

Debug SSL certificate  from the command line.

You can view the certificate using command line as below.

openssl s_client -connect udara.com:443
CONNECTED(00000003)
depth=0 C = US, ST = CA, L = Mountain View, O = WSO2, CN = localhost
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 C = US, ST = CA, L = Mountain View, O = WSO2, CN = localhost
verify error:num=21:unable to verify the first certificate
verify return:1
---
Certificate chain
 0 s:/C=US/ST=CA/L=Mountain View/O=WSO2/CN=localhost
   i:/C=US/ST=CA/L=Mountain View/O=WSO2/CN=localhost
---
Server certificate
-----BEGIN CERTIFICATE-----
MIICNTCCAZ6gAwIBAgIES343gjANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJV
UzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxDTALBgNVBAoM
BFdTTzIxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xMDAyMTkwNzAyMjZaFw0zNTAy
MTMwNzAyMjZaMFUxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwN
TW91bnRhaW4gVmlldzENMAsGA1UECgwEV1NPMjESMBAGA1UEAwwJbG9jYWxob3N0
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUp/oV1vWc8/TkQSiAvTousMzO
M4asB2iltr2QKozni5aVFu818MpOLZIr8LMnTzWllJvvaA5RAAdpbECb+48FjbBe
0hseUdN5HpwvnH/DW8ZccGvk53I6Orq7hLCv1ZHtuOCokghz/ATrhyPq+QktMfXn
RS4HrKGJTzxaCcU7OQIDAQABoxIwEDAOBgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcN
AQEFBQADgYEAW5wPR7cr1LAdq+IrR44iQlRG5ITCZXY9hI0PygLP2rHANh+PYfTm
xbuOnykNGyhM6FjFLbW2uZHQTY1jMrPprjOrmyK5sjJRO4d1DeGHT/YnIjs9JogR
Kv4XHECwLtIVdAbIdWHEtVZJyMSktcyysFcvuhPQK8Qc/E/Wq8uHSCo=
-----END CERTIFICATE-----
subject=/C=US/ST=CA/L=Mountain View/O=WSO2/CN=localhost
issuer=/C=US/ST=CA/L=Mountain View/O=WSO2/CN=localhost
---
No client certificate CA names sent
---
SSL handshake has read 1100 bytes and written 443 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: 061F79D65FD224EDFFC5130BEE77EE37183F1C6AB943315B1B00C64BE6C64DB9
    Session-ID-ctx: 
    Master-Key: 84E05FFF76FF291E0A8FB08981D1CD86407E93B0A1DEC6CD115ACCCFD4514ACC139BCE33D51E73E50F65860A10FAD8CE
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 300 (seconds)
    TLS session ticket:
    0000 - 90 8e 1c dd 0e 56 c5 73-1c 7e 2f dd 21 7a c9 0b   .....V.s.~/.!z..
    0010 - 69 19 e9 7f af b3 74 1d-c1 fc 13 ab 9c c5 15 aa   i.....t.........
    0020 - 8b 15 9d ae 12 0c 1b 4b-97 0a 07 9a 1e 5d 0c cc   .......K.....]..
    0030 - 4c ba 1e 43 09 34 06 55-e9 15 9c be e8 30 94 c4   L..C.4.U.....0..
    0040 - 8d 58 65 4c 19 91 85 09-a7 a5 12 99 03 e5 7c ca   .XeL..........|.
    0050 - 8f c5 cd 71 69 3f 44 76-64 fa 59 ea a5 4e 24 40   ...qi?Dvd.Y..N$@
    0060 - e2 ef 71 11 6d 5a b3 5c-e2 94 4c 79 49 59 2b 1f   ..q.mZ...LyIY+.
    0070 - 07 3d e3 a9 6a a1 8c eb-71 c7 30 35 4c 73 59 80   .=..j...q.05LsY.
    0080 - 74 84 25 b5 b7 cc 17 81-10 01 f3 32 c9 44 3e 19   t.%........2.D>.
    0090 - 93 52 13 65 36 4a 13 65-a4 ff 92 a3 fd a6 3e 95   .R.e6J.e......>.

    Start Time: 1402859008
    Timeout   : 300 (sec)
    Verify return code: 21 (unable to verify the first certificate

Понравилась статья? Поделить с друзьями:
  • Ssl error rx record too long ubuntu
  • Ssl error rx record too long squid
  • Ssl error rx record too long nginx
  • Ssl error rx record too long apache2
  • Ssl error rx malformed alert