Skip to content

Commit

Permalink
INDY-1087: add improvements for setup_iptables script. (hyperledger#533)
Browse files Browse the repository at this point in the history
The following features were added:
 - logging of rejected connections;
 - checking for rule existance before appending.

Signed-off-by: Sergey Shilov <[email protected]>
  • Loading branch information
sergey-shilov authored and ashcherbakov committed Jan 24, 2018
1 parent 135cfa5 commit e735222
Showing 1 changed file with 33 additions and 5 deletions.
38 changes: 33 additions & 5 deletions scripts/setup_iptables
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,41 @@ if [ $# -lt 2 ]; then
exit 1;
fi


DPORT=$1
CONN_LIMIT=$2
LOG_CHAIN=LOG_CONN_REJECT

add_rule_if_not_exist()
{
RULE="$1"

cmd="iptables -C $RULE 2>/dev/null 1>&2"
eval $cmd

if [ $? -eq 1 ]; then
cmd="iptables -A $RULE"
eval $cmd
fi
}

# Check whether iptables installed and works
dpkg -s iptables 2>/dev/null 1>&2 && iptables -L 2>/dev/null 1>&2
dpkg -s iptables 2>/dev/null 1>&2 && iptables -nL 2>/dev/null 1>&2
if [ $? -eq 0 ]; then
# Add iptables rule to limit the number of simultaneous clients connections
iptables -I INPUT -p tcp --syn --dport $1 \
-m connlimit --connlimit-above $2 --connlimit-mask 0 \
-j REJECT --reject-with tcp-reset
# Create logging chain for rejected connections
iptables -N $LOG_CHAIN 2>/dev/null 1>&2

# Append a rule that sets log level and log prefix
RULE="$LOG_CHAIN -j LOG --log-level warning --log-prefix \"connlimit: \""
add_rule_if_not_exist "$RULE"

# Append a rule that finally rejects connection
RULE="$LOG_CHAIN -p tcp -j REJECT --reject-with tcp-reset"
add_rule_if_not_exist "$RULE"

# Append a rule to limit the number of simultaneous clients connections
RULE="INPUT -p tcp --syn --dport $DPORT -m connlimit --connlimit-above $CONN_LIMIT --connlimit-mask 0 -j $LOG_CHAIN"
add_rule_if_not_exist "$RULE"
else
echo "Warning: iptables is not installed or permission denied, clients connections limit is not set."
fi

0 comments on commit e735222

Please sign in to comment.