Отображение удаленного сертификата SSL детализирует инструменты CLI использования

В Chrome, нажимая на зеленый значок блокировки HTTPS открывает окно с деталями сертификата:

enter image description here

Когда я попробовал то же ЗАВИХРЕНИЕМ, я получил только часть информации:

$ curl -vvI https://gnupg.org
* Rebuilt URL to: https://gnupg.org/
* Hostname was NOT found in DNS cache
*   Trying 217.69.76.60...
* Connected to gnupg.org (217.69.76.60) port 443 (#0)
* TLS 1.2 connection using TLS_DHE_RSA_WITH_AES_128_CBC_SHA
* Server certificate: gnupg.org
* Server certificate: Gandi Standard SSL CA
* Server certificate: UTN-USERFirst-Hardware
> HEAD / HTTP/1.1
> User-Agent: curl/7.37.1
> Host: gnupg.org
> Accept: */*

Какая-либо идея, как получить полную информацию сертификата, формирует инструмент командной строки (ЗАВИХРЕНИЕ или другой)?

200
задан 24 January 2015 в 00:13
11 ответов

Вы должны иметь возможность использовать OpenSSL для своих целей:

echo | openssl s_client -showcerts -servername gnupg.org -connect gnupg.org:443 2>/dev/null | openssl x509 -inform pem -noout -text

Эта команда подключается к желаемому веб-сайту и передает сертификат в формате PEM другой команде openssl, которая считывает и анализирует детали.

(Обратите внимание, что «избыточный» параметр -servername необходим, чтобы заставить openssl выполнить запрос с поддержкой SNI.)

282
ответ дан 16 December 2019 в 22:45

Зависит от того, какую информацию вы хотите, но:

openssl s_client -showcerts -connect gnupg.org:443

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

29
ответ дан 16 December 2019 в 22:45

Чтобы проверить детали сертификата SSL, я использую следующий инструмент командной строки с тех пор, как он стал доступен:

https://github.com/azet/tls_tools

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

Так выглядят первые несколько строк вывода :

$ ./check_certificate_chain.py gnupg.org 443

>> Certificate Chain:

 [+]*       OU=Domain Control Validated, OU=Gandi Standard SSL, CN=gnupg.org
 [+]**      C=FR, O=GANDI SAS, CN=Gandi Standard SSL CA
 [+]***     C=US, ST=UT, L=Salt Lake City, O=The USERTRUST Network, OU=http://www.usertrust.com, CN=UTN-USERFirst-Hardware

>> Certificate Information:

................................................................................
- [Subject]:        OU=Domain Control Validated, OU=Gandi Standard SSL, CN=gnupg.org
- [Issuer]:     C=FR, O=GANDI SAS, CN=Gandi Standard SSL CA
- [Valid from]:     Mar 18 00:00:00 2014 GMT
- [Valid until]:    Mar 18 23:59:59 2016 GMT
- [Authority]:      Is not a CA
- [Version]:        2
- [Serial No.]:     43845251655098616578492338727643475746
- [X.509 Extension Details]:
  -- [x509_authorityKeyIdentifier]:
       keyid:B6:A8:FF:A2:A8:2F:D0:A6:CD:4B:B1:68:F3:E7:50:10:31:A7:79:21 

За этим выводом следует вся цепочка сертификатов с тем же уровнем детализации.

Что мне нравится, это вместо того, чтобы быть ssl-ориентированным инструментом cli, таким как s_client openssl, этот пытается просто выполнять одну работу, которую мы нужно большую часть времени. Конечно, openssl более гибок (то есть также проверяет clientcerts, imap на нечетных портах и ​​т. Д.), Но мне это не всегда нужно.

В качестве альтернативы, если у вас есть время покопаться и настроить или оценить дополнительные функции, есть инструмент большего размера с именем sslyze (не использующий его из-за зависимостей и установки ...)

6
ответ дан 16 December 2019 в 22:45

Я использую для этого сценарий оболочки. Это просто оболочка вокруг команды openssl, которая избавляет меня от запоминания синтаксиса.

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

Может либо запросить локальный файл сертификата или удаленный сервер.

Использование:

$ ssl-cert-info --help
Usage: ssl-cert-info [options]

This shell script is a simple wrapper around the openssl binary. It uses
s_client to get certificate information from remote hosts, or x509 for local
certificate files. It can parse out some of the openssl output or just dump all
of it as text.

Options:

  --all-info   Print all output, including boring things like Modulus and 
               Exponent.

  --alt        Print Subject Alternative Names. These will be typically be 
               additional hostnames that the certificate is valid for.

  --cn         Print commonName from Subject. This is typically the host for 
               which the certificate was issued.

  --debug      Print additional info that might be helpful when debugging this
               script.

  --end        Print certificate expiration date. For additional functionality
               related to certificate expiration, take a look at this script:
               "http://prefetch.net/code/ssl-cert-check".

  --dates      Print start and end dates of when the certificate is valid.

  --file       Use a local certificate file for input.

  --help       Print this help message.

  --host       Fetch the certificate from this remote host.

  --issuer     Print the certificate issuer.

  --most-info  Print almost everything. Skip boring things like Modulus and
               Exponent.

  --option     Pass any openssl option through to openssl to get its raw
               output.

  --port       Use this port when conneting to remote host. If ommitted, port
               defaults to 443.

  --subject    Print the certificate Subject -- typically address and org name.

Examples:

  1. Print a list of all hostnames that the certificate used by amazon.com 
     is valid for.

     ssl-cert-info --host amazon.com --alt
     DNS:uedata.amazon.com
     DNS:amazon.com
     DNS:amzn.com
     DNS:www.amzn.com
     DNS:www.amazon.com

  2. Print issuer of certificate used by smtp.gmail.com. Fetch certficate info
     over port 465.

     ssl-cert-info --host smtp.gmail.com --port 465 --issuer
     issuer= 
         countryName               = US
         organizationName          = Google Inc
         commonName                = Google Internet Authority G2

  3. Print valid dates for the certificate, using a local file as the source of 
     certificate data. Dates are formatted using the date command and display
     time in your local timezone instead of GMT.

     ssl-cert-info --file /path/to/file.crt --dates
     valid from: 2014-02-04 16:00:00 PST
     valid till: 2017-02-04 15:59:59 PST


  4. Print certificate serial number. This script doesn't have a special option
     to parse out the serial number, so will use the generic --option flag to
     pass '-serial' through to openssl.

     ssl-cert-info --host gmail.com --option -serial
     serial=4BF004B4DDC9C2F8

Вы можете получить сценарий здесь: http://giantdorks.org/alain/shell-script-to-check-ssl-certificate-info -like-expiration-date-and-subject /

4
ответ дан 16 December 2019 в 22:45

Простое решение

Это мой повседневный сценарий:

curl --insecure -v https://www.google.com 2>&1 | awk 'BEGIN { cert=0 } /^\* SSL connection/ { cert=1 } /^\*/ { if (cert) print }'

Вывод:

* SSL connection using TLS1.2 / ECDHE_RSA_AES_128_GCM_SHA256
*    server certificate verification SKIPPED
*    server certificate status verification SKIPPED
*    common name: www.google.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: C=US,ST=California,L=Mountain View,O=Google Inc,CN=www.google.com
*    start date: Wed, 24 May 2017 17:39:15 GMT
*    expire date: Wed, 16 Aug 2017 17:13:00 GMT
*    issuer: C=US,O=Google Inc,CN=Google Internet Authority G2
*    compression: NULL
* ALPN, server accepted to use http/1.1
* Connection #0 to host www.google.com left intact
68
ответ дан 16 December 2019 в 22:45

Если вы хотите сделать это в Windows, вы можете используйте PowerShell со следующей функцией:

function Retrieve-ServerCertFromSocket ($hostname, $port=443, $SNIHeader, [switch]$FailWithoutTrust)
{
    if (!$SNIHeader) {
        $SNIHeader = $hostname
    }

    $cert = $null
    try {
        $tcpclient = new-object System.Net.Sockets.tcpclient
        $tcpclient.Connect($hostname,$port)

        #Authenticate with SSL
        if (!$FailWithoutTrust) {
            $sslstream = new-object System.Net.Security.SslStream -ArgumentList $tcpclient.GetStream(),$false, {$true}
        } else {
            $sslstream = new-object System.Net.Security.SslStream -ArgumentList $tcpclient.GetStream(),$false
        }

        $sslstream.AuthenticateAsClient($SNIHeader)
        $cert =  [System.Security.Cryptography.X509Certificates.X509Certificate2]($sslstream.remotecertificate)

     } catch {
        throw "Failed to retrieve remote certificate from $hostname`:$port because $_"
     } finally {
        #cleanup
        if ($sslStream) {$sslstream.close()}
        if ($tcpclient) {$tcpclient.close()}        
     }    
    return $cert
}

Это позволяет вам делать некоторые изящные вещи, например

#Save to file and open 
Retrieve-ServerCertFromSocket www.wrish.com 443 | Export-Certificate -FilePath C:\temp\test.cer ; start c:\temp\test.cer

#Display the cert details
Retrieve-ServerCertFromSocket www.wrish.com 443 | fl subject,*not*,Thumb*,ser*
4
ответ дан 16 December 2019 в 22:45
nmap -p 443 --script ssl-cert gnupg.org

Параметр -p 443 указывает сканировать только порт 443. Если он не указан, будут просканированы все порты, и будут отображены сведения о сертификате для любой найденной службы SSL. - сценарий ssl-cert сообщает обработчику сценариев Nmap запускать только сценарий ssl-cert . Из документа этот сценарий "(r) извлекает сертификат SSL сервера. Объем информации, печатаемой о сертификате, зависит от уровня детализации."

Пример вывода:

Starting Nmap 7.40 ( https://nmap.org ) at 2017-11-01 13:35 PDT
Nmap scan report for gnupg.org (217.69.76.60)
Host is up (0.16s latency).
Other addresses for gnupg.org (not scanned): (null)
rDNS record for 217.69.76.60: www.gnupg.org
PORT    STATE SERVICE
443/tcp open  https
| ssl-cert: Subject: commonName=gnupg.org
| Subject Alternative Name: DNS:gnupg.org, DNS:www.gnupg.org
| Issuer: commonName=Gandi Standard SSL CA 2/organizationName=Gandi/stateOrProvinceName=Paris/countryName=FR
| Public Key type: rsa
| Public Key bits: 2048
| Signature Algorithm: sha256WithRSAEncryption
| Not valid before: 2015-12-21T00:00:00
| Not valid after:  2018-03-19T23:59:59
| MD5:   c3a7 e0ed 388f 87cb ec7f fd3e 71f2 1c3e
|_SHA-1: 5196 ecf5 7aed 139f a511 735b bfb5 7534 df63 41ba

Nmap done: 1 IP address (1 host up) scanned in 2.31 seconds
25
ответ дан 16 December 2019 в 22:45

Если вам нужна только дата истечения срока действия (это не совсем ответ, но 9/10, для чего люди используют детали сертификата Chrome ), вы можете использовать:

echo | openssl s_client -connect google.com:443 2> / dev / null | openssl x509 -noout -enddate

Полезно для сценариев и т. д.

c4urself@eos ~ → which ssl_expiry
ssl_expiry () {
  echo | openssl s_client -connect ${1}:443 2> /dev/null | openssl x509 -noout -enddate
}
c4urself@eos ~ → ssl_expiry google.com
notAfter=Jun 12 16:54:00 2018 GMT
2
ответ дан 16 December 2019 в 22:45
nmap -sV -sC google.com -p 443
3
ответ дан 16 December 2019 в 22:45

Для полноты: если вы установили в своей системе Java 7 или более поздней версии

 keytool -printcert -sslserver $host[:$port]

показывает цепочку (как обслуживаемая) почти со всеми деталями в основном довольно уродливый формат.

Следует ли вам установить Java в вашей системе, я не отвечаю.

6
ответ дан 16 December 2019 в 22:45

Вы также можете попробовать инструмент gnutls-cli из https://www.gnutls.org/:

echo | gnutls-cli serverfault.com

echo | есть чтобы заставить gnutls-cli выйти быстро, вместо того, чтобы ждать ввода со стандартного ввода.

Если вам нужны необработанные данные сертификата (в формате PEM), добавьте --print-cert.

2
ответ дан 5 August 2020 в 12:55

Теги

Похожие вопросы