En anteriores entradas como Crear SFTP en Alta disponibilidad en Azure y Detener ataques de fuerza bruta ya vimos como instalar y configurar fail2ba y ipset. En este caso os traigo un pequeño script para obtener un informe de los ataques sufridos.
En dicho script únicamente tendríais que modificar la variable de $MAILTOADDRESS y la ruta de la blacklist de IPSET: $IPSETCUSTOM.
En caso de no tener IPSET se puede eliminar/comentar perfectamente dicha parte.
Sin mas preámbulos os dejo el script:
#!/bin/bash
# Weekly Fail2Ban Report
FAIL2BAN_PATH="/var/log/fail2ban*"
LOGFILE="/var/log/custom_fail2ban_report_$(date +%m%d%Y).html"
MAILTOADDRESS="rokitoh@red-orbita.com"
SUBJECT="$Weekly Fail2Ban Report"
ALLBAN=$(fail2ban-client status sshd | grep "Total banned:" | awk '{print $4}')
CURRENTLYBAN=$( fail2ban-client status sshd | grep "Currently banned:" | awk '{print $4}')
IPSET=$(ipset list | wc -l)
IPSETCUSTOM=$(cat /etc/ipset-blacklist/ip-blacklist-custom.list | wc -l)
MIP=$(for ip in `zgrep -h "Ban" /var/log/fail2ban* | awk '{print $10,$8}' | sort | sort -n | tail | sort -nr | sort -ut:`; do
echo -e "<tr>"
echo -e "<td>$ip</td>"
echo -e "</tr>"
done)
MGEOIP=$(for ip in `zgrep -h "Ban" /var/log/fail2ban* | awk '{print $NF}' | sort | uniq -c | sort -n | tail -n15 | sort -nr| awk '{print $2}'`; do
geo=`geoiplookup -l $ip | cut -d ':' -f2`
echo -e "<tr>"
echo -e "<td>$ip</td>\n<td>$geo</td>"
echo -e "</tr>"
done)
cat << EOF >> $LOGFILE
<style>
table.customTable {
width: 100%;
background-color: #FFFFFF;
border-collapse: collapse;
border-width: 2px;
border-color: #18B6C3;
border-style: solid;
color: #000000;
}
table.customTable td, table.customTable th {
border-width: 2px;
border-color: #18B6C3;
border-style: solid;
padding: 5px;
}
table.customTable thead {
background-color: #18B6C3;
}
</style>
<table class="customTable">
<thead>
<tr>
<th colspan="2" scope="rowgroup">Weekly Fail2Ban Report</th>
</tr>
</thead>
<tbody>
<tr>
<td>Date:</td>
<td>$(date +%m/%d/%Y)</td>
</tr>
<tr>
<td>Server:</td>
<td>$HOSTNAME</td>
</tr>
<td>Total banned:</td>
<td>$ALLBAN</td>
<tr>
<td>Total banned:</td>
<td>$ALLBAN</td>
</tr>
</tbody>
</table>
</br>
</br>
</br>
</br>
<table class="customTable">
<thead>
<tr>
<th colspan="2" scope="rowgroup">Most frequently banned IP addresses</th>
</tr>
</thead>
<tbody>
$MIP
</tbody>
</table>
</br>
</br>
</br>
</br>
<table class="customTable">
<thead>
<tr>
<th colspan="2" scope="rowgroup">GeoIP</th>
</tr>
</thead>
<tbody>
$MGEOIP
</tbody>
</table>
</br>
</br>
</br>
</br>
<table class="customTable">
<thead>
<tr>
<th colspan="2" scope="rowgroup">BackList IPSET</th>
</tr>
</thead>
<tbody>
<tr>
<td>Total banned:</td>
<td>$IPSET</td>
</tr>
<tr>
<td>Custom banned:</td>
<td>$IPSETCUSTOM</td>
</tr>
</tbody>
</table>
EOF
sleep 10
mail -a "Content-type: text/html" -s "$SUBJECT" "$MAILTOADDRESS" < $LOGFILE
rm $LOGFILE
:wq!