task4.txt: filtering rule and alert condition

Part A: rsyslog filter rules on the server (stored in separate files):

docker exec logserver bash -c 'cat > /etc/rsyslog.d/20-filters.conf << "EOF"
# Rule 1: every authentication failure goes to its own file
if ($msg contains "Failed password") then {
    action(type="omfile" file="/var/log/remote/auth_failures.log" template="AllFmt")
}
# Rule 2: severity err or worse (0-3) goes to critical.log
if ($syslogseverity <= 3) then {
    action(type="omfile" file="/var/log/remote/critical.log" template="AllFmt")
}
# Rule 3: sshd program only
if ($programname == "sshd") then {
    action(type="omfile" file="/var/log/remote/sshd_only.log" template="AllFmt")
}
EOF'
docker exec logserver rsyslogd -N1
restart_rsyslog logserver
docker exec client1 pkill -HUP rsyslogd        # client reconnects after the server restart
sleep 3

Demonstrate the result (send new events, then read the filtered files):

docker exec client1 logger -p auth.warning -t sshd "Failed password for invalid user test from 192.0.2.77 port 999 ssh2"
docker exec client2 logger -p daemon.err   -t nginx "upstream timed out"
docker exec client2 logger -p user.info    -t myapp "normal event, should NOT appear in filters"
sleep 2
docker exec logserver cat /var/log/remote/auth_failures.log     # only failed-password lines
docker exec logserver cat /var/log/remote/critical.log          # only err and worse
docker exec logserver cat /var/log/remote/sshd_only.log
docker exec logserver grep -c "should NOT appear" /var/log/remote/auth_failures.log      # 0

Part B: alert condition (threshold of 5 failures from the same IP):

# one-shot check on the server
docker exec logserver bash -c "grep 'Failed password' /var/log/remote/all.log | grep -oE 'from [0-9.]+' | sort | uniq -c | awk '\$1>=5 {print \"ALERT: possible brute force from \"\$3\" (\"\$1\" failures)\"}'"

# continuous watcher: leave running in terminal A, then trigger it from terminal B
docker exec logserver bash -c "tail -Fn0 /var/log/remote/auth_failures.log | grep --line-buffered -oE 'from [0-9.]+' | awk '{c[\$2]++; if (c[\$2]>=5) print \"ALERT: \"\$2\" has \"c[\$2]\" failures\"}'"
for i in 1 2 3 4 5 6; do docker exec client2 logger -p auth.warning -t sshd "Failed password for root from 192.0.2.99 port 70$i ssh2"; done
#  EXPECT: ALERT lines appear after the 5th failure from 192.0.2.99

Part C (optional): count per host with a time window

docker exec logserver bash -c "grep 'Failed password' /var/log/remote/all.log | awk '{print \$2}' | sort | uniq -c | awk '\$1>=3 {print \"WARNING: \"\$2\" has \"\$1\" auth failures\"}'"