#!/bin/sh
#
# Script terminating SSH connections in 'accept' state older than $TIMEOUT
# seconds
#
# This script can be used as a mitigation to DoS issue triggered by
# CVE-2024-6387 mitigation consisting in disabling LoginGraceTime.
#
# Author: Renaud Métrich <rmetrich@redhat.com>
#
# 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 3.
#
# 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=${1:-120}

export LANG=C

PIDS=()

for pid in $(pgrep -x sshd); do
    if [[ $(readlink -f /proc/$pid/exe) == /usr/sbin/sshd ]] && \
       tr -d '\0' < /proc/$pid/cmdline 2>/dev/null | grep -Eq "^sshd: (\[accepted\]|unknown)"; then
        PIDS+=( $pid )
    fi
done

now=$(date +%s)
up_to_epoch=$(($now - $TIMEOUT))

for pid in $PIDS; do
    last_access=$(stat -c %Y /proc/$pid 2>/dev/null)
    if [ ${last_access:-$now} -lt $up_to_epoch ]; then
        kill $pid 2>/dev/null
    fi
done

# vi: set autoindent expandtab softtabstop=4 shiftwidth=4 :
