Linux просмотр цепочки сертификатов

showcert: проверяем сертификаты (без боли)

showcert — маленькая CLI утилитка, альтернатива openssl для просмотра сертификатов. Она умеет 1% того, что может openssl, но зато умеет [почти] все, что нужно в обычной админской жизни и даже немного больше чем openssl. И гораздо проще в использовании. Основные функции:

  • Взять сертификат (или цепочку) из stdin, файла(файлов) или из TLS сервиса (HTTPS, POP3S, IMAPS), в том числе через STARTTLS (для SMTP, POP3, IMAP)
  • Проверить валидность сертификата.
  • Проверить «свежесть» сертификата, и если срок действия истекает через N дней — передать это в коде завершения.
  • Распечатать сертификат (цепочку) в краткой форме (только основное), полной, в PEM формате (для сохранения в cert.pem или fullchain.pem).

И все это делается простым, интуитивно-понятным образом, для людей.

Когда я хочу проверить дату истечения, например, почтового сертификата яндекса, немного гуглю, потом сноровисто пишу что-то вроде:

$ echo | openssl s_client -connect mx.yandex.ru:25 -starttls smtp 2>&1 | openssl x509 -noout -dates

Когда я печатаю эту строчку, вспоминаю немало многокоренных слов из флотской службы, а ведь я даже не служил. А теперь, представьте, что мы хотим не просто увидеть дату, а еще и как-то что-то сделать, если до истечения останется меньше 20 дней. как будет выглядеть команда? Мне вообще сложно представить, как это можно автоматизировать через openssl и простые шелл скрипты.

Просмотр сертификатов через showcert

А теперь (после установки: pip3 install showcert ) сравните с:

$ showcert mx.yandex.ru:25
Names: mx.yandex.ru mx.yandex.net
notBefore: 2022-07-25 11:16:45 (15 days old)
notAfter: 2023-01-22 20:59:59 (165 days left)
Issuer: C=BE O=GlobalSign nv-sa CN=GlobalSign RSA OV SSL CA 2018

Ну разве не проще? showcert сам (по номеру порта) догадывается, как начать STARTTLS (но конечно же, это можно переопределить через опцию -t / —starttls, например, -t no или -t imap).

Предупредить о том, что сертификат скоро протухнет? Окей!

$ showcert mx.yandex.ru:25 -qw 200 || echo PROBLEM
mx.yandex.ru:25 expires in 165 days
PROBLEM

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

Проверить https вебсайт? showcert github.com (Несложный синтаксис?)

«Скопировать» fullchain.pem с сервера (взять его и распечатать в PEM):

$ showcert google.com —chain -o pem > fullchain.pem

У меня после этого дампа (не с гугла, а со своего другого сервера) — даже md5 файлов сошелся!

Так же можно посмотреть или проверить один или несколько локальных файлов сертификатов (fullchain.pem или cert.pem).

Можно добавить —chain чтобы увидеть всю цепочку. И ключ -w тоже работает.

Формат вывода сертификатов

По умолчанию ( -o brief ) выводится краткая информация (все, что обычно важно, минимум лишнего). -o full дает полный дамп (как openssl), -o pem даст сертификат в PEM формате (удобно сделать редирект в файл и получить его на диске).

Читайте также:  Ida pro linux debugger

Еще есть удобный формат -o names — просто распечатывает все имена из сертификата, и его вариация -o dnames , о ней ниже.

Сахар для LetsEncrypt

Мы много используем LetsEncrypt, поэтому showcert удобен для этого. На сервере могут быть десятки (а то и сотни) сайтов, у каждого сертификат. Да, certbot renew в теории должен обновлять их, но сайты живые, постоянно разрабатываются, причем разными людьми и с ними иногда происходят разные чудеса. То поменяется DocumentRoot, то появятся правила rewrite/redirect, которые блокируют проверку, то доменное имя куда-то уедет. В общем, обновления иногда фейлятся и сертификаты протухают. А когда сайтов много, что-то проблемное случается регулярно.

