#!/bin/sh ## This script reads ${num_last_lines_to_check} of output from the `last -i` ## command and verifies that the connection came from a known ip address, as ## defined in ${known_host_patterns}. ## ## If a line does not match any of the known host patterns, it sends to the ## ${admin_email} address a notification email containing the line of the ## output that did not match any of the expected host patterns. ## ## The script stops at the first non-matching line, and exits with a status ## of 1 if a match was found. Otherwise, it exits with 0. ## ## History: ## ## 2008-05-03: minor alterations to eliminate non-POSIX idioms. ## ## 2008-04-11: initial version ## # Number of lines of `last -i` output to check for non-matching IP addresses. num_last_lines_to_check=100 # Email address of person to be notified if a non-matching entry is found. admin_email="admin@$(hostname)" # A space-separated list of known host patterns, in standard regex syntax; # NOTE: you must escape metacharacters, such as periods. known_host_patterns="127\.0\.0\.1 127\.0\.0\.2" last -i | head -n ${num_last_lines_to_check} | \ while read line; do # Whether we've matched this line to a known host yet matched=0 # Check each pattern in the known host patterns for pat in ${known_host_patterns%% }; do # Try to match pattern consisting of junk followed by whitespace # followed by the host pattern to the current line if expr match "${line}" ".*\s${pat}" > /dev/null ; then # expr exits with 0 status if the match succeeds matched=1 break fi done # If none of the patterns matched, fire off a warning email and exit if [ ${matched} -eq 0 ]; then printf "Unexpected login to server '%s':\n\n%s\n" $(hostname) "${line}" | \ mail -s "ALERT: connection from non-standard IP address" ${admin_email} exit 1 fi done