Skynet Skynet - Router Firewall & Security Enhancements

  • ATTENTION! You'll notice a Prefix dropdown when you create a thread. If your post applies to one of the topics listed, please use that Prefix for your post. When browsing the thread list you can use the Prefix to filter the view.
  • ATTENTION! As of November 1, 2020, you will not be able to reply to threads 6 months after the thread is opened. Threads will not be locked, so posts may still be edited by their authors.

wbennett77

Regular Contributor
Hey Adamm,

Is there a limit to how many addresses can be blocked? I reached 65535 IPs being banned a few days ago and the number has not increased since which doesn't seem right?

Cheers!
 
Last edited:

Adamm

Part of the Furniture
Hey Adamm,

Is there a limit to how many addresses can be blocked? I reached 65535 IPs being banned a few days ago and the number has not increased since which doesn't seem right?

Cheers!
This is more the likely due to the "maxelem" defaulting at 65535 when not specified. I'll get you the exact syntax when I finish work but you should be able to work it out from here



EDIT;

When creating your IPSets its best to leave this stuff unspecified as IPSet is supposed to dynamically adjust the values, but in this case seeing it isn't you would need to specify the following.

ipset -N -q Whitelist nethash --maxelem 65535
ipset -N -q Blacklist iphash --maxelem 65535
ipset -N -q BlockedCountries nethash --maxelem 65535
 
Last edited:

wbennett77

Regular Contributor
This is more the likely due to the "maxelem" defaulting at 65535 when not specified. I'll get you the exact syntax when I finish work but you should be able to work it out from here



EDIT;

When creating your IPSets its best to leave this stuff unspecified as IPSet is supposed to dynamically adjust the values, but in this case seeing it isn't you would need to specify the following.

Quote:
ipset -N -q Whitelist nethash --maxelem 65535
ipset -N -q Blacklist iphash --maxelem 65535
ipset -N -q BlockedCountries nethash --maxelem 65535
__________________
How and where would I place this info?

Update: I have two ipset files....ipset.txt and ipset2.txt where ipset.txt is the most recent and includes the whitelist, all the blacklisted ips and countries and ipset2.txt includes the whitelist and blocked ips but not the countries (I only recently added the countries) .

In each file I have the following:

-N Whitelist nethash --hashsize 1024 --probes 4 --resize 50
-N Blacklist iphash --hashsize 298932 --probes 8 --resize 50
-N BlockedCountries nethash --hashsize 298932 --probes 4 --resize 50

Are these the values I need to overwrite and is it normal to have the two ipset files?

I also, in the ipamount file see the magic number 65535.

Thanks!
 
Last edited:

Adamm

Part of the Furniture
How and where would I place this info?

Update: I have two ipset files....ipset.txt and ipset2.txt where ipset.txt is the most recent and includes the whitelist, all the blacklisted ips and countries and ipset2.txt includes the whitelist and blocked ips but not the countries (I only recently added the countries) .

In each file I have the following:

-N Whitelist nethash --hashsize 1024 --probes 4 --resize 50
-N Blacklist iphash --hashsize 298932 --probes 8 --resize 50
-N BlockedCountries nethash --hashsize 298932 --probes 4 --resize 50

Are these the values I need to overwrite and is it normal to have the two ipset files?

I also, in the ipamount file see the magic number 65535.

Thanks!
ipset.txt is where each set is saved to every hour. ipset2.txt is a backup of that file every 24 hours.

That being said, the values only need to be replaced in ipset.txt then a reboot should fix your issue (as it will load ipset.txt on boot)


ipamount is just where I store the number of banned IP's for the syslog to reference.
 

wbennett77

Regular Contributor
Am I supposed to just add the three lines or replace (overwrite) the three current lines?
Thanks!
 

Adamm

Part of the Furniture
Am I supposed to just add the three lines or replace (overwrite) the three current lines?
Thanks!
Just overwrite the current lines in the file and IPSet should do the rest of the work for you after a reboot when it loads the file (ipset.txt)
 

HardCat

Regular Contributor
I have installed the scripts to the correct locations and have checked to ensure they are executable. I am not getting any banned IP's and when I run the script manually
Code:
sh /jffs/scripts/firewall-start
I get the following output:
Code:
Correct Settings Detected.
[IP Banning Started] ... ... ...
iptables: Bad rule (does a matching rule exist in that chain?).
iptables: Bad rule (does a matching rule exist in that chain?).
iptables: Bad rule (does a matching rule exist in that chain?).
iptables: No chain/target/match by that name.
/opt/bin/firewall: line 145: echo: Argument list too long
Started:  Wed Jul  9 07:26:48 DST 2014
Finished: Wed Jul  9 07:26:49 DST 2014
0 IP's currently banned.
Output from:
Code:
ipset -n -L
Name: Whitelist
Type: nethash
References: 1
Header: hashsize: 1024 probes: 4 resize: 50
Members:
192.168.225.0/24
192.168.1.0/24

Name: Blacklist
Type: iphash
References: 2
Header: hashsize: 1024 probes: 8 resize: 50
Members:

Name: BlockedCountries
Type: nethash
References: 1
Header: hashsize: 1024 probes: 4 resize: 50
Members:
Any ideas as to what I need to change?
 

djtech2k

Regular Contributor
This thread is great!

I just setup an AC68U with RMerlin and I want to block all non-us countries. I started looking at IPTables to block all the subnets from IPDeny.com, but its too many rules which will cause bad perf. I was directed to look at ipsets since its supposed to not impact performance.

So I started reading this thread at the first post. Is that first post still the best instructions for this or are there updates?

I am not sure how the country is determined in this method. However it is detected, how often is it updated with most recent subnets?

