Last active
April 22, 2023 13:52
-
-
Save hongkongkiwi/e8388c88975eb6783822 to your computer and use it in GitHub Desktop.
Bash script to allow some ports on Asus routers running Merlin firmware. This should be put in your /jffs/scripts and made executable (chmod +x /jffs/scripts/firewall-start). Now handles duplicate rules (it won't add again) and inserting before any final DROP in the INPUT chain. Quite useful ;)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
DEBUG="NO" | |
LOGGER_NAME="firewall" | |
PORTS="tcp:9443" | |
WAN="$1" | |
log() { | |
if [ "$DEBUG" == "YES" ]; then | |
echo "$1" | |
else | |
logger "$LOGGER_NAME" "$1" | |
fi | |
} | |
log "Applying firewall-start rules" | |
COUNTER=0 | |
for i in $(echo $PORTS | tr ";" "\n") | |
do | |
: | |
COUNTER=$((COUNTER+1)) | |
PORT=$(echo $i | cut -f2 -d':') | |
PROTO=$(echo $i | cut -f1 -d':') | |
SOURCE_ADDRESS=$(echo $i | cut -f3 -d':') | |
if [ "$PORT" == "$i" ] || [ "$PROTO" == "$i" ]; then | |
log "Invalid protocal:port combo #2${COUNTER} in firewall-start script \"$i\". Ignoring..." | |
continue | |
fi | |
# Only Include s if there is a value | |
s=`[ "$SOURCE_ADDRESS" == "" ] || echo "-s $SOURCE_ADDRESS"` | |
# Generate our rule to search for and remove whitespaces | |
rule=`echo "-A INPUT -i $WAN -p $PROTO -m $PROTO --dport $PORT -j ACCEPT $s" | xargs` | |
# Check if our rule already exists (no point to add it twice) | |
rule_exists=`iptables-save | grep -- "$rule"` | |
if [ "$rule_exists" != "" ]; then | |
log "Rule already exists! $PROTO/$PORT. Skipping." | |
continue | |
else | |
if [ "$s" == "" ]; then | |
log "Allowing port $PROTO/$PORT" | |
else | |
log "Allowing port $PROTO/$PORT from source $SOURCE_ADDRESS" | |
fi | |
fi | |
# If there is a final drop rule, we need to get the number | |
rule_num=`iptables -L "INPUT" --line-numbers | grep -v "state INVALID" | grep "DROP" | tail -n1 | cut -f1 -d' '` | |
if [ "$rule_num" != "" ]; then | |
#echo "iptables -I INPUT $rule_num -p $PROTO -m $PROTO --dport $PORT -j ACCEPT -i $WAN $s" | |
# Insert our rule before the final drop rule | |
iptables -I INPUT $rule_num -p "$PROTO" -m "$PROTO" --dport "$PORT" -j ACCEPT -i "$WAN" $s | |
else | |
#echo "iptables -A INPUT -p $PROTO -m $PROTO --dport $PORT -j ACCEPT -i $WAN $s" | |
# No drop rule, just append it to the end of the chain | |
iptables -A INPUT -p "$PROTO" -m "$PROTO" --dport "$PORT" -j ACCEPT -i "$WAN" $s | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment