Skip to content

Commit

Permalink
feat: support docker in p2p-iptables.sh (#437)
Browse files Browse the repository at this point in the history
* Remove v3 iptables

* Add p2p-iptables.sh
  • Loading branch information
sebastijankuzner authored Feb 16, 2024
1 parent 06cd5f1 commit 5f3ef01
Showing 1 changed file with 41 additions and 8 deletions.
49 changes: 41 additions & 8 deletions scripts/v3-iptables.sh → scripts/p2p-iptables.sh
Original file line number Diff line number Diff line change
@@ -1,13 +1,43 @@
#!/usr/bin/env bash
#mainnet_ports P2P_GLOBAL=4001 / devnet_ports P2P_GLOBAL=4002 / testnet_ports P2P_GLOBAL=4000
P2P_GLOBAL=4001
#mainnet_port P2P_GLOBAL=4001 / devnet_port P2P_GLOBAL=4002 / testnet_port P2P_GLOBAL=4000
P2P_GLOBAL=4000
P2P_GLOBAL_CONN=10
#for docker operation set DOCKER=true
DOCKER=false

#do not edit below this line

d_check=$(which docker || :)

if [[ $DOCKER == "true" ]] && [[ -z "$d_check" ]]; then
echo "Couldn't find docker. Please set 'DOCKER=false' for normal operation"
exit 1
fi

globals() {

table=$(sudo iptables -nL P2P_LIMIT 2> /dev/null)

if [[ $DOCKER == "true" ]]; then
c_name=$(docker ps -a -q -f name=mainsail --format "{{.Names}}")
myip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ${c_name})
ipt="DOCKER-USER"
else
myip=$(ip -o route get to 1.1.1.1 | sed -n 's/.*src \([0-9.]\+\).*/\1/p')
ipt="INPUT"
fi

params=( "${table}" "${myip}" "${ipt}" )

}

#Initialize p2p limiter
start_limit() {

table=$(sudo iptables -nL P2P_LIMIT 2> /dev/null)
myip=$(ip -o route get to 1.1.1.1 | sed -n 's/.*src \([0-9.]\+\).*/\1/p')
globals
table=${params[0]}
myip=${params[1]}
ipt=${params[2]}

if [[ $table ]]; then
sudo iptables -F P2P_LIMIT
Expand All @@ -20,24 +50,27 @@ if [[ $table ]]; then
else
echo "Applying Connection Limits..."
sudo iptables -N P2P_LIMIT
sudo iptables -I INPUT -p tcp -d $myip --dport ${P2P_GLOBAL} -j P2P_LIMIT
sudo iptables -I $ipt -p tcp -d $myip --dport ${P2P_GLOBAL} -j P2P_LIMIT
sudo iptables -A P2P_LIMIT -p tcp --syn -m connlimit --connlimit-above ${P2P_GLOBAL_CONN} --connlimit-mask 32 -j REJECT --reject-with tcp-reset
sudo iptables -A P2P_LIMIT -m state --state NEW -m recent --set
sudo iptables -A P2P_LIMIT -m state --state NEW -m recent --update --seconds 30 --hitcount 4 -j DROP #Allow 4 new connections every 30 sec
sudo iptables -A P2P_LIMIT -p tcp -j ACCEPT
echo "Done!"
fi

}

#Stop limiter
stop_limit() {

table=$(sudo iptables -nL P2P_LIMIT 2> /dev/null)
myip=$(ip -o route get to 1.1.1.1 | sed -n 's/.*src \([0-9.]\+\).*/\1/p')
globals
table=${params[0]}
myip=${params[1]}
ipt=${params[2]}

if [[ $table ]]; then
sudo iptables -F P2P_LIMIT
sudo iptables -D INPUT -p tcp -d $myip --dport ${P2P_GLOBAL} -j P2P_LIMIT > /dev/null 2>&1
sudo iptables -D $ipt -p tcp -d $myip --dport ${P2P_GLOBAL} -j P2P_LIMIT > /dev/null 2>&1
sudo iptables -X P2P_LIMIT
echo "Removed Connection Limits!"
fi
Expand Down

0 comments on commit 5f3ef01

Please sign in to comment.