commit d3d14a431e23ed94102b78c80cdb37bc7ff9cfea Author: Jonny007-MKD Date: Thu Feb 27 22:40:33 2020 +0100 First script that parses nmaps output and checks for unexpected ports diff --git a/check_nmap.sh b/check_nmap.sh new file mode 100755 index 0000000..fc848ea --- /dev/null +++ b/check_nmap.sh @@ -0,0 +1,146 @@ +#!/bin/bash + +function echoerr { echo "$@" 1>&2; } + +### Parse attributes ### + +INPUT="" +DEBUG=false +PORT_RANGE="1-65535" +NMAP_ARGS="" +KNOWN_PORTS=() +while [[ $# -gt 0 ]]; do + case $1 in + -i|--input) + INPUT="$2" + if [ ! -f "$INPUT" ]; then + echoerr "The specified input file '$INPUT' does not exist" + exit 3 + fi + shift;; + -h|--host) HOST="$2"; shift;; + -d|--debug) DEBUG=true;; + -p|--portrange) PORT_RANGE="$2"; shift;; + -k|--known) KNOWN_PORTS+=($2); shift;; + --) shift; NMAP_ARGS="$@"; shift $#;; + -?|--help) + echo "Check nmap portscan. Arguments:" + echo "--raid NAME: Raid name, e.g. md0" + echo "--input FILE: Read from this file. Default: /proc/mdstat" + exit 0 + ;; + esac + shift +done + +if [ -z "$HOST" -a -z "$INPUT" ]; then + echoerr "Missing host argument (-h)" +fi + +function log { + if $DEBUG; then + echo " > $@" + fi +} +function logLine { + if $DEBUG; then + echo " : $@" + fi +} +NL=$'\n' + +log "INPUT: $INPUT" +log "PORT_RANGE: $PORT_RANGE" +log "KNOWN_PORTS: ${KNOWN_PORTS[@]}" + +function runNmap { + local $portrange + if [ -n "$PORT_RANGE" ]; then + portrange="-p$PORT_RANGE" + else + portrange="" + fi + + local $input + if [ -n "$INPUT" ]; then + while read -r line; do + parseLine "$line" + done < $INPUT + else + local $cmd + cmd="nmap $portrange $NMAP_ARGS -- $HOST" + log "$cmd" + while read -r line; do + parseLine "$line" + done <<< $($cmd) + result=$? + log "nmap exited with $result" + if [ $result -ne 0 ]; then + echoerr "CRITICAL - nmap exited with $result" + exit 2 + fi + fi +} + +NOW_PORTS=false +OPEN_PORTS=() +function parseLine { + local line="$1" + if ! $NOW_PORTS; then + if [[ "$line" == PORT*STATE*SERVICE ]]; then + NOW_PORTS=true + fi + else + if [ -z "$line" ]; then + NOW_PORTS=false + else + local x=${line/\/*} + OPEN_PORTS+=($x) + fi + fi +} + +ERROR=false +NEW_PORTS=() +function comparePorts { + log ${KNOWN_PORTS[@]} + KNOWN_PORTS=($(for each in ${KNOWN_PORTS[@]}; do echo $each; done | sort)) + log ${KNOWN_PORTS[@]} + + for i in "${OPEN_PORTS[@]}"; do + skip=false + for j in "${KNOWN_PORTS[@]}"; do + if [ $j -eq $i ]; then + skip=true + break + fi + done + if ! $skip; then + log Unexpected open port: $i + NEW_PORTS+=($i) + fi + done + if [ ${#NEW_PORTS[@]} -gt 0 ]; then + ERROR=true + fi +} + +function print { + if $ERROR; then + echo "CRITICAL - These ports should not be open: ${NEW_PORTS[@]}" + else + echo "OK" + fi + + + if $ERROR; then + exit 2 + else + exit 0 + fi +} + +runNmap +comparePorts +print +