#!/bin/bash
#
# Copyright (C) 2014-2016 FUSS Project <info@fuss.bz.it>
# Author:  Simone Piccardi and Truelite Srl
#
# This program 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; version 2 of the License.
#
# 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 or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA
#

#
# Use as ./listsshkeyaccess.sh
#

LOGFILE=/var/log/auth.log
KEYTABLEDIR=/tmp/keytable-$(id -u)
[ -d  $KEYTABLEDIR ] || mkdir -m 700 $KEYTABLEDIR
PREFIX="key-"

cd $KEYTABLEDIR
grep -v '^#' ~/.ssh/authorized_keys | split -l1 -d - $PREFIX

declare -A KEYTABLE

for i in ${PREFIX}*; do
    FPR=$(ssh-keygen -l -f $i|awk '{print $2}')
    OWNER=$(awk '{ print $NF }' $i)
    KEYTABLE[$FPR]=$OWNER
done

echo SSH Access
echo -e "Access date\t\tFrom IP \tTo User\tBy keyID" 
for i in ${!KEYTABLE[@]}; do
    SESSIONS=$(grep -i "sshd.* Accepted publickey for.* $i" $LOGFILE|
		      uniq|cut -d[ -f2|cut -d] -f1)
    for j in $SESSIONS; do
	REGEX="sshd\[$j\].*Accepted publickey for ([[:alnum:]]+) from ([0-9.:]+).*"
	ACCESS=$(sed -nre "s/$REGEX/\1 \2/p" $LOGFILE)
	DATE=$(echo $ACCESS|cut -d" " -f 1-3)
	REMAIN=$(echo $ACCESS|cut -d" " -f 4-)
	USER=$(echo $REMAIN|awk '{print $2}')
	IP=$(echo $REMAIN|awk '{print $3}')
	echo -e "$DATE\t$IP\t$USER\t${KEYTABLE[$i]}"
    done
done

