#!/bin/bash # Rocky9 compatible # Sync M2-BLOCKED-IP-FROM-GUI and db # needed to run only one time to fix old installations # v 1.2.1 # Protection against running more than one instance if [[ "`/sbin/pidof -x $(basename $0) -o %PPID`" ]]; then echo "$(basename $0) script is already running with PID `/sbin/pidof -x $(basename $0) -o %PPID`" exit fi . /usr/src/m2/framework/bash_functions.sh k_iptables_locking_option server_config_file="/etc/m2/system.conf" log_file="/var/log/m2/m2_get_blocked_ip.log" whitelist_chain="M2-IPAUTH-WHITELIST" gui_chain="M2-BLOCKED-IP-FROM-GUI" iptables $l_opt -nL $gui_chain >/dev/null 2>&1 # if no $gui_chain exist, there is nothing to do here if [ $? -ne 0 ]; then exit 1; fi server_id=$(grep server_id $server_config_file | tr -d '[:space:]' | awk -F'=' '{print $2}') format_date() { date "+%Y-%m-%d %H:%M:%S" } if [ $server_id -eq 0 ] || ! echo $server_id | grep -qE '^[0-9]+$'; then echo "$(format_date) [ERROR] server_id! It has value $server_id, but it should be a digit (> 0)" echo "$(format_date) [ERROR] Aborting script. Check server_id value in $server_config_file" exit 1; fi # Get connection details set_database_variables while IFS=';' read ip_chain ip_address do result=$(/usr/bin/mysql --show-warnings -h "$DB_HOST" -u "$DB_USERNAME" --password="$DB_PASSWORD" "$DB_NAME" --disable-column-names -B -e "select count(*) from blocked_ips where server_id=$server_id and blocked_ip='$ip_address' and unblock=2") if [ $result == "0" ]; then /usr/bin/mysql --show-warnings -h "$DB_HOST" -u "$DB_USERNAME" --password="$DB_PASSWORD" "$DB_NAME" -e "INSERT INTO blocked_ips (server_id, blocked_ip, chain, unblock) VALUES ($server_id, '$ip_address', '$ip_chain', 2)" fi done < <(/sbin/iptables-save | grep "\-A $gui_chain" | perl -ne '/-s\s(\d+\.\d+\.\d+\.\d+)\/32.+--comment\s["](.+)["]/ && print "$2;$1\n"') # Get blocked from GUI without comments while IFS=';' read ip_chain ip_address do result=$(/usr/bin/mysql --show-warnings -h "$DB_HOST" -u "$DB_USERNAME" --password="$DB_PASSWORD" "$DB_NAME" --disable-column-names -B -e "select count(*) from blocked_ips where server_id=$server_id and blocked_ip='$ip_address' and unblock=2") if [ $result == "0" ]; then /usr/bin/mysql --show-warnings -h "$DB_HOST" -u "$DB_USERNAME" --password="$DB_PASSWORD" "$DB_NAME" -e "INSERT INTO blocked_ips (server_id, blocked_ip, chain, unblock) VALUES ($server_id, '$ip_address', '', 2)" fi done < <(/sbin/iptables $l_opt -nL $gui_chain | grep -vF '/*' | grep -e "DROP" -e "REJECT" | awk -F" " '{print $4}' | sed -e "s/^/$gui_chain;/")