Skip to main content

SSL 常用技巧

Check TLS/SSL certificate expiration date

from a website)

DOM="www.cloudcoin.global" 
PORT="443" 
## note echo added ## 
echo | openssl s_client -servername $DOM -connect $DOM:$PORT \
| openssl x509 -noout -dates

output

depth=2 C = IE, O = Baltimore, OU = CyberTrust, CN = Baltimore CyberTrust Root
verify return:1
depth=1 C = US, O = "Cloudflare, Inc.", CN = Cloudflare Inc ECC CA-3
verify return:1
depth=0 C = US, ST = CA, L = San Francisco, O = "Cloudflare, Inc.", CN = cloudcoin.global
verify return:1
DONE
notBefore=Jun  5 00:00:00 2020 GMT
notAfter=Jun  5 12:00:00 2021 GMT
  • s_client : The s_client command implements a generic SSL/TLS client which connects to a remote host using SSL/TLS.
  • -servername $DOM : Set the TLS SNI (Server Name Indication) extension in the ClientHello message to the given value.
  • -connect $DOM:$PORT : This specifies the host ($DOM) and optional port ($PORT) to connect to.
  • x509 : Run certificate display and signing utility.
  • -noout : Prevents output of the encoded version of the certificate.
  • -dates : Prints out the start and expiry dates of a TLS or SSL certificate.

from a PEM encoded certificate file)

openssl x509 -enddate -noout -in /etc/nginx/ssl/www.cyberciti.biz.fullchain.cer

output

notAfter=Dec 29 23:48:42 2020 GMT

Shell script to alert sysadmin

#!/bin/bash
# Purpose: Alert sysadmin/developer about the TLS/SSL cert expiry date in advance
# Author: Vivek Gite {https://www.cyberciti.biz/} under GPL v2.x+
# -------------------------------------------------------------------------------
PEM="/etc/nginx/ssl/letsencrypt/cyberciti.biz/cyberciti.biz.fullchain.cer"
 
# 7 days in seconds 
DAYS="604800" 
 
# Email settings 
_sub="$PEM will expire within $DAYS (7 days)."
_from="system-account@your-dommain"
_to="sysadmin@your-domain"
_openssl="/usr/bin/openssl"
$_openssl x509 -enddate -noout -in "$PEM"  -checkend "$DAYS" | grep -q 'Certificate will expire'
 
# Send email and push message to my mobile
if [ $? -eq 0 ]
then
	echo "${_sub}"
        mail -s "$_sub" -r "$_from" "$_to" <<< "Warning: The TLS/SSL certificate ($PEM) will expire soon on $HOSTNAME [$(date)]"
        # See https://www.cyberciti.biz/mobile-devices/android/how-to-push-send-message-to-ios-and-android-from-linux-cli/ #
        source ~/bin/cli_app.sh
        push_to_mobile "$0" "$_sub. See $_to email for detailed log. -- $HOSTNAME " >/dev/null
fi
Get the CA chain certificate from the website
echo -n | openssl s_client -showcerts -servername some.web.site -connect some.web.site:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > some-web-site_CA.pem

除了使用 openssl 以外,也可以用 Firefox 或 Chrome 手動下載 CA 鏈憑證檔。

顯示憑證檔 *.crt, *.pem 的詳細資訊

憑證檔的內容是由兩字串 -----BEGIN CERTIFICATE----------END CERTIFICATE----- 所包含的亂數組合,要解析其中的憑證資訊,可以使用 openssl 工具:

openssl x509 -text -noout -in my_CA.pem