cert_status 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/bin/bash
  2. function print_cert_info {
  3. local enddate
  4. local subject
  5. local san_str
  6. # Get the wanted informations with OpenSSL.
  7. issuer="$(openssl x509 -noout -issuer -in "$1" | sed -n 's/.*CN = \(.*\)/\1/p')"
  8. enddate="$(openssl x509 -noout -enddate -in "$1" | sed -n 's/notAfter=\(.*$\)/\1/p')"
  9. subject="$(openssl x509 -noout -subject -in "$1" | sed -n 's/.*CN = \([a-z0-9.-]*\)/- \1/p')"
  10. san_str="$(openssl x509 -text -in "$1" | grep 'DNS:')"
  11. echo "Certificate was issued by $issuer"
  12. if [[ "$2" == "expired" ]]; then
  13. echo "Certificate was valid until $enddate"
  14. else
  15. echo "Certificate is valid until $enddate"
  16. fi
  17. echo "Subject Name:"
  18. echo "$subject"
  19. # Display the SAN info only if there is more than one SAN domain.
  20. while IFS=',' read -ra SAN; do
  21. if [[ ${#SAN[@]} -gt 1 ]]; then
  22. echo "Subject Alternative Name:"
  23. for domain in "${SAN[@]}"; do
  24. echo "$domain" | sed -n 's/.*DNS:\([a-z0-9.-]*\)/- \1/p'
  25. done
  26. fi
  27. done <<< "$san_str"
  28. }
  29. echo '##### Certificate status #####'
  30. for cert in /etc/nginx/certs/*/fullchain.pem; do
  31. [[ -e "$cert" ]] || continue
  32. if [[ -e "${cert%fullchain.pem}chain.pem" ]]; then
  33. # Verify the certificate with OpenSSL.
  34. verify=$(openssl verify -CAfile "${cert%fullchain.pem}chain.pem" "$cert" 2>&1)
  35. if [[ $? -eq 0 ]]; then
  36. echo $verify
  37. # Print certificate info.
  38. print_cert_info "$cert"
  39. else
  40. echo "${cert}: EXPIRED"
  41. # Print certificate info.
  42. print_cert_info "$cert" "expired"
  43. fi
  44. else
  45. echo "${cert}: no corresponding chain.pem file, unable to verify certificate"
  46. # Print certificate info.
  47. print_cert_info "$cert"
  48. fi
  49. # Find the .crt files in /etc/nginx/certs which are
  50. # symlinks pointing to the current certificate.
  51. unset symlinked_domains
  52. for symlink in /etc/nginx/certs/*.crt; do
  53. [[ -e "$symlink" ]] || continue
  54. if [[ "$(readlink -f "$symlink")" == "$cert" ]]; then
  55. domain="$(echo "${symlink%.crt}" | sed 's#/etc/nginx/certs/##g')"
  56. symlinked_domains+=("$domain")
  57. fi
  58. done
  59. # Display symlinks pointing to the current cert if there is any.
  60. if [[ ${#symlinked_domains[@]} -gt 0 ]]; then
  61. echo "Certificate is used by the following domain(s):"
  62. for domain in "${symlinked_domains[@]}"; do
  63. echo "- $domain"
  64. done
  65. fi
  66. echo '##############################'
  67. done