#!/bin/sh
# thomas loimer
# Remove an address from the blocking table,
# See man iptables-extensions(8), module recent (xt_recent), pam_exec(3).
#
# Changes:
# 2017-07-21
#   * Completely rewrite the logic: Use netstat, not dig,
#     to find the remote ip-address.
# 2017-07-20
#   * account for address range of institute to be now 128.130.169.1-255,
#     not, as previously, 128.130.169.1-128
#     MODIFY /etc/network/iptables.up.rules to the new net mask as well, and do
#     /sbin/iptables-restore </etc/network/iptables.up.rules
# 2016-07-13
#   * add $arg, more extensive message
# 2016-04-13
#   * Initial version.

# Get the ip address of the remote user logging in.
# This is done by searching the addresses returned by netstat for
# the last one from which a connection for this user was done.
# The sshd-processes are owned by root, but the cmdline contains the user name.

# Get the pid of the primary ssh daemon.
pid_sshd=`ps -o pid,cmd --no-headers --ppid 1 | \
	sed -n '/\/usr\/sbin\/sshd/s/ *\([0-9]*\) .*/\1/p'`
# Now the pid of the sshd for this session. The heuristics is, that
# the pid of the most recently started sshd-process (--sort -etime) for this
# user, PAM_USER, shoud be ours. This might fail due to a race condition.
pid=`ps --sort etime -o sess,cmd --no-headers --ppid $pid_sshd | \
	sed -n "/sshd: $PAM_USER/{s/ *\([0-9]*\) .*/\1/p;q}"`
# Search the netstat output for the remote ip of our sshd process.
# With -p, netstat outputs the cmd, but possibly truncates the cmdline
ip=`netstat -Wnpt | sed -n \
	"/$pid\/sshd/{s/\([^ ]\{1,\} \{1,\}\)\{4\}\([0-9.]*\):.*/\2/p;q}"`

# Check that the process really belongs to PAM_USER
if !(fgrep -qa $PAM_USER /proc/$pid/cmdline) || test -z $ip ; then
	exit 1;
fi

if test ${ip%.*} != '128.130.169' ; then
	/bin/echo -$ip >/proc/net/xt_recent/DEFAULT
	logger -p auth.notice -t pam_exec -- \
		"Unblock $ip for user $PAM_USER@$PAM_RHOST."
fi
