Syed Jahanzaib – Personal Blog to Share Knowledge !

August 15, 2011

Mikrotik Firewall / Short Notes + Scripts


Contents …


– session-timeout / idle-timeout / keepalive-timeout
TOP-  Block TRACE Route in Mikrotik
1- Secure Services by Firewall Filter Rules
2- Firewall Sample
3- Better approach on blocking Ports
4- howto block Winbox Discovery
5- Filter Rules to Allow/Block VPN Protocol
6- Howto block P2P / Torrents & Downloads using L7/Contents
7- Howto block User via MAC address
8- Script to reboot Router Daily in night at 1:00am
9- Disable/Enable Users using Script and Schedule
10- Update Hotspot walled garden list by fetching text file
11- Disconnect all active PPPoE users
12- Block download based on file SIZE …
13- Monitor WAN link (pppoe-out1) and reconnect (for ptcl 50mb vdsl hang issue)
14- Disable HOTSPOT Users based who donot have comments “PAID”
15- Script to disconnect previously logged user if same id connected with second computer [Hotspot]
16- Radius Offline, enable local ppp secret
17- Download Mikrotik Upgrade package via command in ROS [26/8/2014]
18- Multiple WAN ISP’s link with SAME GATEWAY [03/10-OCT/2014]
19 – Print/Find WAN ip (if you have multiple wan IP assigned on same wan interface] [10th Jan, 2015]
20- Print/Find (pppoe dialer base) WAN IP address [10th Jan, 2015]
21- Mikrotik 10g SFP+ Supported Card [Tested]
22- Login to FBR site IRIS not working with Load Balancing PCC
23- Monitor LOG & email upon admin user logged in
24- Delete BUSY leases from Mikrotik DHCP
25- detecting ROGUE dhcp in LAN


Session-timeout / Idle-timeout / Keepalive-timeout in Mikrotik

– `Session-timeout` is used to disconnect user after specific period of time (like after x seconds/minutes/hours). If user is connected with the router, he will be disconnected either he is using router network or not,

– `idle-timeout` is used to detect, if client is not using Router networks (INTERNET or locally natted hosts).
Reaching timeout user will be logged out, etc.
In other words, idle timeout checks traffic. If user is online but is just not sending./receiving anything, he may reach its idle timeout.

– `keep-alive-timeout` keepalive timeout checks availability. It is used to detect, if user is available and reachable, if check fails client will be dropped out, etc.
keepalive timeout may only be reached if client is physically disconnected or turned off.The default keepalive-timeout value of 10 is OK in most cases. If you set it to 0, the router will not disconnect clients until they explicitly log out or the router is restarted.

Regard’s
Syed.Jahanzaib


TOP- Block TRACEROUTE in Mikrotik

/ip firewall filter
add action=drop chain=forward comment="BLOCK TRACEROUTE - ZAIB" icmp-options=11:0 protocol=icmp
add action=drop chain=forward comment="BLOCK TRACEROUTE - ZAIB" icmp-options=3:3 protocol=icmp

Move above two rules on TOP & done.


0- Change mangle PCC rules by finding comments

Recently I configured a load balancer (PCC base) in Mikrotik RB for a client. For some customized reasons, He wanted to run dst-address as Per-connection-classifier in Day time, & both-address-and-ports in Night time. He had to do this manually on a daily basis, so he asked me if it can be done automatically  by the system. To achieve it, I added comments in all MARK CONNECTION (prerouting) mangle rules, like “rule1” “rule2” and so on, then I used following code in scheduled script which actually change the per connection classifier settings only.

/ip firewall mangle set per-connection-classifier=dst-address:4/0 [find comment="rule1"]

🙂


 

Sometimes, in Mikrotik logs, you will see that some ips from WAN/LAN try to login to your MT box using SSH,Winbox etc. To secure your router , the best solution would be to come up with a list of networks that should be allowed to access the router administratively, and block everything else. Following code might help you in this situation.
[Most rules are copied from Mikrotik Wiki’s Articles]

The following rules will create a address list which will have your management PC ip address. an then it will allow all ports like WINBOX, FTP, SSH, TELNET from this address list only, and rest of ips wont be able to access these ports.


/ip firewall address-list
add list=management-servers address=10.10.0.1

/ip firewall filter
add chain=input src-address-list=management-servers protocol=tcp dst-port=21,22,23,80,443,8291 action=accept

add chain=input protocol=tcp dst-port=21,22,23,80,443,8291 action=drop

Now scenario will be like below.

It is strongly advised to DISABLE all Unnecessary Services on the MikroTik Router specially SSH/FTP which is highly used for brute force attacks. Also make sure to change the default services ports to some other number, preferably higher unused ports like 50000 or above or likewise …

This reduces the attack surface of your router the less services there are to attack the less likely your router could be compromised or overloaded 🙂

Remotely Accessible Router Services should be limited to few addresses

This is a simple and very effective way of controlling who can attempt to access the MikroTik router. One could check from which addresses or networks the MikroTik Router would be administered. Then one could create firewall rules that only allow access to the router services from the management networks.

Deny all un wanted inbound Traffic and allow only related traffic  (***The best approach***)

By restricting inbound traffic to the router, you can prevent the accidental opening up of services on the router. Also by restricting all types of services except for the services you know about & you want, you prevent any services (that you may not be aware of ) being accessible remotely on the MikroTik router.


HOWTO PREVENT VIRUS / PORTS FLOODING ?

A basic Mikrotik Firewall Script to secure MT box from virus and flooding. First copy all contents of below script to notepad, then carefully read it,


/ip firewall filter

# To Block ICMP on your WAN Interface
add action=drop chain=input comment="Block ICMP on WAN interface" in-interface=pppoe-out1 protocol=icmp