In the post, it says that this will grab IP's from the syslog and automatically ban them. Did I read that right?

Does this ban individual IP's or subnet ranges?

I would really like to implement this on my AC68U and also my Linux web server. I just want to make sure that I am working with the most accurate process when I start implementing it.

Thanks!
 
Last edited:

Skirk

Occasional Visitor
I just decided to re-set this up on a new router after a massive flood of dropped connections in my syslog from China!

Here is the code, and I am making the assumption Adamm doesn't mind me re-posting his excellent work:

firewall-start
Code:
#!/bin/sh

echo "0 * * * * /tmp/mnt/sda1/asusware.arm/bin/firewall save" > /var/spool/cron/crontabs/admin
echo "0 5 * * * /tmp/mnt/sda1/asusware.arm/bin/firewall backup" >> /var/spool/cron/crontabs/admin
[ -n "`pidof crond`" ] && killall -q crond

sleep 1
crond
sh /tmp/mnt/sda1/asusware.arm/bin/firewall
and /opt/bin/firewall

Code:
#!/bin/sh
############################################################
## 17/04/2014 --- RT-AC56U/RT-AC68U Firewall Addition v2.2 #
######################################################################################
###          ----- Make Sure To Edit The Following Files -----                       #
### /jffs/firewall-start				 <-- Sets up cronjob/iptables rules			 #
### /opt/bin/firewall					 <-- Blacklists IP's From /opt/tmp/ipset.txt #
### /opt/tmp/ipset.txt                   <-- Banned IP List/IPSet Rules              #
######################################################################################

##############################
#####Commands / Variables#####
##############################
UNBANSINGLE="unban"          # <-- Remove Single IP From Blacklist
UNBANALL="unbanall"          # <-- Unbans All IPs In Blacklist
REMOVEBANS="removeall"       # <-- Remove All Entries From Blacklist
SAVEIPSET="save"             # <-- Save Blacklists to /opt/tmp/ipset.txt
BANSINGLE="ban"              # <-- Adds Entry To Blacklist
BANCOUNTRYSINGLE="country"   # <-- Adds entire country to blacklist
BANCOUNTRYLIST="bancountry"  # <-- Bans specified countries in this file
WHITELIST="whitelist"        # <-- Add IPs from path to Whitelist
BACKUPRULES="backup"         # <-- Backup IPSet Rules to /opt/tmp/ipset2.txt / Checks for firmware updates
##############################

started=`date`
bannedips=/opt/tmp/ipamount
cat /opt/bin/firewall | head -23

#########################################################################################
# Unban / Unbanall / Removeall / Save / Ban / Country / Bancountry / Whitelist / Backup #
#########################################################################################

if [ X"[email protected]" = X"$UNBANSINGLE" ]
then
	echo "Input IP Address To Unban"
	read unbannedip
	logger -t Firewall "[Unbanning And Removing $unbannedip From Blacklist] ... ... ..."
	ipset  -D Blacklist $unbannedip
	echo "`sed /$unbannedip/d /opt/tmp/ipset.txt`" > /opt/tmp/ipset.txt
	echo "$unbannedip Is Now Unbanned"

elif [ X"[email protected]" = X"$UNBANALL" ]
then
	echo "[Unbanning All IP's] ... ... ..."
	logger -t Firewall "[Unbanning All IP's] ... ... ..."
	ipset --flush Blacklist
	ipset --flush BlockedCountries

elif [ X"[email protected]" = X"$REMOVEBANS" ]
then
	expr `ipset list | wc -l` - 15 > /opt/tmp/ipamount
	echo "[Deleting All `cat $bannedips` Entries From Blacklist] ... ... ..."
	logger -t Firewall "[Deleting `cat $bannedips` Entries From Blacklist] ... ... ..."
	ipset --flush Blacklist
	ipset --flush BlockedCountries
	ipset --save > /opt/tmp/ipset.txt

elif [ X"[email protected]" = X"$SAVEIPSET" ]
then
	echo "[Saving Blacklists] ... ... ..."
	ipset --save > /opt/tmp/ipset.txt
	echo "`sed '/crond: USER admin/d' /tmp/syslog.log`" > /tmp/syslog.log

elif [ X"[email protected]" = X"$BANSINGLE" ]
then
	echo "Input IP Address"
	read bannedip
	logger -t Firewall "[Adding $bannedip To Blacklist] ... ... ..."
	ipset -q -A Blacklist $bannedip
	echo "$bannedip Is Now Banned"

