Ssl

如何以人類可讀的形式獲取伺服器的 ssl 證書?

  • September 1, 2017

例如,我想了解 encrypted.google.com 的證書何時到期(即Not After日期),以及哪些其他域可能使用它進行身份驗證(主題備用名稱)。

你可以簡單地寫它:

openssl s_client -showcerts -connect encrypted.google.com:443 < /dev/null \
  2> /dev/null | openssl x509 -noout -enddate

-enddate可用於檢索其他欄位的其他選項。-text輸出大部分資訊。

另請參閱keytooljava:

keytool -printcert -sslserver encrypted.google.com:443

如果可能,它將列印整個證書鏈(可能從 Java 證書儲存中檢索到的一些證書)。

使用 openssl 將伺服器的證書列印為文本:

#!/bin/bash
#
# Show server's certificate in a human-readable form.
#
# Usage: $ show-cert HOST [PORT]
#
exec <&- # close stdin to suppress `read:errno=0` from openssl
exec openssl x509 -noout -text \
    -in <(openssl s_client -connect "$1":"${2:-443}" -showcerts)

或者使用 Python 獲取 json 格式的輸出:

#!/usr/bin/env python3
"""Show server's certificate as json.

Usage:
 $ %(prog)s HOST [PORT]
"""
import json
import socket
import ssl
import sys

def getcert(addr, timeout=None):
   """Retrieve server's certificate at the specified address (host, port)."""
   # it is similar to ssl.get_server_certificate() but it returns a dict
   # and it verifies ssl unconditionally, assuming create_default_context does
   with socket.create_connection(addr, timeout=timeout) as sock:
       context = ssl.create_default_context()
       with context.wrap_socket(sock, server_hostname=addr[0]) as sslsock:
           return sslsock.getpeercert()

def main(argv):
   host = argv[1]
   port = int(argv[2]) if len(argv) > 2 else 443
   print(json.dumps(getcert((host, port)), indent=2, sort_keys=True))

if __name__ == "__main__":
   main(sys.argv)

例子:

$ getcert encrypted.google.com | jq -r '.notAfter, .subjectAltName[][1]'
Mar 20 00:00:00 2014 GMT
*.google.com
*.android.com
*.appengine.google.com
*.cloud.google.com
...

最新版本:getcert.py

引用自:https://unix.stackexchange.com/questions/104623