# Add flooding ips coming from the internet to the Blocked List for 1 mnt
add action=jump chain=forward connection-state=new jump-target=block-ddos
add action=drop chain=forward connection-state=new dst-address-list=ddosed src-address-list=ddoser
add action=return chain=block-ddos dst-limit=50,50,src-and-dst-addresses/10s
add action=add-dst-to-address-list address-list=ddosed address-list-timeout=1m chain=block-ddos
add action=add-src-to-address-list address-list=ddoser address-list-timeout=1m chain=block-ddos

# Block DNS Request on INCOMING WAN INTERFACE
add action=drop chain=input comment="BLOCK DNS REQUEST ON WAN INTERFACE" dst-port=53 in-interface=pppoe-out1 protocol=udp

# Block PORT Scanner Users for 2 minutes
add action=drop chain=input comment="ping port scanners" src-address-list="port scanners"
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2m chain=input comment="Port scanners to list " protocol=tcp psd=21,3s,3,1
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2m chain=input comment="NMAP FIN Stealth scan" protocol=tcp tcp-flags=fin,!syn,!rst,!psh,!ack,!urg
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2m chain=input comment="SYN/FIN scan" protocol=tcp tcp-flags=fin,syn
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2m chain=input comment="SYN/RST scan" protocol=tcp tcp-flags=syn,rst
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2m chain=input comment="FIN/PSH/URG scan" protocol=tcp tcp-flags=fin,psh,urg,!syn,!rst,!ack
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=30m chain=input comment="ALL/ALL scan" protocol=tcp tcp-flags=fin,syn,rst,psh,ack,urg
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2m chain=input comment="NMAP NULL scan" protocol=tcp tcp-flags=!fin,!syn,!rst,!psh,!ack,!urg

# Block Common Virus Ports
add action=drop chain=virus comment="Blaster Worm" dst-port=135-139 protocol=tcp
add action=drop chain=virus comment="Blaster Worm" dst-port=445 protocol=tcp
add action=drop chain=virus comment="Messenger Worm" dst-port=135-139 protocol=udp
add action=drop chain=virus comment="Blaster Worm" dst-port=445 protocol=udp
add action=drop chain=virus comment=________ dst-port=593 protocol=tcp
add action=drop chain=virus comment=________ dst-port=1024-1030 protocol=tcp
add action=drop chain=virus comment=MyDoom dst-port=1080 protocol=tcp
add action=drop chain=virus comment=________ dst-port=1214 protocol=tcp
add action=drop chain=virus comment="ndm requester" dst-port=1363 protocol=tcp
add action=drop chain=virus comment="ndm server" dst-port=1364 protocol=tcp
add action=drop chain=virus comment="screen cast" dst-port=1368 protocol=tcp
add action=drop chain=virus comment=hromgrafx dst-port=1373 protocol=tcp
add action=drop chain=virus comment=cichlid dst-port=1377 protocol=tcp
add action=drop chain=virus comment="Bagle Virus" dst-port=2745 protocol=tcp
add action=drop chain=virus comment=Dumaru.Y dst-port=2283 protocol=tcp
add action=drop chain=virus comment=Beagle dst-port=2535 protocol=tcp
add action=drop chain=virus comment=Beagle.C-K dst-port=2745 protocol=tcp
add action=drop chain=virus comment=MyDoom dst-port=3127-3128 protocol=tcp
add action=drop chain=virus comment="Backdoor OptixPro" dst-port=3410 protocol=tcp
add action=drop chain=virus comment=Sasser dst-port=5554 protocol=tcp
add action=drop chain=virus comment=Beagle.B dst-port=8866 protocol=tcp
add action=drop chain=virus comment=Dabber.A-B dst-port=9898 protocol=tcp
add action=drop chain=virus comment=Dumaru.Y dst-port=10000 protocol=tcp
add action=drop chain=virus comment=MyDoom.B dst-port=10080 protocol=tcp
add action=drop chain=virus comment=NetBus dst-port=12345 protocol=tcp
add action=drop chain=virus comment=Kuang2 dst-port=17300 protocol=tcp
add action=drop chain=virus comment=SubSeven dst-port=27374 protocol=tcp
add action=drop chain=virus comment="PhatBot, Agobot, Gaobot" dst-port=65506 protocol=tcp

add action=jump chain=forward comment="jump to the virus chain" jump-target=virus
add chain=input comment="Accept established connections" connection-state=established
add chain=input comment="Accept related connections" connection-state=related
add action=drop chain=input comment="invalid connections" connection-state=invalid
add chain=input comment=UDP protocol=udp
add action=drop chain=forward comment="invalid connections" connection-state=invalid
# Script Ends Here

A BETTER APPROACH ON BLOCKING PORTS !

/ip firewall mangle
add action=add-src-to-address-list address-list=Worm-Infected-p445 address-list-timeout=1h chain=prerouting connection-state=new disabled=no dst-port=445 limit=5,10 protocol=tcp

/ip firewall filter
add action=drop chain=forward disabled=no dst-port=445 protocol=tcp src-address-list=Worm-Infected-p445
add action=drop chain=forward disabled=no dst-port=445 protocol=tcp src-address-list=Worm-Infected-p445

[/sourcecode]

The above Rules allows 5 packets per second with a burst of 10 specific to new connections. The mangle rule will put addresses on a list when it exceeds that limit. That way legitimate use isn’t blocked but something like a virus or worm sending out mass amounts will be detected and stopped. It’s a much more elegant solution than blocking a bunch of ports for all users. It also gives you a list of user IPs that need to clean up their pc.


Mikrotik How to block Winbox Discovery + Limit Winbox Access