elif [ X"[email protected]" = X"$BANCOUNTRYSINGLE" ]
then
	echo "Input Country Abbreviation"
	read country
	for IP in $(wget -q -O - http://www.ipdeny.com/ipblocks/data/countries/$country.zone)
	do
	ipset -q -A BlockedCountries $IP
	done

elif [ X"[email protected]" = X"$BANCOUNTRYLIST" ]
then
	echo "[Banning Spam Countries] ... ... ..."
	for country in pk cn in jp ru sa
	do
    for IP in $(wget -q -O - http://www.ipdeny.com/ipblocks/data/countries/$country.zone)
    do
    ipset -q -A BlockedCountries $IP
	done
	done

elif [ X"[email protected]" = X"$WHITELIST" ]
then
	echo "Input file location"
	read WHITELISTFILE
	for IP in `cat $WHITELISTFILE`
	do
	ipset -q -A Whitelist $IP
	echo $IP
	done
	ipset --save > /opt/tmp/ipset.txt

elif [ X"[email protected]" = X"$BACKUPRULES" ]
then
	echo "Backing Up Current IPSet Rules"
	cp -f /opt/tmp/ipset.txt /opt/tmp/ipset2.txt


else
		if [ X"`nvram get fw_log_x`" = X"drop" ]
		then
			echo "Correct Settings Detected"
		else
			nvram set fw_log_x=drop
			nvram commit
		fi

		if [ X"`nvram get fw_enable_x`" = X"1" ]
		then
			echo "Correct Settings Detected."
		else
			nvram set fw_enable_x=1
			nvram commit
		fi

	echo "[IP Banning Started] ... ... ..."
	logger -t Firewall "[IP Banning Started] ... ... ..."
	ipset -q -R  < /opt/tmp/ipset.txt
	ipset -q -N Whitelist nethash
	ipset -q -N Blacklist iphash
	ipset -q -N BlockedCountries nethash
	iptables -D logdrop -m state --state NEW -j LOG --log-prefix "DROP " --log-tcp-sequence --log-tcp-options --log-ip-options
	iptables -D INPUT -m set --match-set Whitelist src -j ACCEPT
	iptables -D INPUT -m set --match-set Blacklist src -j DROP
	iptables -D INPUT -m set --match-set BlockedCountries src -j DROP
	iptables -D logdrop -m state --state NEW -j SET --add-set Blacklist src
	iptables -I INPUT -m set --match-set Blacklist src -j DROP
	iptables -I INPUT -m set --match-set BlockedCountries src -j DROP
	iptables -I INPUT -m set --match-set Whitelist src -j ACCEPT
	iptables -I logdrop -m state --state NEW -j SET --add-set Blacklist src
	ipset -q -A Whitelist 192.168.1.0/24
	ipset -q -A Whitelist `nvram get lan_ipaddr`/24
	echo "`sed '/DROP IN=/d' /tmp/syslog.log`" > /tmp/syslog.log
	echo "`sed '/DROP IN=/d' /tmp/syslog.log-1`" > /tmp/syslog.log-1
fi

#########
#Logging#
#########
OLDAMOUNT=`cat /opt/tmp/ipamount`
echo "Started:  $started"
echo "Finished: `date`"
expr `ipset -L Blacklist | wc -l` - 6 > /opt/tmp/ipamount
NEWAMOUNT=`cat /opt/tmp/ipamount`
echo "`cat $bannedips` IP's currently banned."
logger -t Firewall "[Complete] `cat $bannedips` IPs currently banned. `expr $NEWAMOUNT - $OLDAMOUNT` New IP's Banned. "
 

Amateur273

Occasional Visitor
Unknown arg `--match-set'

Asus RT-AC66U v.376.49

[email protected]:/tmp/mnt/OPTWARE# iptables -V
iptables v1.3.8
[email protected]:/tmp/mnt/OPTWARE# ipset -V
ipset v4.5, protocol version 4.
Kernel module protocol version 4.

[email protected]:/tmp/mnt/OPTWARE# iptables -A INPUT -m set --match-set blacklist src -j LOG --log-prefix "DROP blacklist entry: "
iptables v1.3.8: Unknown arg `--match-set'
Try `iptables -h' or 'iptables --help' for more information.
====================

Update: Solved by change "-m set --match-set blacklist" to "-m set --set blacklist"
 
Last edited:

Eet_46

Occasional Visitor
I got this log:

Code:
Dec 27 19:51:55 dropbear[24029]: Bad password attempt for 'admin' from 122.225.109.206:48156
Dec 27 19:51:56 dropbear[24031]: Login attempt for nonexistent user from 122.225.109.206:53411
Dec 27 19:51:56 dropbear[24029]: Exit before auth (user 'admin', 10 fails): Max auth tries reached - user 'admin' from 122.225.109.206:48156
Dec 27 19:51:56 dropbear[24032]: Child connection from 122.225.109.206:56225
Dec 27 19:51:56 dropbear[24031]: Login attempt for nonexistent user from 122.225.109.206:53411
Dec 27 19:51:56 dropbear[24033]: Child connection from 122.225.109.206:56757
Dec 27 19:51:57 dropbear[24031]: Login attempt for nonexistent user from 122.225.109.206:53411
Dec 27 19:51:58 dropbear[24031]: Login attempt for nonexistent user from 122.225.109.206:53411
Dec 27 19:51:58 dropbear[24032]: Login attempt for nonexistent user from 122.225.109.206:56225
Dec 27 19:51:58 dropbear[24031]: Login attempt for nonexistent user from 122.225.109.206:53411
Dec 27 19:51:59 dropbear[24032]: Login attempt for nonexistent user from 122.225.109.206:56225
Dec 27 19:51:59 dropbear[24031]: Login attempt for nonexistent user from 122.225.109.206:53411
Dec 27 19:51:59 dropbear[24032]: Login attempt for nonexistent user from 122.225.109.206:56225
Dec 27 19:52:00 dropbear[24031]: Login attempt for nonexistent user from 122.225.109.206:53411
Dec 27 19:52:00 dropbear[24032]: Login attempt for nonexistent user from 122.225.109.206:56225
Dec 27 19:52:00 dropbear[24031]: Login attempt for nonexistent user from 122.225.109.206:53411
Dec 27 19:52:00 dropbear[24032]: Login attempt for nonexistent user from 122.225.109.206:56225
Dec 27 19:52:01 dropbear[24031]: Exit before auth: Max auth tries reached - user 'is invalid' from 122.225.109.206:53411
Dec 27 19:52:01 dropbear[24032]: Login attempt for nonexistent user from 122.225.109.206:56225
Dec 27 19:52:01 dropbear[24035]: Child connection from 122.225.109.206:2035
Dec 27 19:52:01 dropbear[24033]: Bad password attempt for 'admin' from 122.225.109.206:56757
Dec 27 19:52:02 dropbear[24032]: Login attempt for nonexistent user from 122.225.109.206:56225
Dec 27 19:52:02 dropbear[24033]: Bad password attempt for 'admin' from 122.225.109.206:56757
Dec 27 19:52:02 dropbear[24032]: Exit before auth: Error reading: Connection reset by peer
Dec 27 19:52:02 dropbear[24033]: Exit before auth (user 'admin', 2 fails): Error reading: Connection reset by peer
Dec 27 19:52:02 dropbear[24035]: Exit before auth: Error writing: Connection reset by peer
Dec 27 20:00:01 [B][COLOR="Red"]Firewall: [Complete] 0 IPs currently banned. 0 New IP's Banned. [/COLOR][/B]
Dec 27 20:17:03 dropbear[24157]: Child connection from 122.194.76.75:1077
Dec 27 20:17:05 dropbear[24157]: Login attempt for nonexistent user from 122.194.76.75:1077
Dec 27 20:17:06 dropbear[24157]: Exit before auth: Disconnect received
Dec 27 20:17:09 dropbear[24158]: Child connection from 122.194.76.75:3897
Dec 27 20:17:14 dropbear[24158]: Login attempt for nonexistent user from 122.194.76.75:3897
Dec 27 20:17:14 dropbear[24158]: Exit before auth: Disconnect received
Dec 27 20:17:18 dropbear[24159]: Child connection from 122.194.76.75:5940
Dec 27 20:17:24 dropbear[24159]: Login attempt for nonexistent user from 122.194.76.75:5940
Dec 27 20:17:24 dropbear[24159]: Exit before auth: Error reading: Connection reset by peer
Dec 27 20:47:56 dropbear[24279]: Child connection from 113.161.0.114:52661
Dec 27 20:47:57 dropbear[24279]: Exit before auth: Exited normally
Isn't the firewall script supposed to ban these ips?? What's going on?
Then i ran the firewall script manually, with following output:

Code:
[email protected]:/tmp/home/root# sh /jffs/scripts/firewall-start
#!/bin/sh
############################################################
## 17/04/2014 --- RT-AC56U/RT-AC68U Firewall Addition v2.2 #
################################################################################
######
###          ----- Make Sure To Edit The Following Files -----
     #
### /jffs/firewall-start                 <-- Sets up cronjob/iptables rules
     #
### /opt/bin/firewall                    <-- Blacklists IP's From /opt/tmp/ipset
.txt #
### /opt/tmp/ipset.txt                   <-- Banned IP List/IPSet Rules
     #
################################################################################
######

##############################
#####Commands / Variables#####
##############################
UNBANSINGLE="unban"          # <-- Remove Single IP From Blacklist
UNBANALL="unbanall"          # <-- Unbans All IPs In Blacklist
REMOVEBANS="removeall"       # <-- Remove All Entries From Blacklist
SAVEIPSET="save"             # <-- Save Blacklists to /opt/tmp/ipset.txt
BANSINGLE="ban"              # <-- Adds Entry To Blacklist
BANCOUNTRYSINGLE="country"   # <-- Adds entire country to blacklist
BANCOUNTRYLIST="bancountry"  # <-- Bans specified countries in this file
WHITELIST="whitelist"        # <-- Add IPs from path to Whitelist
BACKUPRULES="backup"         # <-- Backup IPSet Rules to /opt/tmp/ipset2.txt / C
hecks for firmware updates
##############################
Correct Settings Detected
Correct Settings Detected.
[IP Banning Started] ... ... ...
iptables: No chain/target/match by that name.
/opt/bin/firewall: line 145: echo: Argument list too long
Started:  Sat Dec 27 20:56:51 GMT 2014
Finished: Sat Dec 27 20:56:52 GMT 2014
0 IP's currently banned.
[email protected]:/tmp/home/root#
What am i missing??
My problem seems the same as post #49, but no answer?
 
Last edited:

wbennett77

Regular Contributor
Eet_46,

Try the command "firewall save" one time. Not using this right now but seemed to kick start the banning for me if I remember correctly.
 

Eet_46

Occasional Visitor
Well, i already ran this command some time ago, to make it create /opt/tmp/ipset.txt.
So that file exists already, making me doubt that this is the solution :/

Btw, only thing i edited was the path in "firewall-start", from

/tmp/mnt/sda1/asusware.arm
to
as it otherwise gave me an error.
 
Last edited:

Adamm

Part of the Furniture
I saw this question being asked a few times and this thread being linked so I thought i'd post my current code. I removed a few functions like my autoupdate feature until I get my VPS up and running again.



Code:
#!/bin/sh
#################################################################################################
## - 25/12/2014 ---		RT-AC66U/RT-AC56U/RT-AC68U Firewall Addition v2.5 -  		#
###################################################################################################################
###					----- Make Sure To Edit The Following Files -----			  #
### /jffs/firewall-start					 <-- Sets up cronjob/iptables rules		  #
### /jffs/scripts/firewall					 <-- Blacklists IP's From /jffs/scripts/ipset.txt #
### /jffs/scripts/ipset.txt					 <-- Banned IP List/IPSet Rules			  #
###################################################################################################################

##############################
#####Commands / Variables#####
##############################
UNBANSINGLE="unban"          # <-- Remove Single IP From Blacklist
UNBANALL="unbanall"          # <-- Unbans All IPs In Blacklist
REMOVEBANS="removeall"       # <-- Remove All Entries From Blacklist
SAVEIPSET="save"             # <-- Save Blacklists to /jffs/scripts/ipset.txt
BANSINGLE="ban"              # <-- Adds Entry To Blacklist
BANCOUNTRYSINGLE="country"   # <-- Adds entire country to blacklist
BANCOUNTRYLIST="bancountry"  # <-- Bans specified countries in this file
WHITELIST="whitelist"        # <-- Add IPs from path to Whitelist
NEWLIST="new"				 # <-- Create new IPSet Blacklist
DUMPCFE="dumpcfe"	     	 # <-- Dumps current CFE to /jffs/scripts/cfe.dump
UPDATECFE="updatecfe"	     # <-- Flash CFE from /jffs/scripts/cfe.flash (reset nvram afterwards)
##############################

start_time=`date +%s`
cat /jffs/scripts/firewall | head -28

#####################################################################################################################################
# - Unban / Unbanall / Removeall / Save / Ban / Country / Bancountry / Whitelist / Hideme / Findme/ DumpCFE / UpdateCFE  / Backup - #
#####################################################################################################################################

if [ X"[email protected]" = X"$UNBANSINGLE" ]
then
	echo "Input IP Address To Unban"
	read unbannedip
	logger -t Firewall "[Unbanning And Removing $unbannedip From Blacklist] ... ... ..."
	ipset  -D Blacklist $unbannedip
	echo "`sed /$unbannedip/d /jffs/scripts/ipset.txt`" > /jffs/scripts/ipset.txt
	echo "$unbannedip Is Now Unbanned"

elif [ X"[email protected]" = X"$UNBANALL" ]
then
	echo "[Unbanning All IP's] ... ... ..."
	logger -t Firewall "[Unbanning All IP's] ... ... ..."
	ipset --flush Blacklist
	ipset --flush BlockedCountries

elif [ X"[email protected]" = X"$REMOVEBANS" ]
then
	nvram set Blacklist=`expr \`ipset -L Blacklist | wc -l\` - 6`
	echo "[Deleting All `echo \`nvram get Blacklist\`` Entries From Blacklist] ... ... ..."
	logger -t Firewall "[Deleting All `echo \`nvram get Blacklist\`` Entries From Blacklist] ... ... ..."
	ipset --flush Blacklist
	ipset --flush BlockedCountries
	ipset --save > /jffs/scripts/ipset.txt

elif [ X"[email protected]" = X"$SAVEIPSET" ]
then
	echo "[Saving Blacklists] ... ... ..."
	ipset --save > /jffs/scripts/ipset.txt
	echo "`sed '/crond: USER admin/d' /tmp/syslog.log`" > /tmp/syslog.log

elif [ X"[email protected]" = X"$BANSINGLE" ]
then
	echo "Input IP Address"
	read bannedip
	logger -t Firewall "[Adding $bannedip To Blacklist] ... ... ..."
	ipset -q -A Blacklist $bannedip
	echo "$bannedip Is Now Banned"

elif [ X"[email protected]" = X"$BANCOUNTRYSINGLE" ]
then
	echo "Input Country Abbreviation"
	read country
	for IP in $(wget -q -O - http://www.ipdeny.com/ipblocks/data/countries/$country.zone)
	do
	ipset -q -A BlockedCountries $IP
	done

elif [ X"[email protected]" = X"$BANCOUNTRYLIST" ]
then
	echo "[Banning Spam Countries] ... ... ..."
	for country in pk cn in jp ru sa
	do
        for IP in $(wget -q -O - http://www.ipdeny.com/ipblocks/data/countries/$country.zone)
       	do
    	ipset -q -A BlockedCountries $IP
	done
	done

elif [ X"[email protected]" = X"$WHITELIST" ]
then
	echo "Input file location"
	read WHITELISTFILE
	for IP in `cat $WHITELISTFILE`
	do
	ipset -q -A Whitelist $IP
	echo $IP
	done
	ipset --save > /jffs/scripts/ipset.txt

elif [ X"[email protected]" = X"$NEWLIST" ]
then
	echo "Does The Blacklist Need To Be Downloaded? yes/no"
	read ENABLEDOWNLOAD
		if [ X"$ENABLEDOWNLOAD" = X"yes" ]; then
			echo "Input URL For IPSet Blacklist"
			read DOWNLOADURL
			wget -O /jffs/scripts/ipset2.txt $DOWNLOADURL
		fi
	echo "Input New Set Name"
	read SETNAME
	sed -i "s/Blacklist/$SETNAME/g" /jffs/scripts/ipset2.txt
	ipset -q -R  < /jffs/scripts/ipset2.txt
	echo "Successfully Added New Set"


elif [ X"[email protected]" = X"$DUMPCFE" ] && [ X"`nvram get model`" = X"RT-AC68U" ]
then
	echo "Dumping CFE"
	logger -t Firewall "[Dumping CFE] ... ... ..."
	OLDCFE="`strings /dev/mtd0 | grep model` - `strings /dev/mtd0 | grep bl_v` - `strings /dev/mtd0 | grep 0:ccode` - `strings /dev/mtd0 | grep et0macaddr` - `strings /dev/mtd0 | grep 0:macaddr` - `strings /dev/mtd0 | grep 1:macaddr` - `strings /dev/mtd0 | grep secret_code`"
	cat /dev/mtd0 > /jffs/scripts/cfe.dump
	echo "Sucessfully Dumped CFE - $OLDCFE"
	logger -t Firewall "Sucessfully Dumped CFE - $OLDCFE"

elif [ X"[email protected]" = X"$UPDATECFE" ] && [ X"`nvram get model`" = X"RT-AC68U" ]
then
	echo "Flashing new CFE"
	logger -t Firewall "[Flashing new CFE] ... ... ..."
	OLDCFE="`strings /dev/mtd0 | grep et0macaddr`  `strings /dev/mtd0 | grep 0:macaddr`  `strings /dev/mtd0 | grep 1:macaddr`  `strings /dev/mtd0 | grep secret_code`"
	NEWCFE="`strings /jffs/scripts/cfe.flash | grep et0macaddr`  `strings /jffs/scripts/cfe.flash | grep 0:macaddr`  `strings /jffs/scripts/cfe.flash | grep 1:macaddr`  `strings /jffs/scripts/cfe.flash | grep secret_code`"
		if [ X"`echo $OLDCFE`" = X"`echo $NEWCFE`" ]; then
			echo "Correct Values Detected"
			/jffs/scripts/mtd-write cfe.flash boot && status="Successfully flashed new CFE. `strings /dev/mtd0 | grep bl_v`   `strings /dev/mtd0 | grep 0:ccode`   $NEWCFE"  || status="Failed flashing new CFE"
			logger -t Firewall "$status ... ... ..."
			echo "$status"
		else
			echo "Values Missing From New CFE - Make Sure Values Are Hex'd In" && status="Values Missing From New CFE - Make Sure Values Are Hex'd In"
			echo "Old CFE - $OLDCFE"
			echo "New CFE - $NEWCFE"
			logger -t Firewall "$status ... ... ..."
		fi

else
		if [ X"`nvram get fw_enable_x`" = X"1" ]
		then
			echo "Correct Settings Detected."
		else
			echo "Enabled SPI Firewall"
			nvram set fw_enable_x=1
			nvram commit
		fi

		if [ X"`nvram get fw_log_x`" = X"drop" ]
		then
			echo "Correct Settings Detected"
		else
			echo "Enabled Firewall Logging"
			nvram set fw_log_x=drop
			nvram commit
		fi

		if [ X"`nvram get clkfreq`" != X"1200,800" ] && [ X"`nvram get model`" = X"RT-AC68U" ]
		then
			echo "Enabled Overclock - Current Clock `nvram get clkfreq`"
			nvram set clkfreq=1200,800
			nvram commit
		else
			echo "Correct Settings Detected."
		fi


	echo "`sed '/IP Banning Started/d' /tmp/syslog.log`" > /tmp/syslog.log
	echo "[IP Banning Started] ... ... ..."
	logger -t Firewall "[IP Banning Started] ... ... ..."
	ipset -q -R  < /jffs/scripts/ipset.txt
	ipset -q -N Whitelist nethash
	ipset -q -N Blacklist iphash
	ipset -q -N BlockedCountries nethash
	iptables -D logdrop -m state --state NEW -j LOG --log-prefix "DROP " --log-tcp-sequence --log-tcp-options --log-ip-options  > /dev/null 2>&1
	iptables -D INPUT -m set --match-set Whitelist src -j ACCEPT
	iptables -D INPUT -m set --match-set Blacklist src -j DROP
	iptables -D INPUT -m set --match-set BlockedCountries src -j DROP
	iptables -D logdrop -m state --state NEW -j SET --add-set Blacklist src
	iptables -I INPUT -m set --match-set Blacklist src -j DROP
	iptables -I INPUT -m set --match-set BlockedCountries src -j DROP
	iptables -I INPUT -m set --match-set Whitelist src -j ACCEPT
	iptables -I logdrop -m state --state NEW -j SET --add-set Blacklist src
	ipset -q -A Whitelist 192.168.1.0/24
	ipset -q -A Whitelist 192.3.148.0/24
	ipset -q -A Whitelist `nvram get lan_ipaddr`/24
	echo "`sed '/DROP IN=/d' /tmp/syslog.log`" > /tmp/syslog.log
	echo "`sed '/DROP IN=/d' /tmp/syslog.log-1`" > /tmp/syslog.log-1

fi

###############
# - Logging - #
###############
OLDAMOUNT=`nvram get Blacklist`
nvram set Blacklist=`expr \`ipset -L Blacklist | wc -l\` - 6`
NEWAMOUNT=`nvram get Blacklist`
nvram set BlacklistTotal=`expr \`ipset -L | wc -l\` - 26`
start_time=$(expr `date +%s` - $start_time)
echo "[Complete] $NEWAMOUNT IPs currently banned. `expr $NEWAMOUNT - $OLDAMOUNT` New IP's Banned. `nvram get BlacklistTotal` Banned Overall [`echo $start_time`s]"
logger -t Firewall "[Complete] $NEWAMOUNT IPs currently banned. `expr $NEWAMOUNT - $OLDAMOUNT` New IP's Banned. `nvram get BlacklistTotal` Banned Overall [`echo $start_time`s]"

Code:
#!/bin/sh

echo "0 * * * * /jffs/scripts/firewall save" > /var/spool/cron/crontabs/admin
[ -n "`pidof crond`" ] && killall -q crond

sleep 5
crond
sh /jffs/scripts/firewall
 
Last edited:

Eet_46

Occasional Visitor
I saw this question being asked a few times and this thread being linked so I thought i'd post my current code. I removed a few functions like my autoupdate feature until I get my VPS up and running again.
Sorry, i'm a bit confused now, with your new code, some of the changes would be nice to know why they are made :)

Maybe an update of the main post, so everything is up to date? That would be a lot easier, rather than one having to read through the entire thread to gather bits of info..
 

faria

Senior Member
Hold the Phone... why does this script backup and flashes the bootoader?
I saw this question being asked a few times and this thread being linked so I thought i'd post my current code. I removed a few functions like my autoupdate feature until I get my VPS up and running again.



Code:
#!/bin/sh
#################################################################################################
## - 25/12/2014 ---        RT-AC66U/RT-AC56U/RT-AC68U Firewall Addition v2.5 -          #
###################################################################################################################
###                    ----- Make Sure To Edit The Following Files -----              #
### /jffs/firewall-start                     <-- Sets up cronjob/iptables rules          #
### /jffs/scripts/firewall                     <-- Blacklists IP's From /jffs/scripts/ipset.txt #
### /jffs/scripts/ipset.txt                     <-- Banned IP List/IPSet Rules              #
###################################################################################################################

##############################
#####Commands / Variables#####
##############################
UNBANSINGLE="unban"          # <-- Remove Single IP From Blacklist
UNBANALL="unbanall"          # <-- Unbans All IPs In Blacklist
REMOVEBANS="removeall"       # <-- Remove All Entries From Blacklist
SAVEIPSET="save"             # <-- Save Blacklists to /jffs/scripts/ipset.txt
BANSINGLE="ban"              # <-- Adds Entry To Blacklist
BANCOUNTRYSINGLE="country"   # <-- Adds entire country to blacklist
BANCOUNTRYLIST="bancountry"  # <-- Bans specified countries in this file
WHITELIST="whitelist"        # <-- Add IPs from path to Whitelist
NEWLIST="new"                 # <-- Create new IPSet Blacklist
DUMPCFE="dumpcfe"              # <-- Dumps current CFE to /jffs/scripts/cfe.dump
UPDATECFE="updatecfe"         # <-- Flash CFE from /jffs/scripts/cfe.flash (reset nvram afterwards)
##############################

start_time=`date +%s`
cat /jffs/scripts/firewall | head -28

#####################################################################################################################################
# - Unban / Unbanall / Removeall / Save / Ban / Country / Bancountry / Whitelist / Hideme / Findme/ DumpCFE / UpdateCFE  / Backup - #
#####################################################################################################################################

if [ X"[email protected]" = X"$UNBANSINGLE" ]
then
    echo "Input IP Address To Unban"
    read unbannedip
    logger -t Firewall "[Unbanning And Removing $unbannedip From Blacklist] ... ... ..."
    ipset  -D Blacklist $unbannedip
    echo "`sed /$unbannedip/d /jffs/scripts/ipset.txt`" > /jffs/scripts/ipset.txt
    echo "$unbannedip Is Now Unbanned"

elif [ X"[email protected]" = X"$UNBANALL" ]
then
    echo "[Unbanning All IP's] ... ... ..."
    logger -t Firewall "[Unbanning All IP's] ... ... ..."
    ipset --flush Blacklist
    ipset --flush BlockedCountries

elif [ X"[email protected]" = X"$REMOVEBANS" ]
then
    nvram set Blacklist=`expr \`ipset -L Blacklist | wc -l\` - 6`
    echo "[Deleting All `echo \`nvram get Blacklist\`` Entries From Blacklist] ... ... ..."
    logger -t Firewall "[Deleting All `echo \`nvram get Blacklist\`` Entries From Blacklist] ... ... ..."
    ipset --flush Blacklist
    ipset --flush BlockedCountries
    ipset --save > /jffs/scripts/ipset.txt

elif [ X"[email protected]" = X"$SAVEIPSET" ]
then
    echo "[Saving Blacklists] ... ... ..."
    ipset --save > /jffs/scripts/ipset.txt
    echo "`sed '/crond: USER admin/d' /tmp/syslog.log`" > /tmp/syslog.log

elif [ X"[email protected]" = X"$BANSINGLE" ]
then
    echo "Input IP Address"
    read bannedip
    logger -t Firewall "[Adding $bannedip To Blacklist] ... ... ..."
    ipset -q -A Blacklist $bannedip
    echo "$bannedip Is Now Banned"

elif [ X"[email protected]" = X"$BANCOUNTRYSINGLE" ]
then
    echo "Input Country Abbreviation"
    read country
    for IP in $(wget -q -O - http://www.ipdeny.com/ipblocks/data/countries/$country.zone)
    do
    ipset -q -A BlockedCountries $IP
    done

elif [ X"[email protected]" = X"$BANCOUNTRYLIST" ]
then
    echo "[Banning Spam Countries] ... ... ..."
    for country in pk cn in jp ru sa
    do
        for IP in $(wget -q -O - http://www.ipdeny.com/ipblocks/data/countries/$country.zone)
           do
        ipset -q -A BlockedCountries $IP
    done
    done

elif [ X"[email protected]" = X"$WHITELIST" ]
then
    echo "Input file location"
    read WHITELISTFILE
    for IP in `cat $WHITELISTFILE`
    do
    ipset -q -A Whitelist $IP
    echo $IP
    done
    ipset --save > /jffs/scripts/ipset.txt

elif [ X"[email protected]" = X"$NEWLIST" ]
then
    echo "Does The Blacklist Need To Be Downloaded? yes/no"
    read ENABLEDOWNLOAD
        if [ X"$ENABLEDOWNLOAD" = X"yes" ]; then
            echo "Input URL For IPSet Blacklist"
            read DOWNLOADURL
            wget -O /jffs/scripts/ipset2.txt $DOWNLOADURL
        fi
    echo "Input New Set Name"
    read SETNAME
    sed -i "s/Blacklist/$SETNAME/g" /jffs/scripts/ipset2.txt
    ipset -q -R  < /jffs/scripts/ipset2.txt
    echo "Successfully Added New Set"


elif [ X"[email protected]" = X"$DUMPCFE" ] && [ X"`nvram get model`" = X"RT-AC68U" ]
then
    echo "Dumping CFE"
    logger -t Firewall "[Dumping CFE] ... ... ..."
    OLDCFE="`strings /dev/mtd0 | grep model` - `strings /dev/mtd0 | grep bl_v` - `strings /dev/mtd0 | grep 0:ccode` - `strings /dev/mtd0 | grep et0macaddr` - `strings /dev/mtd0 | grep 0:macaddr` - `strings /dev/mtd0 | grep 1:macaddr` - `strings /dev/mtd0 | grep secret_code`"
    cat /dev/mtd0 > /jffs/scripts/cfe.dump
    echo "Sucessfully Dumped CFE - $OLDCFE"
    logger -t Firewall "Sucessfully Dumped CFE - $OLDCFE"

elif [ X"[email protected]" = X"$UPDATECFE" ] && [ X"`nvram get model`" = X"RT-AC68U" ]
then
    echo "Flashing new CFE"
    logger -t Firewall "[Flashing new CFE] ... ... ..."
    OLDCFE="`strings /dev/mtd0 | grep et0macaddr`  `strings /dev/mtd0 | grep 0:macaddr`  `strings /dev/mtd0 | grep 1:macaddr`  `strings /dev/mtd0 | grep secret_code`"
    NEWCFE="`strings /jffs/scripts/cfe.flash | grep et0macaddr`  `strings /jffs/scripts/cfe.flash | grep 0:macaddr`  `strings /jffs/scripts/cfe.flash | grep 1:macaddr`  `strings /jffs/scripts/cfe.flash | grep secret_code`"
        if [ X"`echo $OLDCFE`" = X"`echo $NEWCFE`" ]; then
            echo "Correct Values Detected"
            /jffs/scripts/mtd-write cfe.flash boot && status="Successfully flashed new CFE. `strings /dev/mtd0 | grep bl_v`   `strings /dev/mtd0 | grep 0:ccode`   $NEWCFE"  || status="Failed flashing new CFE"
            logger -t Firewall "$status ... ... ..."
            echo "$status"
        else
            echo "Values Missing From New CFE - Make Sure Values Are Hex'd In" && status="Values Missing From New CFE - Make Sure Values Are Hex'd In"
            echo "Old CFE - $OLDCFE"
            echo "New CFE - $NEWCFE"
            logger -t Firewall "$status ... ... ..."
        fi

else
        if [ X"`nvram get fw_enable_x`" = X"1" ]
        then
            echo "Correct Settings Detected."
        else
            echo "Enabled SPI Firewall"
            nvram set fw_enable_x=1
            nvram commit
        fi

        if [ X"`nvram get fw_log_x`" = X"drop" ]
        then
            echo "Correct Settings Detected"
        else
            echo "Enabled Firewall Logging"
            nvram set fw_log_x=drop
            nvram commit
        fi

        if [ X"`nvram get clkfreq`" != X"1200,800" ] && [ X"`nvram get model`" = X"RT-AC68U" ]
        then
            echo "Enabled Overclock - Current Clock `nvram get clkfreq`"
            nvram set clkfreq=1200,800
            nvram commit
        else
            echo "Correct Settings Detected."
        fi


    echo "`sed '/IP Banning Started/d' /tmp/syslog.log`" > /tmp/syslog.log
    echo "[IP Banning Started] ... ... ..."
    logger -t Firewall "[IP Banning Started] ... ... ..."
    ipset -q -R  < /jffs/scripts/ipset.txt
    ipset -q -N Whitelist nethash
    ipset -q -N Blacklist iphash
    ipset -q -N BlockedCountries nethash
    iptables -D logdrop -m state --state NEW -j LOG --log-prefix "DROP " --log-tcp-sequence --log-tcp-options --log-ip-options  > /dev/null 2>&1
    iptables -D INPUT -m set --match-set Whitelist src -j ACCEPT
    iptables -D INPUT -m set --match-set Blacklist src -j DROP
    iptables -D INPUT -m set --match-set BlockedCountries src -j DROP
    iptables -D logdrop -m state --state NEW -j SET --add-set Blacklist src
    iptables -I INPUT -m set --match-set Blacklist src -j DROP
    iptables -I INPUT -m set --match-set BlockedCountries src -j DROP
    iptables -I INPUT -m set --match-set Whitelist src -j ACCEPT
    iptables -I logdrop -m state --state NEW -j SET --add-set Blacklist src
    ipset -q -A Whitelist 192.168.1.0/24
    ipset -q -A Whitelist 192.3.148.0/24
    ipset -q -A Whitelist `nvram get lan_ipaddr`/24
    echo "`sed '/DROP IN=/d' /tmp/syslog.log`" > /tmp/syslog.log
    echo "`sed '/DROP IN=/d' /tmp/syslog.log-1`" > /tmp/syslog.log-1

fi

###############
# - Logging - #
###############
OLDAMOUNT=`nvram get Blacklist`
nvram set Blacklist=`expr \`ipset -L Blacklist | wc -l\` - 6`
NEWAMOUNT=`nvram get Blacklist`
nvram set BlacklistTotal=`expr \`ipset -L | wc -l\` - 26`
start_time=$(expr `date +%s` - $start_time)
echo "[Complete] $NEWAMOUNT IPs currently banned. `expr $NEWAMOUNT - $OLDAMOUNT` New IP's Banned. `nvram get BlacklistTotal` Banned Overall [`echo $start_time`s]"
logger -t Firewall "[Complete] $NEWAMOUNT IPs currently banned. `expr $NEWAMOUNT - $OLDAMOUNT` New IP's Banned. `nvram get BlacklistTotal` Banned Overall [`echo $start_time`s]"

Code:
#!/bin/sh

echo "0 * * * * /jffs/scripts/firewall save" > /var/spool/cron/crontabs/admin
[ -n "`pidof crond`" ] && killall -q crond

sleep 5
crond
sh /jffs/scripts/firewall
 

Sign Up For SNBForums Daily Digest

Get an update of what's new every day delivered to your mailbox. Sign up here!
Top