123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- #!/bin/sh
- # {{{ Variables
- RESULT=1
- CAPATH="/etc/ssl/certs"
- DATE_CHECK=0
- # }}}
- # {{{ usage()
- usage() {
- cat <<EOH
- USAGE: $(basename "$0") [-t] -u URI
- Options:
- -u Specify the URI to check
- -t Count and print the certificate expiration interval in days
- URI Examples:
- - tls+smtp://smtp.googlemail.com:submission
- - tls+imap://imap.no-log.org:imap
- - ssl://imap.free.fr:imaps
- - ssl://pop.free.fr:pop3s
- - tls+xmpp://jabber.org:xmpp-client
- - ssl://www.google.com:https
- Return:
- print 0 on stdout if the certificate is valid
- print 1 on stdout if the certificate is not valid
- print the certificate expiration interval in days (only with option -t)
- EOH
- }
- # }}}
- # {{{ main()
- while getopts htu: option ; do
- case "${option}" in
- h)
- usage
- exit 1
- ;;
- t)
- DATE_CHECK=1
- ;;
- u)
- URI="${OPTARG}"
- ;;
- esac
- done
- if [ -z "${URI}" ]; then
- printf "Error: URI not found\n\n" >&2
- usage
- exit 1
- fi
- eval $(echo "${URI}" | sed -r -n 's/^(ssl|tls)(\+(.+))?:\/\/([^:]+)(:([^:]+))?$/layer="\1"\nproto="\3"\nhost="\4"\nport="\6"/p')
- tls_opts=
- if [ "${layer}" = "tls" ] && [ "${proto}" != "" ]; then
- tls_opts="$tls_opts -starttls ${proto}"
- fi
- certs_data=$(mktemp -t "$(basename "$(readlink -f "${0}")")-certs.XXXXXXXX")
- errors_log=$(mktemp -t "$(basename "$(readlink -f "${0}")")-errors.XXXXXXXX")
- openssl s_client \
- -CApath "${CAPATH}" \
- -servername "${host}" \
- -connect "${host}:${port}" \
- ${tls_opts} \
- -showcerts < /dev/null 2>"${errors_log}" > "${certs_data}"
- if [ $? != 0 ]; then
- printf "Error (openssl): %s\n" "$(head -n 2 "${errors_log}" | tr '\n' ',')" >&2
- exit 1
- fi
- if [ "${DATE_CHECK}" = 1 ]; then
- cert_enddate="$(sed -n '/BEGIN CERTIFICATE/,/END CERTIFICATE/p' < "${certs_data}" | openssl x509 -text 2>/dev/null | sed -n 's/ *Not After : *//p')"
- if [ -z "${cert_enddate}" ]; then
- printf "Error: unable to find certificate end date\n" >&2
- exit 1
- fi
- cert_enddate_seconds=$(date '+%s' --date "${cert_enddate}")
- now_seconds=$(date '+%s')
- diff_seconds=$(( ${cert_enddate_seconds} - ${now_seconds} ))
- diff_days=$(( ${diff_seconds} / 3600 / 24 ))
- RESULT="${diff_days}"
- else
- return_code=$(cat "${certs_data}" | sed -r -n 's/^\s*Verify return code: ([0-9]+) (.*)$/\1/p')
- if [ "${return_code}" = 0 ]; then
- RESULT=0
- fi
- fi
- rm -f "${certs_data}" "${errors_log}"
- printf -- "${RESULT}\n"
- exit 0
- # }}}
- # vim: foldmethod=marker foldlevel=0 foldenable
|