To hide your mikrotik from being appearing in WINBOX scan negibour list, & to limit WINBOX access from your admin PC only,
Use the Following.

/tool mac-server
add disabled=yes interface=all
/tool mac-server ping
set enabled=no

/ip firewall filter
add action=drop chain=input comment="block mikrotik discovery" disabled=no dst-port=5678 protocol=udp
add action=drop chain=input comment="ALL WINBOX REQUEST By MAC Address" disabled=no dst-port=20561 protocol=udp
add action=drop chain=input comment="ALL WINBOX REQUEST EXCEPT FROM MY PC" disabled=no dst-port=8291 protocol=tcp src-address=!192.168.2.6

You can Also Disable Network Neighbor Discovery on the interface to which your network users are connected

Example:

/ip neighbor discovery set ether1 discover=no

Personnel Recommendation:
Always disable un-necessary Like FTP / SSH / TELNET etc. or if its necessary to enable services, at least Limit there access to specific pcs only.
Allow only WINBOX with different port number.


How-to  Allow VPN (PPTP) Connections for Mikrotik VPN Server

PPTP uses the GRE protocol, You have to allow ip PROTOCOL 47 (GRE), not TCP port.
TCP port 1723 is the control connection, while the actual tunnel is GRE (protocol 47).

Example:


/ip firewall filter
add action=accept chain=input disabled=no dst-port=1723 protocol=tcp
add action=accept chain=input disabled=no protocol=gre

Make sure these rules are above any general DENY rule.


Howto Block Torrent / P2P

Blockin 100% torrent is impossible as nowadays new torrents application are using encrypted method and its nearly impossible to inspect the SSL traffic. I used Forefront TMG 2010 is capable to inspect SSL traffic at some extents.
However you can block basic torrents access by using following.

{The patterns were fetched from Public sources and few from Mikrotik & some personnel lab testing. Modified for easy copy pasting, as we all love copy pasting don’t we ? :p)

/ip firewall layer7-protocol
add comment="P2P WWW web base cnoetent Matching / Zaib" name=p2p_www regexp=\
"^.*(get|GET).+(torrent|thepiratebay|isohunt|entertane|demonoid|btjunkie|mininova|flixflux|vertor|h33t|zoozle|bitnova|bitsoup|meganova|fulldls|btbot|fenopy|gpirate|commonbits).*\$"
add comment="P2P DNS Matching / Zaib" name=p2p_dns regexp=\
"^.+(torrent|thepiratebay|isohunt|entertane|demonoid|btjunkie|mininova|flixflux|vertor|h33t|zoozle|bitnova|bitsoup|meganova|fulldls|btbot|fenopy|gpirate|commonbits).*\$"

/ip firewall mangle
add action=mark-packet chain=postrouting comment="p2p download" disabled=no layer7-protocol=p2p_www new-packet-mark="p2p download" passthrough=no
add action=mark-packet chain=postrouting disabled=no layer7-protocol=p2p_dns new-packet-mark="p2p download" passthrough=no

/ip firewall filter
add action=drop chain=forward comment="Block P2p_www Packets / Zaib" disabled=no layer7-protocol=p2p_www
add action=drop chain=forward comment="Block P2p_dns Packets / Zaib" disabled=no layer7-protocol=p2p_dns
add action=drop chain=forward comment="Block General P2P Connections , default mikrotik p2p colelction / zaib" disabled=no p2p=all-p2p

Another approach to block P2P, taken from the mikrotik forum, Not personally checked yet. Someone please check and update

/ip firewall filter
add action=drop chain=forward comment="TORRENT No 1: Classic non security torrent" disabled=no p2p=all-p2p
add action=drop chain=forward comment="TORRENT No 2: block outgoing DHT" content=d1:ad2:id20: disabled=no dst-port=1025-65535 packet-size=95-190 protocol=udp
add action=drop chain=forward comment="TORRENT No 3: block outgoing TCP announce" content="info_hash=" disabled=no dst-port=2710,80 protocol=tcp
add action=drop chain=forward comment="TORRENT No 4: prohibits download .torrent files. " content="\r\nContent-Type: application/x-bittorrent" disabled=no protocol=tcp src-port=80
add action=drop chain=forward comment="TORRENT No 5: 6771 block Local Broadcast" content="\r\nInfohash:" disabled=no dst-port=6771 protocol=udp


Howto Block User MAC address

/ip fir fi
add chain=input action=drop src-mac-address=74:EA:3A:F2:AF:90
add chain=forward action=drop src-mac-address=74:EA:3A:F2:AF:90

SCRIPT SECTION



Script to reboot router daily at 1:00am

First add script which ahve command to reboto router, then simply schedule it to run daily in night 1:00am or whatever you like 🙂

/system script
add name=sysreboot policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api source="/system reboot"
/system scheduler add name="rebootat1am" start-date="dec/04/2013" start-time="01:00:00" interval="1d" on-event="/system reboot"
# OR
/system scheduler add name="rebootat1am" start-date="dec/04/2013" start-time="01:00:00" interval="1d" on-event="sysreboot"


Disable/Enable Users using Script and Schedule

http://forum.mikrotik.com/viewtopic.php?f=13&t=81284&p=406269#p406269



Update Hotspot walled garden list by fetching text file

http://forum.mikrotik.com/viewtopic.php?f=2&t=81249


Disconnect all active PPPoE users

# Print local time for LOG record purposes / tracking
:local CurrentTime [/system clock get time];
:log warning "Script Start to Disconnect all active PPPoE Users for RM Data record purposes at  $CurrentTime. . ."
# Disconnect users using find
/ppp active remove [find service="pppoe"]
:log warning "Users disconnection script completed at  $CurrentTime. . ."


