diff --git a/add_iptables_block.sh b/add_iptables_block.sh index 027fc83..ccc276e 100755 --- a/add_iptables_block.sh +++ b/add_iptables_block.sh @@ -1,12 +1,18 @@ #!/bin/bash iptables_path=/usr/sbin/iptables -blocked_ips=`cat ~/gitlab-iptables-blocker/blocked_ips.txt` -iptables_list=`$iptables_path -L DOCKER-USER` +lockfile="/tmp/iptables_blocker.lock" -while read -r line; do - if ! echo "$iptables_list" | grep -q $line; then - echo "Adding $line to iptables deny rule" - sh -c "$iptables_path -I DOCKER-USER -s $line -j DROP -m comment --comment \"Malicious IP range\"" - fi -done <<< $blocked_ips +# Prevent overlapping runs +exec 9>"$lockfile" +flock -n 9 || exit 1 + +# Load current blocked rules once +iptables_rules="$(iptables-save -t filter | grep DOCKER-USER)" +# Read list of IPs to block +while IFS= read -r ip; do + if ! echo "$iptables_rules" | grep -q "\-s $ip "; then + echo "Adding $ip to iptables deny rule" + $iptables_path -I DOCKER-USER -s "$ip" -j DROP -m comment --comment "Malicious IP range" + fi +done < ~/gitlab-iptables-blocker/blocked_ips.txt