summaryrefslogtreecommitdiff
path: root/certexpiry.sh
blob: d7684004108388ec7f90d12ae2df452649ce80da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/bin/bash
set -euo pipefail

# ==== Variables ====
# Output warning if fewer than this number of seconds until expiry
WARNSECONDS=1209600 # Two weeks
# Bash array of host:port combinations to be checked
HOSTSANDPORTS="hostsandports.txt"
# ==== Variables ====

# Loop through all host:port combinations
while read -r HOSTANDPORT ; do

#  echo "DEBUG: HOSTANDPORT: $HOSTANDPORT."

  # Host before colon
  HOST=$(echo "$HOSTANDPORT" | cut -d ":" -f "1")
  # Port after colon, or nothing if no port given (assumes 443 later on)
  PORT=$(echo "$HOSTANDPORT" | cut -s -d ":" -f "2")

#  echo "DEBUG: HOST: $HOST."

  # Assume no STARTTLS (unless special ports later on)
  STARTTLS=""

  if [ "$PORT" = "" ] ; then
    # Assume 443 if no port specified
    PORT=443
  elif [ "$PORT" -eq 25 ] ; then
    # Assume SMTP STARTTLS if port 25
    STARTTLS="-starttls smtp"
  elif [ "$PORT" -eq 143 ] ; then
    # Assume IMAP STARTTLS if port 143
    STARTTLS="-starttls imap"
  fi

#  echo "DEBUG: PORT: $PORT."
#  echo "DEBUG: STARTTLS: $STARTTLS."

  # Try various TLS versions against this host:port to try and get a response
  RETCODE=1
  for PROTOCOL in -tls1_2 -tls1_1 -tls1 ; do
    if [ "$RETCODE" -eq 0 ] ; then
      break
    fi
    set +e
    # Get the "Not After" field for the certificate expiry
    EXPIRYSTRING=$(echo "Q" | openssl s_client $STARTTLS -connect "$HOST:$PORT" -servername "$HOST" "$PROTOCOL" 2> /dev/null | openssl x509 -noout -text 2> /dev/null | grep "Not After" | sed -r 's/\s*Not After : //')
    RETCODE="$?"
    set -e
  done

#  echo "DEBUG: EXPIRYSTRING: $EXPIRYSTRING."

  # Convert expiry into unixtime
  EXPIRY=$(date -d "$EXPIRYSTRING" +%s)
#  echo "DEBUG: EXPIRY: $EXPIRY."
  NOW=$(date +%s)
#  echo "DEBUG: NOW: $NOW."

  # Number of seconds left
  DIFFERENCE=$(("$EXPIRY" - "$NOW"))
#  echo "DEBUG: DIFFERENCE: $DIFFERENCE."

  # Warn if less than WARNSECONDS less
  if [ "$DIFFERENCE" -lt "$WARNSECONDS" ] ; then
    echo "Warning!  The certificate at $HOST:$PORT expires in $DIFFERENCE seconds (~$((DIFFERENCE / 60 / 60 / 24)) days)."
#  else
#    echo "DEBUG: The certificate at $HOST:$PORT expires in $DIFFERENCE seconds (~$((DIFFERENCE / 60 / 60 / 24)) days)."
  fi

done < "$HOSTSANDPORTS"