Block download based on file SIZE …

I forgot the guy’s name who is from FB, who asked me a question, lets name him Mr. X. The query was > howto block downloads of large files (lets say 5mb or above ) in specific timings (like 8pm-12am).

But the issue is How the router will know the file size before it’s downloaded? The router has no way of knowing how big a connection is… An workaround is to create a Firewall Filter rule that will will allow the first 5MB of a connection through, and once it reaches that, it will start to drop packets. I used it a network in Gulistan-e-Jauhar, and it worked good.
But do remember that that It will also affect streaming, RDP like protocols, VPNs, and any other connection that transfers a large number of bytes.

/ip firewall filter
add action=drop chain=forward comment="downloading of files larger then 5mb (It will break connection after 5mb of transfer) applicable from 8pm till 12am / zaib" connection-bytes=5242880-0 disabled=no protocol=tcp time=\
20h-23h59m59s,sun,mon,tue,wed,thu,fri,sat

But do remember that it will only drop packets for that specific download, user can do another session of download. to prevent this , you can create mangle rule that will add the user in a temporary list (with timeout value of 1 hour or more) and next time the user will try to download , his access to that particular resource will be denied, you can customize this action to be either whole session or specific file like mp3 exe zip etc etc. You can also do a source base or destination base controlling.

You can also make a Simple Queue with or without burst, that should slow down the download speed after 5Mb to be crawled in few kbits only
( it will not block based on size)

You can also forward these packets to external proxy like Squid to do the filter base on reply_body_max_size directive. example:

reply_body_max_size 5242880 deny all # in specific timings only

As some1 asked, for squid use this:

acl localnet src 100.0.0.0/8
reply_body_max_size 5242880 deny localnet # deny download of 1mb and above,
http_access allow localnet

I would recommend to GO with Queues and mangle rules, this way nothing will gonna be blocked, but scaling back bandwidth based on how much data has passed through the connection to make downloading large files painful for the cable.net users …



Disable HOTSPOT Users based who donot have comments “PAID”

# Script source: http://forum.mikrotik.com/viewtopic.php?f=9&t=82129
# To block HOTSPOT users who donot have comments "PAID" in there comment box
# Syed Jahanzaib / aacable@hotamil.com / https://aacable.wordpress.com

/ip hotspot user
:foreach i in=[find] do={
:local username [get $i name]
:if ([get $i comment]~"paid") do={
} else={
:log warning "$username..."
/ip hotspot user disable $username
}
}

##################################################################
BELOW SCRIPT IS ORIGINAL VERSION OF ABOVE MODIFIED SCRIPT,
SCRIPT SOURCE: MIKROTIK FORUM
##################################################################

:local username
:local userunpaid

:foreach i in=[/ip hotspot user find] do {
:set username ( username [ip hotspot user get $i name])
:if ([/ip hotspot user get [/ip hotspot user find name=$username] comment] != "paid") do {
:foreach j in=[/ip hotspot active find] do {
:set userunpaid ( userunpaid [ip hotspot active get $j user])
:if (username = userunpaid) do {
[/ip hotspot active remove [/ip hotspot active find user=$userunpaid]]
:log info "User $userunpaid was removed from active list due to payment delay"
}}}}}

Mikrotik Hotspot: Script to disconnect previously logged user if same id is used at second device

It will automatically remove first logged in user automatically , if the same id is logged in from 2nd computer.
[add it in hotspot user profile ON LOGIN SCRIPT]

# Syed Jahanzaib
# Hotspot script to remove duplicate users - Script take from mikrotik forums with Minor changes
# 7-NOv-2017
:local uname $user;
:local usercount 0;
:local usertime "00:00:00";
:local kickable;
:local maxuser 2;

:foreach i in=[/ip hotspot active find user=$uname] do= {
:local curup [/ip hotspot active get $i uptime];
:if ( $curup > $usertime ) do={
:set usertime $curup;
:set kickable $i;
}
:set usercount ($usercount+1);
}
:if ($usercount >= $maxuser) do={
log error "Duplicate Login user found: $uname ($usercount/$maxuser- Time > $usertime) - Now kicking ... !!!";
log error "Duplicate Login user found: $uname ($usercount/$maxuser- Time > $usertime) - Now kicking ... !!!";
log error "Duplicate Login user found: $uname ($usercount/$maxuser- Time > $usertime) - Now kicking ... !!!";
/ip hotspot active remove numbers=$kickable;
} else {
:log info "HOTSPOT user logged-in ID = $uname ($usercount/$maxuser)";
}

Mikrotik Script to disconnect hotspot user if its already active in pppoe

# Check if this hotspot user is already logged in on PPPOE on same mikrotik, then kick HOTSPOT 7 log in window
:local kickable;
:local uname $user;
:local u;
:foreach u in=[/ppp active find name=$user ] do={
:log warning "$user ID is already active in pppoe. Now disconnecting this user from HotSpot ... Done!"
:foreach i in=[/ip hotspot active find user=$uname] do= {
/ip hotspot active remove numbers=$i;
}
}

Remote Radius server offline – enable local ppp secrets !!!

Question was

“Using radius server with pppoe and have set the clients with ppp secret disabled but if radius server goes offline clients cannot authenticate, so I would like to use netwatch to monitor the IP address of radius server and if unreachable to run script to enable ppp client secrets , any advice is most welcome”

Answer was simple:

You can create a for i loop and add it in netwatch.
Example: (copy paste version)

ROS Code:

