- Google chrome / chromium
- Mozilla network security services (nss)
- Zabbix
- Вариант 1: создать csr
- Дополнительные примечания
- Квалифицированный сертификат
- Пакет сертификатов haproxy
- Дополнительные примечания
- Подготовка конфигурационных файлов
- Самоподписанный сертификат ssl
- Квалифицированный сертификат
- Пакет сертификатов haproxy
- Дополнительные примечания
Google chrome / chromium
Как уже было сказано, при работе на Linux, Google Chrome использует библиотеку Mozilla Network Security Services (NSS) для выполнения верификации сертификатов.
Корневые CA сертификаты, которые добавил пользователь, хранятся в файле ~/.pki/nssdb/cert9.db, их можно просмотреть командой:
certutil -L -d ~/.pki/nssdb
Поскольку Chrome не может удалить сертификаты из хранилища NSS, то если вы отключите некоторые из них в настройках веб браузера (Privacy and security → Manage certificates → Authorities), то в том же файле, где хранятся добавленные пользователем корневые CA сертификаты, будут сохранены изменения о полномочиях отключённого сертификата:
Используемые в Google Chrome / Chromium корневые CA сертификаты в Linux можно посмотреть следующим причудливым способом:
1. Найдите расположение файла libnssckbi.so (как было сказано в предыдущем разделе, в нём NSS хранит доверенные корневые сертификаты):
locate libnssckbi.so
Примеры расположений этого файла:
- /usr/lib/libnssckbi.so
- /usr/lib/x86_64-linux-gnu/nss/libnssckbi.so
2. Теперь выполните команду вида:
ln -s /ПУТЬ/ДО/libnssckbi.so ~/.pki/nssdb
Например:
ln -s /usr/lib/x86_64-linux-gnu/nss/libnssckbi.so ~/.pki/nssdb
2. Затем запустите команду:
certutil -L -d sql:$HOME/.pki/nssdb/ -h 'Builtin Object Token'
Вы увидите доверенные корневые сертификаты, которые использует Google Chrome в Linux.
Также вы можете просмотреть корневые CA сертификаты в настройках браузера:
Конфиденциальность и безопасность (выбрать «Ещё») → Настроить сертификаты → Центры сертификации, на английском это Privacy and security → Manage certificates → Authorities.
Mozilla network security services (nss)
Network Security Services (NSS) это набор библиотек, разработанных для поддержки кросс-платформенной разработки защищенных клиентских и серверных приложений. Приложения построенные с использование NSS могут использовать SSL v2 и v3, TLS, PKCS#5, PKCS#7, PKCS#11, PKCS#12, S/MIME, сертификаты X.509 v3 и другие стандарты обеспечения безопасности.
В отличие от OpenSSL, NSS использует файлы базы данных в качестве хранилища сертификатов.
NSS начинается с жёстко закодированного списка доверенных сертификатов CA внутри файла libnssckbi.so. Этот список можно просмотреть из любого приложения, использующего NSS, способного отображать (и манипулировать) хранилищем доверенных сертификатов, например, Chrome-совместимые или Firefox-совместимые браузеры.
Некоторые приложения, использующие библиотеку NSS, используют хранилище сертификатов, отличное от рекомендованного. Собственный Firefox от Mozilla является ярким примером этого.
В вашем дистрибутиве скорее всего уже установлен пакет NSS, в некоторых дистрибутивах он называется libnss3 (Debian и производные) в некоторых — nss (Arch Linux, Gentoo и производные).
Если вы хотите просматривать и изменять хранилища сертификатов NSS, то понадобиться утилита certutil. В Arch Linux эта утилита входит в пакет nss и, следовательно, предустановлена в Arch Linux. А в Debian и производные установка делается так:
sudo apt install libnss3-tools
Zabbix
Скрипт ssl-check-revoc.sh может проверять сертификаты не только из консоли, он также вполне подходит в качестве чекера для Zabbix, поэтому всю грязную работу по отслеживанию попадания сертификатов в список отзыва можно поручить системе мониторинга.
Заходим в конфиг Zabbix /etc/zabbix/zabbix_server.conf и смотрим, где лежат скрипты для внешних проверок:
ExternalScripts=/etc/zabbix/externalscripts
Копируем в этот каталог наш скрипт и рестартуем Zabbix:
sudo cp ssl-check-revoc.sh /etc/zabbix/externalscripts/
sudo systemctl restart zabbix-serverЗаходим в веб-интерфейс и создаём шаблон (Configuration >> Templates >> Create template). В качестве имени шаблона указываем «Template SSL Checking». Затем внутри шаблона создаём элемент данных (Item) «SSL Certificate in Revocation List», в качестве ключа указываем «ssl-check-revoc.sh[{HOST.
Также понадобятся два триггера:
1. Для сигнализации отзыва сертификата «Certificate for domain {HOST.NAME} is in revocation list»Expression: “{Template Custom SSL Checking:ssl-check-revoc.sh[{HOST.NAME}].last()}=1”
2. Для сигнализации об ошибке на случай, если что-то пойдёт не так (например возникнут проблемы с CLR-сервером и т.п.) «Error to check certificate for domain {HOST.NAME}»Expression: “{Template Custom SSL Checking:ssl-check-revoc.sh[{HOST.NAME}].last()}=2”
Не забываем в экшенах (Configuration >> Actions) настроить способ оповещения в случае срабатывания триггеров.
Теперь осталось создать хосты, сертификаты которых будем регулярно проверять (Configuration >> Hosts >> Create host). На вкладке Templates прилинковываем наш темплейт «Template SSL Checking».
И всё! Можно спать спокойно: если SSL-сертификат вашего домена по какой-либо причине попадёт в список отозванных, Zabbix сразу же вам сообщит.
Вариант 1: создать csr
Первое, что нужно сделать, – это создать 2048-битную пару ключей RSA локально. Эта пара будет содержать как ваш закрытый, так и открытый ключ. Вы можете использовать инструмент Java key или другой инструмент, но мы будем работать с OpenSSL.
Чтобы создать открытый и закрытый ключ с запросом на подпись сертификата (CSR), выполните следующую команду OpenSSL:
openssl req –out certificatesigningrequest.csr -new -newkey rsa:2048 -nodes -keyout privatekey.key
Что эта команда означает:
openssl– активирует программное обеспечение OpenSSLreq– указывает, что мы хотим CSR–out– указывает имя файла, в котором будет сохранен ваш CSR. У нас в примере этоcertificatesigningrequest.csr–new –newkey– создать новый ключrsa:2048– cгенерировать 2048-битный математический ключ RSA–nodes– нет DES, то есть не шифровать закрытый ключ в PKCS#12 файл–keyout– указывает домен, для которого вы генерируете ключ
Далее ваша система должна запустить текстовую анкету для заполнения, которую мы описывали в таблице выше:
Country Name (2 letter code) [AU]: State or Province Name (full name) [Some-State]: Locality Name (eg, city) []: Organization Name (eg, company) [Internet Widgits Pty Ltd]: Organizational Unit Name (eg, section) []: Common Name (e.g. server FQDN or YOUR name) []: Email Address []:
После завершения работы программы вы сможете найти файл CSR в вашем рабочем каталоге. Запрос на подпись сертификата, сгенерированный с помощью OpenSSL, всегда будет иметь формат файла .csr. Чтобы найти в папке все файлы этого формата используйте команду
ls *.csr
Тут будет список всех сертификатов, останется только найти тот, что мы только что сгенерировали.
Также вы можете открыть файл .csr в текстовом редакторе, например nano, чтобы просмотреть сгенерированный буквенно-цифровой код.
sudo nano your_domain.csr
После того, как вы сгенерировали CSR с парой ключей, сложно увидеть, какую информацию она содержит, поскольку она не будет в удобочитаемом формате. Вы можете легко декодировать CSR на своем сервере, используя следующую команду OpenSSL:
openssl req -in server.csr -noout -text
Далее можно декодировать CSR и убедиться, что он содержит правильную информацию о вашей организации, прежде чем он будет отправлен в центр сертификации. В Интернете существует множество CSR-декодеров, которые могут помочь вам сделать то же самое, просто скопировав содержимое файла CSR, например sslshopper.
Дополнительные примечания
Вы можете использовать веб-браузер вместо curl для проверки локально сохраненного сертификата, но это не очень удобно.
Я отключил эфемерные комплекты алгоритмов DH, но вы можете указать файл параметров DH для использования.
Вы можете использовать openssl s_server для обслуживания файлов по сети, но это просто еще один лакомый кусочек.
Проверьте код возврата (он отличается от кода выхода), так как он четко покажет, что с предоставленными промежуточными сертификатами что-то не так.
Код возврата не является кодом выхода.
Коды возврата описаны на странице руководства verify.
0 X509_V_OK: ok
the operation was successful.
2 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: unable to get issuer certificate
the issuer certificate of a looked up certificate could not be found. This normally means the list of trusted certificates is not complete.
3 X509_V_ERR_UNABLE_TO_GET_CRL: unable to get certificate CRL
the CRL of a certificate could not be found.
4 X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: unable to decrypt certificate's signature
the certificate signature could not be decrypted. This means that the actual signature value could not be determined rather than it not matching the expected value, this is only meaningful for RSA
keys.
5 X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: unable to decrypt CRL's signature
the CRL signature could not be decrypted: this means that the actual signature value could not be determined rather than it not matching the expected value. Unused.
6 X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: unable to decode issuer public key
the public key in the certificate SubjectPublicKeyInfo could not be read.
7 X509_V_ERR_CERT_SIGNATURE_FAILURE: certificate signature failure
the signature of the certificate is invalid.
8 X509_V_ERR_CRL_SIGNATURE_FAILURE: CRL signature failure
the signature of the certificate is invalid.
9 X509_V_ERR_CERT_NOT_YET_VALID: certificate is not yet valid
the certificate is not yet valid: the notBefore date is after the current time.
10 X509_V_ERR_CERT_HAS_EXPIRED: certificate has expired
the certificate has expired: that is the notAfter date is before the current time.
11 X509_V_ERR_CRL_NOT_YET_VALID: CRL is not yet valid
the CRL is not yet valid.
12 X509_V_ERR_CRL_HAS_EXPIRED: CRL has expired
the CRL has expired.
13 X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: format error in certificate's notBefore field
the certificate notBefore field contains an invalid time.
14 X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: format error in certificate's notAfter field
the certificate notAfter field contains an invalid time.
15 X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: format error in CRL's lastUpdate field
the CRL lastUpdate field contains an invalid time.
16 X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: format error in CRL's nextUpdate field
the CRL nextUpdate field contains an invalid time.
17 X509_V_ERR_OUT_OF_MEM: out of memory
an error occurred trying to allocate memory. This should never happen.
18 X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: self signed certificate
the passed certificate is self signed and the same certificate cannot be found in the list of trusted certificates.
19 X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: self signed certificate in certificate chain
the certificate chain could be built up using the untrusted certificates but the root could not be found locally.
20 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: unable to get local issuer certificate
the issuer certificate could not be found: this occurs if the issuer certificate of an untrusted certificate cannot be found.
21 X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: unable to verify the first certificate
no signatures could be verified because the chain contains only one certificate and it is not self signed.
22 X509_V_ERR_CERT_CHAIN_TOO_LONG: certificate chain too long
the certificate chain length is greater than the supplied maximum depth. Unused.
23 X509_V_ERR_CERT_REVOKED: certificate revoked
the certificate has been revoked.
24 X509_V_ERR_INVALID_CA: invalid CA certificate
a CA certificate is invalid. Either it is not a CA or its extensions are not consistent with the supplied purpose.
25 X509_V_ERR_PATH_LENGTH_EXCEEDED: path length constraint exceeded
the basicConstraints pathlength parameter has been exceeded.
26 X509_V_ERR_INVALID_PURPOSE: unsupported certificate purpose
the supplied certificate cannot be used for the specified purpose.
27 X509_V_ERR_CERT_UNTRUSTED: certificate not trusted
the root CA is not marked as trusted for the specified purpose.
28 X509_V_ERR_CERT_REJECTED: certificate rejected
the root CA is marked to reject the specified purpose.
29 X509_V_ERR_SUBJECT_ISSUER_MISMATCH: subject issuer mismatch
the current candidate issuer certificate was rejected because its subject name did not match the issuer name of the current certificate. Only displayed when the -issuer_checks option is set.
30 X509_V_ERR_AKID_SKID_MISMATCH: authority and subject key identifier mismatch
the current candidate issuer certificate was rejected because its subject key identifier was present and did not match the authority key identifier current certificate. Only displayed when the
-issuer_checks option is set.
31 X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: authority and issuer serial number mismatch
the current candidate issuer certificate was rejected because its issuer name and serial number was present and did not match the authority key identifier of the current certificate. Only
displayed when the -issuer_checks option is set.
32 X509_V_ERR_KEYUSAGE_NO_CERTSIGN:key usage does not include certificate signing
the current candidate issuer certificate was rejected because its keyUsage extension does not permit certificate signing.
50 X509_V_ERR_APPLICATION_VERIFICATION: application verification failure
an application specific error. Unused.Квалифицированный сертификат
Выполните простую программу сервера SSL / TLS, используя сертификат SSL, его закрытый ключ и промежуточные сертификаты.
$ openssl s_server -no_dhe -accept 8282 -www -key example.com.key -cert example.com.crt -CAfile example.com.intermediate.crt
Выполните простую клиентскую программу SSL / TLS, чтобы проверить этот сертификат.
CONNECTED(00000003)
---
Certificate chain
0 s:/CN=example.com
i:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
1 s:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
i:/O=Digital Signature Trust Co./CN=DST Root CA X3
2 s:/O=Digital Signature Trust Co./CN=DST Root CA X3
i:/O=Digital Signature Trust Co./CN=DST Root CA X3
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIFGzCCBAOgAwIBAgISA8J1sgvKsx7iOY1ME0atryKhMA0GCSqGSIb3DQEBCwUA
[...]
ncpOI1U724 /U6vTitOoSAHb83qroLAmXl0OF0SBl5xawTSMhAf44UEIvV6x2iJT
Ul9lKA4Qgyrl3tiXrOZu
-----END CERTIFICATE-----
subject=/CN=example.com
issuer=/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 4012 bytes and written 451 bytes
---
---
New, TLSv1/SSLv3, 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: 469596E7A4616EEF91EA3D2344AE9C0FBD4D0E96C4CB0130BC7BCDA7F7DA020E
Session-ID-ctx:
Master-Key: D4DF9C8D2324F51A58EEB5E7D3774F1EE54C9E8E0AB69F7F4EC9E3D3B3A9239992AE832F4C638732B2327ADD35F772CE
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 300 (seconds)
TLS session ticket:
0000 - 66 78 90 a9 98 12 11 40-b8 03 44 58 03 1e 92 32 fx.....@..DX...2
0010 - da 55 0f c7 26 d7 5e 60-94 56 02 4a ba ae c5 16 .U..&.^`.V.J....
0020 - b7 c6 9e 1c ed 3f 3b 2a-16 31 87 10 1b f6 1e 44 .....?;*.1.....D
0030 - e5 b4 b8 5c d5 b7 66 0d-b3 44 1d c3 cd 73 26 14 .....f..D...s&.
0040 - 93 aa 00 f9 32 45 84 e5-bc e4 cf c8 3e 4e f9 b0 ....2E......>N..
0050 - b7 f9 53 5a 0c 36 60 8f-bb 4b 90 20 ef 67 30 21 ..SZ.6`..K. .g0!
0060 - 26 49 83 94 04 e4 81 9d-76 bf 44 96 d3 6f 5e 3b &I......v.D..o^;
0070 - 49 c6 80 f3 ea d5 e8 06-4c db 8b 74 fa ed 7e df I.......L..t..~.
0080 - 85 b5 ae 91 97 e6 72 36-39 f6 e4 6e 9e 9a 6a a1 ......r69..n..j.
0090 - 48 d5 2a ee b1 48 6d fb-4b 91 1e 28 70 cd 07 98 H.*..Hm.K..(p...
00a0 - 2c 66 fa 19 33 2d 15 7f-5c 23 31 ff 38 97 12 13 ,f..3-..#1.8...
Start Time: 1510259115
Timeout : 300 (sec)
Verify return code: 0 (ok)
---Проверьте код возврата – вы можете безопасно использовать этот сертификат.
Используйте подробный вывод для дальнейшей проверки всего процесса.
* Added example.com:8282:127.0.0.1 to DNS cache
* Hostname example.com was found in DNS cache
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to example.com (127.0.0.1) port 8282 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
* CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: /etc/ssl/certs
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
} [5 bytes data]
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
} [512 bytes data]
* TLSv1.2 (IN), TLS handshake, Server hello (2):
{ [94 bytes data]
* TLSv1.2 (IN), TLS handshake, Certificate (11):
{ [3347 bytes data]
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
{ [333 bytes data]
* TLSv1.2 (IN), TLS handshake, Server finished (14):
{ [4 bytes data]
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
} [70 bytes data]
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
} [1 bytes data]
* TLSv1.2 (OUT), TLS handshake, Finished (20):
} [16 bytes data]
* TLSv1.2 (IN), TLS change cipher, Client hello (1):
{ [1 bytes data]
* TLSv1.2 (IN), TLS handshake, Finished (20):
{ [16 bytes data]
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* ALPN, server did not agree to a protocol
* Server certificate:
* subject: CN=example.com
* start date: Oct 28 19:55:12 2021 GMT
* expire date: Jan 26 19:55:12 2021 GMT
* subjectAltName: host "example.com" matched cert's "example.com"
* issuer: C=US; O=Let's Encrypt; CN=Let's Encrypt Authority X3
* SSL certificate verify ok.
} [5 bytes data]
> GET :/ HTTP/1.1
> Host: example.com:8282
> User-Agent: curl/7.55.1
> Accept: */*
>
{ [5 bytes data]
* HTTP 1.0, assume close after body
< HTTP/1.0 200 ok
< Content-type: text/html
<
{ [7670 bytes data]
* Closing connection 0
} [5 bytes data]
* TLSv1.2 (OUT), TLS alert, Client hello (1):
} [2 bytes data]Пакет сертификатов haproxy
После проверки сертификата необходимо создать комплект сертификатов domain.pem, который включает сертификат domain.crt, промежуточные сертификаты domain.intermediate.crt и закрытый ключ domain.key.
Именно в таком порядке.
Там больше ничего нет.
Дополнительные примечания
Вы можете использовать веб-браузер вместо curl для проверки локально сохраненного сертификата, но это не очень удобно.
Я отключил эфемерные комплекты алгоритмов DH, но вы можете указать файл параметров DH для использования.
Вы можете использовать openssl s_server для обслуживания файлов по сети, но это просто еще один лакомый кусочек.
Проверьте код возврата (он отличается от кода выхода), так как он четко покажет, что с предоставленными промежуточными сертификатами что-то не так.
Код возврата не является кодом выхода.
Коды возврата описаны на странице руководства verify.
0 X509_V_OK: ok
the operation was successful.
2 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: unable to get issuer certificate
the issuer certificate of a looked up certificate could not be found. This normally means the list of trusted certificates is not complete.
3 X509_V_ERR_UNABLE_TO_GET_CRL: unable to get certificate CRL
the CRL of a certificate could not be found.
4 X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: unable to decrypt certificate's signature
the certificate signature could not be decrypted. This means that the actual signature value could not be determined rather than it not matching the expected value, this is only meaningful for RSA
keys.
5 X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: unable to decrypt CRL's signature
the CRL signature could not be decrypted: this means that the actual signature value could not be determined rather than it not matching the expected value. Unused.
6 X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: unable to decode issuer public key
the public key in the certificate SubjectPublicKeyInfo could not be read.
7 X509_V_ERR_CERT_SIGNATURE_FAILURE: certificate signature failure
the signature of the certificate is invalid.
8 X509_V_ERR_CRL_SIGNATURE_FAILURE: CRL signature failure
the signature of the certificate is invalid.
9 X509_V_ERR_CERT_NOT_YET_VALID: certificate is not yet valid
the certificate is not yet valid: the notBefore date is after the current time.
10 X509_V_ERR_CERT_HAS_EXPIRED: certificate has expired
the certificate has expired: that is the notAfter date is before the current time.
11 X509_V_ERR_CRL_NOT_YET_VALID: CRL is not yet valid
the CRL is not yet valid.
12 X509_V_ERR_CRL_HAS_EXPIRED: CRL has expired
the CRL has expired.
13 X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: format error in certificate's notBefore field
the certificate notBefore field contains an invalid time.
14 X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: format error in certificate's notAfter field
the certificate notAfter field contains an invalid time.
15 X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: format error in CRL's lastUpdate field
the CRL lastUpdate field contains an invalid time.
16 X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: format error in CRL's nextUpdate field
the CRL nextUpdate field contains an invalid time.
17 X509_V_ERR_OUT_OF_MEM: out of memory
an error occurred trying to allocate memory. This should never happen.
18 X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: self signed certificate
the passed certificate is self signed and the same certificate cannot be found in the list of trusted certificates.
19 X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: self signed certificate in certificate chain
the certificate chain could be built up using the untrusted certificates but the root could not be found locally.
20 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: unable to get local issuer certificate
the issuer certificate could not be found: this occurs if the issuer certificate of an untrusted certificate cannot be found.
21 X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: unable to verify the first certificate
no signatures could be verified because the chain contains only one certificate and it is not self signed.
22 X509_V_ERR_CERT_CHAIN_TOO_LONG: certificate chain too long
the certificate chain length is greater than the supplied maximum depth. Unused.
23 X509_V_ERR_CERT_REVOKED: certificate revoked
the certificate has been revoked.
24 X509_V_ERR_INVALID_CA: invalid CA certificate
a CA certificate is invalid. Either it is not a CA or its extensions are not consistent with the supplied purpose.
25 X509_V_ERR_PATH_LENGTH_EXCEEDED: path length constraint exceeded
the basicConstraints pathlength parameter has been exceeded.
26 X509_V_ERR_INVALID_PURPOSE: unsupported certificate purpose
the supplied certificate cannot be used for the specified purpose.
27 X509_V_ERR_CERT_UNTRUSTED: certificate not trusted
the root CA is not marked as trusted for the specified purpose.
28 X509_V_ERR_CERT_REJECTED: certificate rejected
the root CA is marked to reject the specified purpose.
29 X509_V_ERR_SUBJECT_ISSUER_MISMATCH: subject issuer mismatch
the current candidate issuer certificate was rejected because its subject name did not match the issuer name of the current certificate. Only displayed when the -issuer_checks option is set.
30 X509_V_ERR_AKID_SKID_MISMATCH: authority and subject key identifier mismatch
the current candidate issuer certificate was rejected because its subject key identifier was present and did not match the authority key identifier current certificate. Only displayed when the
-issuer_checks option is set.
31 X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: authority and issuer serial number mismatch
the current candidate issuer certificate was rejected because its issuer name and serial number was present and did not match the authority key identifier of the current certificate. Only
displayed when the -issuer_checks option is set.
32 X509_V_ERR_KEYUSAGE_NO_CERTSIGN:key usage does not include certificate signing
the current candidate issuer certificate was rejected because its keyUsage extension does not permit certificate signing.
50 X509_V_ERR_APPLICATION_VERIFICATION: application verification failure
an application specific error. Unused.Подготовка конфигурационных файлов
Необходимо создать конфигурационный файл для OpenSSL. Создадим файл /root/ca/openssl.cnf, скопируем в него следующее содержимое root-config.txt.Раздел [ca] является обязательным. Здесь мы говорим OpenSSL использовать параметры из раздела [CA_default]:
[ ca ]
#man ca
default_ca = CA_default
Раздел [CA_default] содержит ряд значений по умолчанию:
[ CA_default ]
# Directory and file locations.
dir = /root/ca
certs = $dir/certs
crl_dir = $dir/crl
new_certs_dir = $dir/newcerts
database = $dir/index.txt
serial = $dir/serial
RANDFILE = $dir/private/.rand
# The root key and root certificate.
private_key = $dir/private/ca.key.pem
certificate = $dir/certs/ca.cert.pem
# For certificate revocation lists.
crlnumber = $dir/crlnumber
crl = $dir/crl/ca.crl.pem
crl_extensions = crl_ext
default_crl_days = 30
# SHA-1 is deprecated, so use SHA-2 instead.
default_md = sha256
name_opt = ca_default
cert_opt = ca_default
default_days = 375
preserve = no
policy = policy_strict
Policy_strict будет применяться для всех подписей корневого центра сертификации, и корневой центр сертификации будет использоваться только для создания промежуточных центров сертификации.
[ policy_strict ]
# The root CA should only sign intermediate certificates that match.
# See the POLICY FORMAT section of man ca.
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
Применим policy_loose для всех подписей промежуточных центров серфтификации, так как промежуточные центры сертификации это подписывающие серверы, и клиентские сертификаты могут приходить от различных третьих лиц.
[ policy_loose ]
# Allow the intermediate CA to sign a more diverse range of certificates.
# See the POLICY FORMAT section of the `ca` man page.
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
Параметры из секции [ req ] применяются когда создаются сертификаты или запросы на подписывание сертификатов.
[ req ]
# Options for the `req` tool (`man req`).
default_bits = 2048
distinguished_name = req_distinguished_name
string_mask = utf8only
# SHA-1 is deprecated, so use SHA-2 instead.
default_md = sha256
# Extension to add when the -x509 option is used.
x509_extensions = v3_ca
Секция [ req_distinguished_name ] определяет информацию, которая обычно требуется при запросе на подписывание сертификата. Можно указать некоторые значения по умолчанию.
Самоподписанный сертификат ssl
Это простейший возможный пример, который предназначен для сбоев, поскольку нет способа проверить какой-либо случайный самаподписанный сертификат SSL.
Выполните простую программу сервера SSL / TLS, используя самоподписанный сертификат SSL и его закрытый ключ.
$ openssl s_server -no_dhe -accept 8282 -www -key example.org.key -cert example.org.crt
Выполните простую клиентскую программу SSL / TLS, чтобы проверить этот сертификат.
CONNECTED(00000003)
depth=0 C = PL, ST = pomorskie, O = personal, L = Gdansk, CN = example.org, OU = IT, emailAddress = admin@example.org
verify error:num=18:self signed certificate
verify return:1
depth=0 C = PL, ST = pomorskie, O = personal, L = Gdansk, CN = example.org, OU = IT, emailAddress = admin@example.org
verify return:1
---
Certificate chain
0 s:/C=PL/ST=pomorskie/O=personal/L=Gdansk/CN=example.org/OU=IT/emailAddress=admin@example.org
i:/C=PL/ST=pomorskie/O=personal/L=Gdansk/CN=example.org/OU=IT/emailAddress=admin@example.org
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIFkjCCA3oCCQCza lCDud16jANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMC
[...]
2QZm3C 8jOxDR n1b6bwtrrVl7fD7L0I4iLPDlTBZgzHHibLQbysWzJKQVsuvmbW
QEkCajRYUX0lSHABrIJtgTu5QgJfPOc4Rjzo0LEsoIHonUBiXWc=
-----END CERTIFICATE-----
subject=/C=PL/ST=pomorskie/O=personal/L=Gdansk/CN=example.org/OU=IT/emailAddress=admin@example.org
issuer=/C=PL/ST=pomorskie/O=personal/L=Gdansk/CN=example.org/OU=IT/emailAddress=admin@example.org
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 2361 bytes and written 451 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 4096 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: C1B33BCF1F8A611EE106E7E9D9DED34FD634FFE45C516B716DB14C771F02D32C
Session-ID-ctx:
Master-Key: 22C05CC82AA56345C7E13937A4E7C884A3D6B4CC7C954B54A79C04141CD09DDAF760852D9E31D20900DA20865A42BE52
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 300 (seconds)
TLS session ticket:
0000 - 6c d9 32 c1 a9 7b 97 c7-7d 86 75 49 05 10 3b d8 l.2..{..}.uI..;.
0010 - 9e 2c 6b 26 ac 11 b6 d6-2a 4b 7b de 07 1d 71 b0 .,k&....*K{...q.
0020 - 19 25 66 5b 88 39 ab 51-c8 c6 ad ed 79 c0 15 b2 .%f[.9.Q....y...
0030 - 3f ae db 35 5a b6 95 52-1a a6 34 1e 89 bb dc be ?..5Z..R..4.....
0040 - 54 15 3c 92 c0 55 7e e0-c0 4a 2c dd 6b 8b b3 3d T.<..U~..J,.k..=
0050 - e6 1b 53 3f 4d 30 2f 72-bd 9c 18 0d 3d 62 17 a0 ..S?M0/r....=b..
0060 - 08 a8 32 64 d9 65 06 54-d4 f4 cc 8a 05 8b de 6a ..2d.e.T.......j
0070 - 8c d0 8e a9 9d 68 95 52-ed 71 fa 93 c8 8a b5 a8 .....h.R.q......
0080 - 58 1a 38 47 9d a6 9f 23-f5 c2 42 b6 5f aa 7e a2 X.8G...#..B._.~.
0090 - dc f4 ea 29 d5 8c 1d b6-92 43 4d 09 79 2e 74 1f ...).....CM.y.t.
00a0 - 37 79 2b b8 1a 8a 91 f3-a3 06 c9 4f 54 0e a8 fb 7y ........OT...
Start Time: 1510239128
Timeout : 300 (sec)
Verify return code: 18 (self signed certificate)
---
DONEПроверьте код возврата – вы не можете использовать этот сертификат, не отключив проверку SSL-сертификата.
curl: (60) server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none More details here: http://curl.haxx.se/docs/sslcerts.html curl performs SSL certificate verification by default, using a "bundle" of Certificate Authority (CA) public keys (CA certs). If the default bundle file isn't adequate, you can specify an alternate file using the --cacert option. If this HTTPS server uses a certificate signed by a CA represented in the bundle, the certificate verification probably failed due to a problem with the certificate (it might be expired, or the name might not match the domain name in the URL). If you'd like to turn off curl's verification of the certificate, use the -k (or --insecure) option.
Все как и должно быть.
Квалифицированный сертификат
Выполните простую программу сервера SSL / TLS, используя сертификат SSL, его закрытый ключ и промежуточные сертификаты.
$ openssl s_server -no_dhe -accept 8282 -www -key example.com.key -cert example.com.crt -CAfile example.com.intermediate.crt
Выполните простую клиентскую программу SSL / TLS, чтобы проверить этот сертификат.
CONNECTED(00000003)
---
Certificate chain
0 s:/CN=example.com
i:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
1 s:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
i:/O=Digital Signature Trust Co./CN=DST Root CA X3
2 s:/O=Digital Signature Trust Co./CN=DST Root CA X3
i:/O=Digital Signature Trust Co./CN=DST Root CA X3
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIFGzCCBAOgAwIBAgISA8J1sgvKsx7iOY1ME0atryKhMA0GCSqGSIb3DQEBCwUA
[...]
ncpOI1U724 /U6vTitOoSAHb83qroLAmXl0OF0SBl5xawTSMhAf44UEIvV6x2iJT
Ul9lKA4Qgyrl3tiXrOZu
-----END CERTIFICATE-----
subject=/CN=example.com
issuer=/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 4012 bytes and written 451 bytes
---
---
New, TLSv1/SSLv3, 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: 469596E7A4616EEF91EA3D2344AE9C0FBD4D0E96C4CB0130BC7BCDA7F7DA020E
Session-ID-ctx:
Master-Key: D4DF9C8D2324F51A58EEB5E7D3774F1EE54C9E8E0AB69F7F4EC9E3D3B3A9239992AE832F4C638732B2327ADD35F772CE
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 300 (seconds)
TLS session ticket:
0000 - 66 78 90 a9 98 12 11 40-b8 03 44 58 03 1e 92 32 fx.....@..DX...2
0010 - da 55 0f c7 26 d7 5e 60-94 56 02 4a ba ae c5 16 .U..&.^`.V.J....
0020 - b7 c6 9e 1c ed 3f 3b 2a-16 31 87 10 1b f6 1e 44 .....?;*.1.....D
0030 - e5 b4 b8 5c d5 b7 66 0d-b3 44 1d c3 cd 73 26 14 .....f..D...s&.
0040 - 93 aa 00 f9 32 45 84 e5-bc e4 cf c8 3e 4e f9 b0 ....2E......>N..
0050 - b7 f9 53 5a 0c 36 60 8f-bb 4b 90 20 ef 67 30 21 ..SZ.6`..K. .g0!
0060 - 26 49 83 94 04 e4 81 9d-76 bf 44 96 d3 6f 5e 3b &I......v.D..o^;
0070 - 49 c6 80 f3 ea d5 e8 06-4c db 8b 74 fa ed 7e df I.......L..t..~.
0080 - 85 b5 ae 91 97 e6 72 36-39 f6 e4 6e 9e 9a 6a a1 ......r69..n..j.
0090 - 48 d5 2a ee b1 48 6d fb-4b 91 1e 28 70 cd 07 98 H.*..Hm.K..(p...
00a0 - 2c 66 fa 19 33 2d 15 7f-5c 23 31 ff 38 97 12 13 ,f..3-..#1.8...
Start Time: 1510259115
Timeout : 300 (sec)
Verify return code: 0 (ok)
---Проверьте код возврата – вы можете безопасно использовать этот сертификат.
Используйте подробный вывод для дальнейшей проверки всего процесса.
* Added example.com:8282:127.0.0.1 to DNS cache
* Hostname example.com was found in DNS cache
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to example.com (127.0.0.1) port 8282 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
* CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: /etc/ssl/certs
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
} [5 bytes data]
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
} [512 bytes data]
* TLSv1.2 (IN), TLS handshake, Server hello (2):
{ [94 bytes data]
* TLSv1.2 (IN), TLS handshake, Certificate (11):
{ [3347 bytes data]
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
{ [333 bytes data]
* TLSv1.2 (IN), TLS handshake, Server finished (14):
{ [4 bytes data]
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
} [70 bytes data]
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
} [1 bytes data]
* TLSv1.2 (OUT), TLS handshake, Finished (20):
} [16 bytes data]
* TLSv1.2 (IN), TLS change cipher, Client hello (1):
{ [1 bytes data]
* TLSv1.2 (IN), TLS handshake, Finished (20):
{ [16 bytes data]
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* ALPN, server did not agree to a protocol
* Server certificate:
* subject: CN=example.com
* start date: Oct 28 19:55:12 2021 GMT
* expire date: Jan 26 19:55:12 2021 GMT
* subjectAltName: host "example.com" matched cert's "example.com"
* issuer: C=US; O=Let's Encrypt; CN=Let's Encrypt Authority X3
* SSL certificate verify ok.
} [5 bytes data]
> GET :/ HTTP/1.1
> Host: example.com:8282
> User-Agent: curl/7.55.1
> Accept: */*
>
{ [5 bytes data]
* HTTP 1.0, assume close after body
< HTTP/1.0 200 ok
< Content-type: text/html
<
{ [7670 bytes data]
* Closing connection 0
} [5 bytes data]
* TLSv1.2 (OUT), TLS alert, Client hello (1):
} [2 bytes data]Пакет сертификатов haproxy
После проверки сертификата необходимо создать комплект сертификатов domain.pem, который включает сертификат domain.crt, промежуточные сертификаты domain.intermediate.crt и закрытый ключ domain.key.
Именно в таком порядке.
Там больше ничего нет.
Дополнительные примечания
Вы можете использовать веб-браузер вместо curl для проверки локально сохраненного сертификата, но это не очень удобно.
Я отключил эфемерные комплекты алгоритмов DH, но вы можете указать файл параметров DH для использования.
Вы можете использовать openssl s_server для обслуживания файлов по сети, но это просто еще один лакомый кусочек.
Проверьте код возврата (он отличается от кода выхода), так как он четко покажет, что с предоставленными промежуточными сертификатами что-то не так.
Код возврата не является кодом выхода.
Коды возврата описаны на странице руководства verify.
0 X509_V_OK: ok
the operation was successful.
2 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: unable to get issuer certificate
the issuer certificate of a looked up certificate could not be found. This normally means the list of trusted certificates is not complete.
3 X509_V_ERR_UNABLE_TO_GET_CRL: unable to get certificate CRL
the CRL of a certificate could not be found.
4 X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: unable to decrypt certificate's signature
the certificate signature could not be decrypted. This means that the actual signature value could not be determined rather than it not matching the expected value, this is only meaningful for RSA
keys.
5 X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: unable to decrypt CRL's signature
the CRL signature could not be decrypted: this means that the actual signature value could not be determined rather than it not matching the expected value. Unused.
6 X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: unable to decode issuer public key
the public key in the certificate SubjectPublicKeyInfo could not be read.
7 X509_V_ERR_CERT_SIGNATURE_FAILURE: certificate signature failure
the signature of the certificate is invalid.
8 X509_V_ERR_CRL_SIGNATURE_FAILURE: CRL signature failure
the signature of the certificate is invalid.
9 X509_V_ERR_CERT_NOT_YET_VALID: certificate is not yet valid
the certificate is not yet valid: the notBefore date is after the current time.
10 X509_V_ERR_CERT_HAS_EXPIRED: certificate has expired
the certificate has expired: that is the notAfter date is before the current time.
11 X509_V_ERR_CRL_NOT_YET_VALID: CRL is not yet valid
the CRL is not yet valid.
12 X509_V_ERR_CRL_HAS_EXPIRED: CRL has expired
the CRL has expired.
13 X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: format error in certificate's notBefore field
the certificate notBefore field contains an invalid time.
14 X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: format error in certificate's notAfter field
the certificate notAfter field contains an invalid time.
15 X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: format error in CRL's lastUpdate field
the CRL lastUpdate field contains an invalid time.
16 X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: format error in CRL's nextUpdate field
the CRL nextUpdate field contains an invalid time.
17 X509_V_ERR_OUT_OF_MEM: out of memory
an error occurred trying to allocate memory. This should never happen.
18 X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: self signed certificate
the passed certificate is self signed and the same certificate cannot be found in the list of trusted certificates.
19 X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: self signed certificate in certificate chain
the certificate chain could be built up using the untrusted certificates but the root could not be found locally.
20 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: unable to get local issuer certificate
the issuer certificate could not be found: this occurs if the issuer certificate of an untrusted certificate cannot be found.
21 X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: unable to verify the first certificate
no signatures could be verified because the chain contains only one certificate and it is not self signed.
22 X509_V_ERR_CERT_CHAIN_TOO_LONG: certificate chain too long
the certificate chain length is greater than the supplied maximum depth. Unused.
23 X509_V_ERR_CERT_REVOKED: certificate revoked
the certificate has been revoked.
24 X509_V_ERR_INVALID_CA: invalid CA certificate
a CA certificate is invalid. Either it is not a CA or its extensions are not consistent with the supplied purpose.
25 X509_V_ERR_PATH_LENGTH_EXCEEDED: path length constraint exceeded
the basicConstraints pathlength parameter has been exceeded.
26 X509_V_ERR_INVALID_PURPOSE: unsupported certificate purpose
the supplied certificate cannot be used for the specified purpose.
27 X509_V_ERR_CERT_UNTRUSTED: certificate not trusted
the root CA is not marked as trusted for the specified purpose.
28 X509_V_ERR_CERT_REJECTED: certificate rejected
the root CA is marked to reject the specified purpose.
29 X509_V_ERR_SUBJECT_ISSUER_MISMATCH: subject issuer mismatch
the current candidate issuer certificate was rejected because its subject name did not match the issuer name of the current certificate. Only displayed when the -issuer_checks option is set.
30 X509_V_ERR_AKID_SKID_MISMATCH: authority and subject key identifier mismatch
the current candidate issuer certificate was rejected because its subject key identifier was present and did not match the authority key identifier current certificate. Only displayed when the
-issuer_checks option is set.
31 X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: authority and issuer serial number mismatch
the current candidate issuer certificate was rejected because its issuer name and serial number was present and did not match the authority key identifier of the current certificate. Only
displayed when the -issuer_checks option is set.
32 X509_V_ERR_KEYUSAGE_NO_CERTSIGN:key usage does not include certificate signing
the current candidate issuer certificate was rejected because its keyUsage extension does not permit certificate signing.
50 X509_V_ERR_APPLICATION_VERIFICATION: application verification failure
an application specific error. Unused.