Мы используем okerr (статья про okerr на хабре) для мониторинга. Наш собственный open source гибридный мониторинг. Раньше мы использовали скрипт, создавал индикатор типа sslcert для каждого сайта (это тоже не очень удобно, так как сайты ведь иногда и умирают или переезжают на другой сервер). Но с showcert стало еще проще:

Простой приятный способ проверить, что все LetsEncrypt сертификаты еще свежи:

# showcert :le -qw
/etc/letsencrypt/live/example.com/fullchain.pem expires in 19 days
/etc/letsencrypt/live/example.net/fullchain.pem expires in 19 days
# echo $?
2

Команда выше — синоним showcert /etc/letsencrypt/live/*/fullchain.pem -qw , а код :le запомнить проще, чем путь к сертификатам. Ну и код завершения удобен, чтобы использовать его в мониторинге, собственных скриптах. У нас showcert вызывается из okerrupdate/okerrmod, в окерр внешние скрипты проверки цепляются одной строчкой, но если у вас другой мониторинг — тоже сможете легко подцепить showcert.

Если не используете никакой мониторинг, то showcert :le -qw в cron раз в сутки — оповестит заранее о сертификатах, которые своевременно не смогли обновиться, и у вас будет время починить.

Еще одна опция: -o dnames печатает имена через -d, это удобно чтобы скармливать их certbot:

$ showcert -o dnames habr.ru
-d habr.ru -d www.habr.ru

Для двух имен, как у хабра — это не имеет особого смысла, но если у сертификата имен много, и вам нужно пересоздать его — вручную печатать их можно и ошибиться. Проще через showcert получить часть команды и просто использовать ее (или даже использовать сам showcert в команде:

certbot certonly —webroot /var/www/habr `showcert -o dnames habr.ru`

Попробуйте, например, showcert -o dnames google.com .

Заключение

Утилита простая, синтаксис очевидный и простой, не требует запоминания и для большинства частых админских операций — работает замечательно! Пригодна для отслеживания протухающих сертификатов (через openssl это сложнее). Без нее можно обойтись, но с ней проще.

Очень советую попробовать 🙂

Источник

How to Check Certificate with OpenSSL

Learn how to use the openssl command to check various kinds of certificates on Linux systems.

Keeping a tab on your SSL certificates is a crucial part of a sysadmin’s job.

There are various ways to do it. You can use a monitoring service like Checkmk to monitor the certificates or you can use the good old openssl command for this purpose.

In this guide, I’ll explain to you how to use the openssl command to check various certificates on Linux systems.

Читайте также:  Linux для начинающих файловая

Optional: Generating a TLS/SSL Certificate

To demonstrate this guide, I’ll create some keys and certificate files. If you already have these things, you can skip to the next step.

Let’s begin with a private key, use the following command to create a private key:

openssl genrsa -out my_private_key.key 2048

Create private key with openssl

The above command will create a key with the name my_private_key.key file.

Now that you have a private key, create a public key with it:

openssl rsa -in my_private_key.key -pubout > my_public_key.pub

Create public key with openSSL

That’s good, you now have your private and public keys and you can use them to generate a certificate file. It is important to know beforehand that you are generating a self-signed certificate here. This is because using a CA (Certificate Authority) for signing a certificate requires additional costs.

But don’t worry. Your certificate will suffice as you will use it only for demonstration purposes. Use the below command to build your certificate:

openssl req -x509 -new -key my_private_key.key -days 365 -out mycert.pem

The above command will result in a PEM-type certificate file with the name mycert.pem.

Each option here has its meaning. The 365 indicates the period in days for which the certificate will be valid.

Now enter the details for various questions on the prompt:

Country Name (2 letter code) [AU]:IN State or Province Name (full name) [Some-State]: [Name of your state] Locality Name (eg, city) []: [Name of your city] Organization Name (eg, company) [Internet Widgits Pty Ltd]: [Name of your organization] Organizational Unit Name (eg, section) []: Common Name (e.g. server FQDN or YOUR name) []:[Enter a common name here]

You can now see all your files listed in the current directory with the ls command:

List the files

Checking the Status of a Certificate

It is very important to ensure the SSL certificates you are using are not expired or on the verge of being expired. Negligence in this regard can have a devastating impact on the production systems.

Certificate files usually have a .pem or .crt extension. You can use the openssl commands to explore the details of a certificate. For example, the below command gives the details of the certificate you created above:

openssl x509 -in mycert.pem -text -noout

Checking the status of a certificate

You will see a long output printed on your terminal describing various attributes of the certificate as: Version, Serial Number, Signature Algorithm, Issuer, Validity Status, etc.

Similarly, you can use this command with a port with an SSL certificate attached to it. I guess you will have figured out the validity range of our certificate from the above output.

Always use this command when you plan to replace or renew your SSL certificate. This way you are likely to avoid any mistakes in certificate management.

Using OpenSSL to View the Status of a Website’s Certificate

Let me show you how you can use openssl command to verify and check SSL certificate validity for this website www.linuxhandbook.com or a remote system with a fully qualified domain name (FQDN):

openssl s_client -connect linuxhandbook.com:443 2>/dev/null | openssl x509 -noout -dates

Verifying a website

As you can see from the output, the target certificate is valid only for the specified range: May 5, 2022 to May 5, 2023.

Читайте также:  Arch linux mirrorlist generated by reflector

Let’s break down this command:

FREE Uptime Monitoring

  • s_client: This command implements a general SSL/TLS-based client and establishes an SSL/TLS connection to a remote system.
  • -connect host:port: Here, you specify the host and port number to connect to.
  • x509: This command has multiple uses like showing certificate-related information, converting certificates to various other forms, signing certificate requests, etc.

Verifying Information within a Certificate

CER and CRT type files can be used in parallel as both are identical. The openssl command can also be used to verify a Certificate and CSR(Certificate Signing Request).

Verifying a .crt Type Certificate

For verifying a crt type certificate and to get the details about signing authority, expiration date, etc., use the command:

openssl x509 -in certificate.crt -text -noout

Checking a .csr (Certificate Signing Request) type file

You can use the below command to check a csr type file and retrieve the CSR data entered while creating this file:

openssl req -text -noout -verify -in server.csr

Verifying a KEY type file

This is an extra tip for verifying a KEY type file and its consistency:

openssl rsa -in my_private_key.key -check

Working with .pem type Files

In a mega IT setup, you may find thousands of servers out there. They only accept certificates that are formatted in a particular manner. This means if you are using a .pem format for a server that needs .crt format, then you are at a complete loss until you convert them to the desired format.

Technically, there are some commands that you can use to convert certificates and keys to other formats. In this way, you can make them work with different types of formats required by various servers. For e.g., you can convert a DER file (.cer, .crt or .der) to PEM format as:

openssl x509 -inform der -in base-certificate.cer -out target-certificate.pem

To find the expiration date of a .pem type TLS/SSL certificate, the following command is very handy:

openssl x509 -enddate -noout -in /path/of/the/pem/file

Verifying a Public Key

The public key contained in a private key and a certificate must be the same. You can check this with the openssl command as:

openssl x509 -in certificate.pem -noout -pubkey
openssl rsa -in ssl.key -pubout

Verifying a public key

As you can see, the outputs from the above commands are the same.

Conclusion

You have so far seen how to generate keys and certificates, how to change one form to another, and how to verify different types of files.

Keeping knowledge of your certificate status is very important and OpenSSL does a good job here. Also, if you do not want to engage (or mess up) with the command line, you can use downtime monitoring services like Better Uptime to automatically check the certificates.

Источник

Оцените статью
Adblock
detector