/tool netwatch
add comment="Netwatch script to detect Radius status and act accordingly" disabled=no down-script=":log error \"RADIUS not responding, enabling local users in SECRET section of PPP/zaib\"\r\
\n/ppp secret\r\
\n:foreach i in=[find] do={\r\
\n/ppp secret enable \$i\r\
\n}\r\
\n:log warning \"All PPP acounts are now enabled.\"" host=192.168.1.2 interval=1m timeout=2s up-script=":log error \"RADIUS is now ONLINE. Enabling local users in SECRET section of PPP/zaib\"\r\
\n/ppp secret\r\
\n:foreach i in=[find] do={\r\
\n/ppp secret disable \$i\r\
\n}\r\
\n:log warning \"All local PPP acounts are now DISABLED.\""

host=192.168.1.2 [change this ip to match your local ip address]
You can adjust the timings and timeout values as per your requirements.
But do remember this is just an workaround with some manual overhead management of keeping all users accounts replica to local mikrotik. As rextended mentioned, If resources allows, you should consider in having a cluster base radius , so in case of any single server failure, its replica or other clsuter node should reply to mirkotik seamless. Also Virtualization is very best for clustering like ESXI base High Availability :D or something like this.


.

Download Mikrotik Upgrade package via command in ROS [26/8/2014]

You can use following command to download upgrade package from the mikrotik CLI.
It’s Useful to upgrade old ROS versions like 5.x.
(Following example is for mipsbe CRS series, RB4xx series, RB7xx series, RB9xx series, RB2011 series, SXT, OmniTik, Groove, METAL, SEXTANT)

for 5.x

/tool fetch mode=http url=http://download2.mikrotik.com/routeros/6.18/routeros-mipsbe-6.18.npk

for 6.x

/tool fetch mode=http url=http://download2.mikrotik.com/routeros/5.26/routeros-powerpc-5.26.npk

to check latest version, see following url

http://www.mikrotik.com/download

18- Multiple WAN ISP’s link with SAME GATEWAY [03/10-OCT/2014]

If you have multiple ISP’s link with SAME gateway, then you can add routes like this.

/ip route gateway=1.1.1.1%ether1 distance=1
/ip route gateway=1.1.1.1%ether2 distance=2

Note: 1.1.1.1 is ISP gateway, and ether1 and ether2 are the interfaces connected with ISP1 and ISP2.

.


19- Print/Find WAN ip (if you have multiple wan IP assigned on same wan interface] [10th Jan, 2015]

/ip address
:foreach i in=[ find interface=ether1] do={
:local ip [get value-name=address $i]
:local status [ get value-name=disabled $i]
:if ($status = false) do={
:log error "ip address $ip"
}
}

Note: Change the WAN (ether1) interface if required.


20- Print/Find (pppoe dialer base) WAN IP address [10th Jan, 2015]

:local wanip [/ip address get [/ip address find where interface=pppoe-out1] address];
:set wanip [:pick $wanip 0 ([:len $wanip]-3) ];
#whatever you want to do with said IP goes here
:log warning "Your PPPoE base WAN IP address is $wanip"


21- Script to disconnect all Hotspot Active Users

# Script to Disconnect all Active users in HOTSPOT
# Syed Jahanzaib / aacable@hotamil.com / https://aacable.wordpress.com
:foreach i in=[/ip hotspot active find] do={
/ip hotspot active remove $i;
:log warning "zaib / Hotspot Scripts executed and following user have been kicked >>>   $i "
}
}

21 – Mikrotik 10g SFP+ supported card for x86 Box

10 G LAN Card that is working on Mikrotik RouterOS

  • Brand: Intel
  • Model: X520
  • Ports: Dual interface

mikrotik - 10g sfp+ card x520.jpg

mikrotik - 10g sfp+ card x520 - part2.jpg


22-

If you have mikrotik PCC to load balance multiple WAN links, then user may face problem login to FBR IRIS site. You can bypass the Login site from the PCC which will force it to use single wan link , that is DEFAULT route.

/ip firewall address-list
add address=72.255.0.0/16 list=pcc_exempted
add address=iris.fbr.gov.pk list=pcc_exempted
/ip firewall mangle
add action=accept chain=prerouting dst-address-list=pcc_exempted

Move above rules on TOP.

23- Monitor LOG & email upon admin user logged in

Schedule this script to run every few seconds like 10 seconds. This will check if winbox user is logged in, it will send email once, next email will be generated depend on the counter for active users in winbox.

Make sure you have working email configuration in the mikrotik /tools/email section

# Base script by rextended on Mikrotik Forum
# modified slightly to accommodate local need
:global EMAILSENTFLAG
:log warning message=("Scipt Starts to check Logged In users");
:local tmpAllTheUsersLogged value=[/user active find];
:if ([:len $tmpAllTheUsersLogged] > 0) do={
:local tmpMessage value="";
:foreach tmpArrayItem in=$tmpAllTheUsersLogged do={
:set $tmpMessage value=($tmpMessage.[/user active get value-name=name $tmpArrayItem]." logged from ".[/user active get value-name=when $tmpArrayItem]." via ".[/user active get value-name=via $tmpArrayItem]."\r\n");
};
:set $tmpMessage value=("Logged user(s) ".[/system clock get date]." ".[/system clock get time]."\r\n".$tmpMessage);
:if ($EMAILSENTFLAG != "true") do={
:log info message=$tmpMessage;
/tool e-mail send from="YOURGMAILUSER@gmail.com" to="YOUR_EMAIL@XYZ.com.pk" subject=("Logged user(s) report of ".[/system clock get date]." ".[/system clock get time]) body=$tmpMessage;
:global EMAILSENTFLAG value="true";
};
} else={
:global EMAILSENTFLAG value="false";
};
:log warning message=("Script Ends here to check Loggedin users");

Result:

loged in user report.PNG


