ssl 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!/bin/sh
  2. RESULT=1
  3. CAPATH="/etc/ssl/certs"
  4. DATE_CHECK=0
  5. usage() {
  6. cat <<EOH
  7. USAGE: $(basename "$0") [-t] -u URI
  8. Options:
  9. -u Specify the URI to check
  10. -t Count and print the certificate expiration interval in days
  11. URI Examples:
  12. - tls+smtp://smtp.googlemail.com:submission
  13. - tls+imap://imap.no-log.org:imap
  14. - ssl://imap.free.fr:imaps
  15. - ssl://pop.free.fr:pop3s
  16. - tls+xmpp://jabber.org:xmpp-client
  17. - ssl://www.google.com:https
  18. Return:
  19. print 0 on stdout if the certificate is valid
  20. print 1 on stdout if the certificate is not valid
  21. print the certificate expiration interval in days (only with option -t)
  22. EOH
  23. }
  24. while getopts htu: option ; do
  25. case "${option}" in
  26. h)
  27. usage
  28. exit 1
  29. ;;
  30. t)
  31. DATE_CHECK=1
  32. ;;
  33. u)
  34. URI="${OPTARG}"
  35. ;;
  36. esac
  37. done
  38. if [ -z "${URI}" ]; then
  39. printf "Error: URI not found\n\n" >&2
  40. usage
  41. exit 1
  42. fi
  43. eval $(echo "${URI}" | sed -r -n 's/^(ssl|tls)(\+(.+))?:\/\/([^:]+)(:([^:]+))?$/layer="\1"\nproto="\3"\nhost="\4"\nport="\6"/p')
  44. tls_opts=
  45. if [ "${layer}" = "tls" ] && [ "${proto}" != "" ]; then
  46. tls_opts="$tls_opts -starttls ${proto}"
  47. fi
  48. certs_data=$(mktemp -t "$(basename "$(readlink -f "${0}")")-certs.XXXXXXXX")
  49. errors_log=$(mktemp -t "$(basename "$(readlink -f "${0}")")-errors.XXXXXXXX")
  50. openssl s_client \
  51. -CApath "${CAPATH}" \
  52. -servername "${host}" \
  53. -connect "${host}:${port}" \
  54. ${tls_opts} \
  55. -showcerts < /dev/null 2>"${errors_log}" > "${certs_data}"
  56. if [ $? != 0 ]; then
  57. printf "Error (openssl): %s\n" "$(head -n 2 "${errors_log}" | tr '\n' ',')" >&2
  58. exit 1
  59. fi
  60. if [ "${DATE_CHECK}" = 1 ]; then
  61. cert_enddate="$(sed -n '/BEGIN CERTIFICATE/,/END CERTIFICATE/p' < "${certs_data}" | openssl x509 -text 2>/dev/null | sed -n 's/ *Not After : *//p')"
  62. if [ -z "${cert_enddate}" ]; then
  63. printf "Error: unable to find certificate end date\n" >&2
  64. exit 1
  65. fi
  66. cert_enddate_seconds=$(date '+%s' --date "${cert_enddate}")
  67. now_seconds=$(date '+%s')
  68. diff_seconds=$(( ${cert_enddate_seconds} - ${now_seconds} ))
  69. diff_days=$(( ${diff_seconds} / 3600 / 24 ))
  70. RESULT="${diff_days}"
  71. else
  72. return_code=$(cat "${certs_data}" | sed -r -n 's/^\s*Verify return code: ([0-9]+) (.*)$/\1/p')
  73. if [ "${return_code}" = 0 ]; then
  74. RESULT=0
  75. fi
  76. fi
  77. rm -f "${certs_data}" "${errors_log}"
  78. printf "${RESULT}\n"
  79. exit 0