#! /bin/bash

#  Copyright (c) 2014 Gerhard Lausser, ConSol Software GmbH
#  gerhard.lausser@consol.de
#  
#  check_poodle is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

TIMEOUT=30
HOSTNAME=127.0.0.1
PORT=443
VERBOSE=
PROGNAME="check_poodle"
REVISION="1.0"
OPTERR=

exec 3>&1 4>&2 >/dev/null 2>&1

while :; do
  case "$#" in 0) break; esac;
  OPTSTR="$1"
  shift
  if [ ! -z "$1" ]; then
    if { expr "$1" : "-[\-]*[a-z]"; }; then
      OPTARG=
    else
      OPTARG=$1
      shift
    fi
  fi
  case $OPTSTR in
    --)
      break
      ;;
    --help)
      exec 1>&3 2>&4 3>&- 4>&-
      printf "%s %s\n%s: --hostname [--port]\n" "$PROGNAME" "$REVISION" "$PROGNAME"
      exit 0
      ;;
    --timeout)
      test ! -z "$OPTARG" && TIMEOUT=$OPTARG
      ;;
    --hostname)
      if [ ! -z "$OPTARG" ]; then
        HOSTNAME=$OPTARG
      else
        OPTERR="--hostname needs an argument"
      fi
      ;;
    --port)
      if [ ! -z "$OPTARG" ]; then
        PORT=$OPTARG
      else
        OPTERR="--port needs an argument"
      fi
      ;;
    --verbose)
      VERBOSE=1
      ;;
    *)
      OPTERR="unknown: $OPTSTR"
      break
      ;;
  esac
  if [ ! -z "$OPTERR" ]; then
    break
  fi
done
exec 1>&3 2>&4 3>&- 4>&-
if [ ! -z "$OPTERR" ]; then
  echo "$OPTERR"
  exit 3
fi

timeouthandler() {
  printf "UNKNOWN - timeoout\n"
  exit 3
}

timer() {
  sleep $2
  /usr/bin/kill -s ALRM $1 # nicht built-in kill verwenden!
}

trap 'timeouthandler' ALRM
timer $$ $TIMEOUT &

TIMERPID=$!

# bla
if [ -n "$VERBOSE" ]; then
  echo openssl s_client -ssl3 -connect $HOSTNAME:$PORT
fi
response=$(echo klopfklopf | openssl s_client -ssl3 -connect $HOSTNAME:$PORT 2>/dev/null)
kill -9 $TIMERPID
cipheris='Cipher is'
cipher='Cipher[[:space:]]*:[[:space:]]([^ ]+)'
protocol='Protocol[[:space:]]*:[[:space:]]([^ ]+)'
if [[ "$response" =~ $cipheris ]]; then
  [[ "$response" =~ $cipher ]]
  cipher=${BASH_REMATCH[1]//[$'\t\r\n ']}
  [[ "$response" =~ $protocol ]]
  protocol=${BASH_REMATCH[1]//[$'\t\r\n ']}
  if [ "$cipher" = "0000" -o "$cipher" = "(NONE)" ]; then
    printf "OK - Could not establish sslv3 connection. Not vulnerable\n"
    exit 0
  else
    printf "CRITICAL - Established %s connection using cipher %s. Vulnerable!\n" "$protocol" "$cipher"
    exit 2
  fi
else
  printf "OK - Could not establish ssl connection. Not vulnerable\n"
  exit 0
fi