24- Delete BUSY leases from Mikrotik DHCP

Script#1

:log warning "Checking bogus entries in DHCP server. This script will delete DHCP Bogus entries if found after every hour.... ZAIB"
:local busyaddr [ip dhcp-server lease find status="busy"]
:local i
:foreach i in $busyaddr do={
/ip dhcp-server lease remove $i;
}

Script#2

:log warning "Checking bogus entries in DHCP server. This script will delete DHCP Bogus entries if found after every hour.... ZAIB"
:foreach i in=[/ip dhcp-server lease find status=busy] do={
:if ([:len [/ip dhcp-server lease get $i mac-address]] = 0) do={
/ip dhcp-server lease remove $i;
}
}

25- detecting ROGUE dhcp in LAN

DHCP Alerts: If you are running DHCP on your mikrotik, & wan to detect any rogue dhcp on your LAN, you can set alert like below …

/ip dhcp-server alert
add alert-timeout=1m disabled=no interface=vlan1 on-alert=":log warning \"another DHCP detected on LAN...\""

:timeout value means that after 1 minute , alert will turn off but will turn on again if the rogue dhcp still active.


26- Print Firewall Address List based on Comments

Example if we have multiple address lists, and we want to print only specific list whose comment is “my_x_list”, use below cmd in terminal window

 /ip firewall address-list print where comment="my_x_list" 

HTH,
SYED JAHANZAIB

 

58 Comments »

  1. thanks bhai….
    lkin bhai mujhy lagta hai is mai 1 mistake hai aap virus chain bana na bhool gy hai shyd….

    Like

    Comment by usmans — August 28, 2011 @ 12:53 AM

    • It was left intentionally,

      Like

      Comment by Pinochio / zaib — August 28, 2011 @ 10:53 AM

      • Syed sir, i’d like to know how to Limit number of failed pppoe logon attempts. plz help me sir

        Like

        Comment by aayush — November 25, 2014 @ 9:18 AM

  2. hahahaha….

    Like

    Comment by usmans — August 28, 2011 @ 2:03 PM

  3. is coding ko copy kar ke new terminal main paste karo ga to kiya ye command working kare ge ???

    Liked by 1 person

    Comment by Arshad — November 22, 2011 @ 3:55 PM

  4. Hmm most of rules works fine without any modification.

    However any rule which is specific to any interface or have IP address mentioned, Just change them according to your network ip scenario.

    Like

    Comment by Pinochio~:) — November 22, 2011 @ 6:34 PM

  5. and where the fk i put the codes ?

    Like

    Comment by djgh — January 5, 2012 @ 7:49 PM

  6. Salam Syed…..
    I’ve been following your mikrotik articles since last nite. I’m still very new to it, so as 1st step i’d like to learn how to protect the router n customers as shown in wiki. Seems to me you make it quite simple. I’m still confuse how to put rule one after another specially as shown in wiki, because those are written separately. I mean rules like :
    /ip firewall filter
    add chain=forward connection-state=established comment=”allow established connections”
    add chain=forward connection-state=related comment=”allow related connections”
    add chain=forward connection-state=invalid action=drop comment=”drop invalid connections”
    then rules rules rules are here……… then close by this rule :
    add chain=forward action=drop comment=”drop everything else”
    Yes….. i got it from wiki-protecting your customers.
    After “drop everything else” then for the same rule chain-forward-drop….. MT will ignore, right?

    Syed…. I’ve gotta learn everything i need in mikrotik like ASAP, just thing that i need to manage the network, mostly security issue due to viruses and filtering , of course far away from you’ve been describing in your blog :), which i found so so sophisticated.

    Ok, enough saying, i’ll get back to my MT n learning what you showed me…
    You don’t mind if i ask u some question later, right?
    Many thanks man….. U r awesome

    Like

    Comment by xekender — March 25, 2012 @ 10:51 AM

    • When you apply any rule in mikrotik, you have to first get into its related folder to execute command,
      for example when you type command
      /ip firewall filter

      then you will get into firewall filter menu,
      now when you type any rule (without menu) it will be executed under firewall filter category.
      so once i get into /ip firewall filter category and now when i will add any rule it will be treated as firewall filter rule. e.g:

      /ip firewall filter
      add chain=forward connection-state=established comment=”allow established connections”

      input and forward and different chains.
      to understand them correctly you have to first understand how CHAINS works in it.

      http://www.mikrotik.com/testdocs/ros/2.9/ip/flow.php

      Like

      Comment by Syed Jahanzaib / Pinochio~:) — March 25, 2012 @ 4:52 PM

  7. how to make virus chain which u have left plz tell me

    Liked by 1 person

    Comment by SHAFQAT FARHAN — May 22, 2012 @ 9:43 AM

  8. Hi Syed,

    How can I see the list of the infected PC in src-address-list=Worm-Infected-p445?

    Thanks.

    Like

    Comment by iangranger — July 7, 2012 @ 12:21 PM

  9. I can see the Worm-infected IP addresses in /ip firewall address list. They are all public IP addresses and not our within the LAN, should I create a firewall rule to block those infected public ip addresses?

    Thanks.

    Like

    Comment by iangranger — July 8, 2012 @ 6:50 AM

  10. for virus flooding 5 packets is acceptable for all users or it given for an example only , in above script

    Like

    Comment by tamilmaran — July 17, 2012 @ 9:10 AM

    • You should increase this number as per your network requirements.

      Like

      Comment by Syed Jahanzaib / Pinochio~:) — July 18, 2012 @ 8:49 AM

      • After i added the script
        /ip firewall mangle
        add action=add-src-to-address-list address-list=Worm-Infected-p445 address-list-timeout=1h chain=prerouting connection-state=new disabled=no dst-port=445 limit=5,10 protocol=tcp

        /ip firewall filter
        add action=drop chain=forward disabled=no dst-port=445 protocol=tcp src-address-list=Worm-Infected-p445
        add action=drop chain=forward disabled=no dst-port=445 protocol=tcp src-address-list=Worm-Infected-p445

        I’m getting ip address having wan ips like 14.102.17.xxx ,188.124.109.xxx
        my client IP’s are not logged, how could i log my client ip..

        Even in firewall -> Connections also i’m getting wan ip’s only, i’m not getting any client lan ip’s.

        Like

        Comment by tamilmaran — July 18, 2012 @ 7:46 PM

  11. how to block ping mikrotik between client

    Like

    Comment by abdElrahman — December 26, 2012 @ 10:10 PM

  12. Dear Sayd,
    I’m planning to deploy the following configuration
    Mikrotik hotspot connected to a cheap AP for example dlink-2100 without security key (for advertising purpose)
    the problem is that if a hijacker put an AP with same SSID the customers would connect to the hijacker’s AP and with a fake page he can steal the login information.

    Question1: Is there a simple configuration (smartphones laptops) on the client side that can share information JUST with my hotspot server?

    Question2: Adjusting my hotspot subnet to 255.255.255.255 will it stop a hijacker from sniffing the clients private information(emails, passwords…)?

    Like

    Comment by Mohamad Hassan — February 27, 2013 @ 5:50 AM

  13. Jahanzaib bhai what IP to place here instead of 10.10.0.4?

    # Blocking ICMP Traffic, saves you from many headaches
    14
    add action=drop chain=input comment=”DROP PING REPLY” disabled=no protocol=icmp src-address=!10.10.0.4

    Like

    Comment by M. Saeed. K — March 3, 2013 @ 7:13 PM

  14. I just want to say, thank you Syed Jahanzaib!

    Like

    Comment by eax — May 31, 2013 @ 5:38 PM

  15. hi,,,for the management ip address..can one put a range..of ips.

    Like

    Comment by michael mugambi — August 16, 2013 @ 1:52 AM

  16. Hi

    you wrote two same rules with same PROTOCOL in

    “A BETTER APPROACH ON BLOCKING PORTS !

    /ip firewall filter
    add action=drop chain=forward disabled=no dst-port=445 protocol=tcp src-address-list=Worm-Infected-p445
    add action=drop chain=forward disabled=no dst-port=445 protocol=tcp src-address-list=Worm-Infected-p445 ”

    But i believe you meant this (changing protocol), right?

    /ip firewall filter
    add action=drop chain=forward disabled=no dst-port=445 protocol=TCP src-address-list=Worm-Infected-p445
    add action=drop chain=forward disabled=no dst-port=445 protocol=UDP src-address-list=Worm-Infected-p445

    Like

    Comment by Umer Sarwar — November 20, 2013 @ 6:24 PM

  17. HOW WE CONNECT iSP ADMIN WITH MIKROTIK

    Like

    Comment by eBAD — November 22, 2013 @ 8:23 PM

  18. Thank you for taking the time to do this… Its greatly appriciated

    Like

    Comment by Daniel — March 16, 2014 @ 4:20 PM

  19. Hello
    How can I prevent some malicious network of customer use Mac
    Surfs the Internet and enter freely
    Where Mac Ip spam equals Mac client and Ip
    If you allow Avodona
    Thank you

    Like

    Comment by ابو خالد العامري — August 27, 2014 @ 10:41 PM

  20. Hello
    This problem, which I suffer of them my friends
    I image
    Merged
    Please give me resolve this problem
    Thank you
    https://drive.google.com/file/d/0B3Mk8MFFqNDpdmUtZGxEZ3dxSW8/edit?usp=sharing

    Like

    Comment by ابو خالد العامري — August 28, 2014 @ 6:33 PM

  21. In some people
    Asttaau Ihamo Hbacthm
    This section can be seen

    Like

    Comment by ابو خالد العامري — August 28, 2014 @ 6:46 PM

    • first, thank you so much for your post. but in “Howto Block Torrent / P2P” i follow you script but users can download torrent without permit. can you show more about this

      Like

      Comment by ponlork — August 30, 2014 @ 10:31 AM

    • just limit the number of IPs in the hotspot to 1, you may use the following command

      /ip ho set nu=1 addresses-per-mac=1

      Like

      Comment by Hatem — July 16, 2016 @ 7:18 PM

  22. i want control torrent not block plz

    Like

    Comment by Yasser Hamouda — November 9, 2014 @ 4:37 AM

  23. how can i block content in mikrotik

    Like

    Comment by Adnan Malik — January 22, 2015 @ 12:28 PM

  24. plz send me illegal content list, so i can insert the content list in mikrotik.

    Like

    Comment by Adnan Malik — January 22, 2015 @ 12:30 PM

  25. I need your help, … How can I blok user with active hosname.

    Like

    Comment by ade — January 22, 2015 @ 11:20 PM

  26. dear MR Syed Jahanzaib iwant backup from your MT plz

    Like

    Comment by Huny Mohamed — January 31, 2015 @ 4:29 AM

  27. Hi i have a problem with my RB1100AHx2. when i just plug the WAN Interface i have a traffic up to 2Mo on Wan interface. you can see it on this screenshot http://netonecameroon.net/temp/Ghost_traffic.png
    I need help

    Like

    Comment by lex — April 9, 2015 @ 8:47 PM

    • PROBABLY SOME FLOOD/STORM. FIRST DISABLE ANY NAT RULE WHICH IS ALLOWING INTERNET ACCESS , THEN SEE IF IT MAKES ANY DIFFERENCE, OTHERWISE CONTACT THE ISP.

      Like

      Comment by Syed Jahanzaib / Pinochio~:) — April 11, 2015 @ 2:56 PM

    • first Unplug your LAN side and then monitor,
      If the values dont get normal, then contact your ISP to check for flooding from there end.

      Like

      Comment by Syed Jahanzaib / Pinochio~:) — April 14, 2015 @ 1:01 PM

      • I have already unplug the LAN port and the traffic on my WAN is still 2M.i have called my ISP and he told me that the problem is in my side and it can be my mikrotik who is in fault.i have changed my RB1100AHx2 and restore the precedent configuration of the first one on it, and the traffic back normal.but i would want to know what is append with the first router.thks

        Like

        Comment by lexcyr — April 14, 2015 @ 1:20 PM

  28. Howto Block Torrent / P2P: This first script is not working the CPU load goes on to 100% when apply this script.

    Like

    Comment by Muhammad Shakeel — May 21, 2015 @ 5:36 PM

  29. I have used SCRIPT to disconnect previously logged user if same id is used at second computer in hotspot but it’s not working. please help me some

    Like

    Comment by Forhad — August 15, 2015 @ 3:45 PM

  30. sir mene ip binding ki hai lekin users ko full speed ja rahe hai mein chahta hu k jo users ip binding mein hain un ko b limited speed du to ye kese mumkin hai

    Like

    Comment by softbrw — August 28, 2015 @ 12:01 PM

  31. I did

    /ip firewall address-list
    add list=management-servers address=10.10.0.1
    add list=management-servers address=192.168.0.103

    /ip firewall filter
    add chain=input src-address-list=management-servers protocol=tcp dst-port=21,22,23,80,443,8291 action=accept

    add chain=input protocol=tcp dst-port=21,22,23,80,443,8291 action=drop

    and now i cant access my mikrotik
    the IP from my PC is 192.168.0.103, and i left that 10.10.0.1 from your network
    I’ve tried to do change my IP to 10.10.0.1 also and no luck

    what am i doing wrong? i dont want to hard reset my router.

    Like

    Comment by Gonzalo — December 7, 2015 @ 10:28 AM

  32. Dear Syed ji,

    I am facing one problem in mikrotik router. I have mikrotik router and dma softlab radius manager. My user didn’t disconnect automatically when data has finished but they disconnect on data has been expired. give me a solution please. and also queue are not synchronize. i have api user authentication.

    jDilip

    Like

    Comment by Dilip — February 14, 2016 @ 8:39 AM

    • put radius incoming port 1700 , all things will goes fine

      Like

      Comment by ahmed — April 6, 2016 @ 1:57 AM

  33. /ip dns
    set allow-remote-requests=yes cache-max-ttl=1w cache-size=4096KiB \
    max-udp-packet-size=2048 servers=8.8.8.8
    /ip dns static
    add address=10.0.0.1 disabled=no name=ns1.xxxxxxxxxx.local ttl=1d
    add address=10.0.0.1 disabled=no name=ns2.xxxxxxxxxx.local ttl=1d

    it is best aproch for dns setting

    Like

    Comment by Samar Khan — November 29, 2016 @ 4:21 AM

  34. /ip dns
    set allow-remote-requests=yes cache-max-ttl=1w cache-size=4096KiB \
    max-udp-packet-size=2048 servers=8.8.8.8
    /ip dns static
    add address=10.0.0.1 disabled=no name=ns1.XXXXXXX.local ttl=1d
    add address=10.0.0.1 disabled=no name=ns2.XXXXXXX.local ttl=1d

    Like

    Comment by Samar Khan — November 29, 2016 @ 4:24 AM

  35. hello i am recently installed a mikrotik router RB2011 Ui AS. i have a CIR connection from the ISP i have assigned port # 2 to be my WAN port and then i have created a bridge that allows my traffic through my ethernet ports out through the WAN port. But that Wan to Ethernet port is currently generating alot of unwanted traffic and as a result is consuming most of my bandwidth. can you help me in this regard what should i do to stop the broadcasting/multicasting traffic and receive the actual bandwidth.

    Like

    Comment by Benedict Frederick. — January 12, 2017 @ 12:48 PM

  36. hi , I need to Disable users to Download with Internet download manager, Could you hep me

    Like

    Comment by Waleed — April 12, 2017 @ 11:47 AM

  37. Hello, i tried script 14 ( for hotspot user disable based on PAID comment). It does not work, only the default trial user get logged. Can you give me some help with this?

    Like

    Comment by subarov — June 3, 2017 @ 7:36 PM

  38. Good morning, please I need help with my mikrotik
    1. Creating a hot spot connection on vm and assigning users gives no issue at all where all user manager users with a time span are not timed out until the span is expires.

    The problem: Implementing it on a RB750r2 board gives me serious issues because all users get timed out 5 minutes at least 6 times a day where as the idle time out was set to 1hr and session time out set to open 1hr.

    Observation: Since it works without no issue on vmware, is it likely that the mikrotik RB750 have some bugs in it because it happens on every RB750 I have used so far or I am missing something.

    I have tried complaining to the company that sold me the board but they have no solution. I had to be using authentication by MAC addresses which it’s rather uncomfortable for me.

    Is there anything I’m missing.

    Thank you

    Like

    Comment by Ajaguna Jeffery — June 20, 2019 @ 12:28 PM

  39. […] Mikrotik Firewall / Short Notes + Scripts | Syed Jahanzaib … […]

    Like

    Pingback by Login Timeout Mikrotik - loginen.com — April 14, 2022 @ 6:41 PM


RSS feed for comments on this post. TrackBack URI

Leave a comment