Syed Jahanzaib – Personal Blog to Share Knowledge !

February 11, 2014

Blocking Facebook/Youtube OR OTHER sites via automated address-list in Mikrotik

Filed under: Mikrotik Related — Tags: , , , , — Syed Jahanzaib / Pinochio~:) @ 9:18 AM

bfb

Last Updated: 20-DEC-2016

Update: The script for youtube also adding translate.google.com in the list too. workaround is to either edit the script, or make an ACCEPT rule before the deny rule, which should accept traffic going to translate.google.com ip addresses. 

Recently I was providing mikrotikr related deployment support for an remote African 🌍 network where we configured hotspot for school students & the management wanted to block access to Facebook / Youtube & adult web sites for increased productivity.

Blocking adult websites was easy by redirecting DNS requests to OPENDNS  but blocking facebook was a bit tricky because some people from the management wanted to have its access open for specific users. I preferred to have a address-list with the FB/YT server’s ip addresses using automated script.This way I have more control for these destinations for multi purpose. Example in Filter Rule I created DENY rule  for traffic going to specific Destination list for all SOURCE address EXCEPT ALLOWED one.

Solution was to create two scheduled scripts which will pick facebook/youtube related dns entries from the Mikrotik DNS cache and add it in “facebook/youtube” address lists & we used these address list in the FILTER rule to either allow/block based on the source address list.

 


SCRIPT :

The below script(s) (which can be scheduled to run after every 5 or X minutes) will create a address list which will contain facebook/youtube server ips and afterwards an Firewall Filter rule will block request going to these destinations (using address list feature). To create this address list, it is required that your users must be using your mikrotik DNS as their primary dns , or make a dst-nat rule that forcefully route user dns (udp 53) requests to local mikrotik dns (forced dns redirection).


FOR FACEBOOK ~

# Script to add target web sites DNS IP addresses into address list
# Tested with Mikrotik 6.3x
# Syed Jahanzaib / aacable@hotmail.com
# List name
:local LISTNAME "facebook"

# Web site names which will be added in address list
:local TARGET1 "facebook.com"
:local TARGET2 "fbcd.net"

# 1st time runner, check if address list is not created previously and add entries in it for 1st time usage
:if ( [/ip firewall address-list find where list=$LISTNAME] = "") do={
:log warning "No address list for $TARGET1 and $TARGET2 found ! creating and adding resolved entry for 1st time usage ... zaib"

:resolve $TARGET1
:resolve $TARGET2

/ip firewall address-list add list=$LISTNAME
} else={
:log warning "Previous List for $LISTNAME found ! moving forward and checking if DNS entries can be added in it ..."
}

# Check DNS entries and collect matching names
:foreach i in=[/ip dns cache all find where (name~"$TARGET1" || name~"$TARGET2") && (type="A") ] do={

# Get IP Address from the names and hold it in temporary buffer
:local Buffer [/ip dns cache get $i address];
delay delay-time=10ms

# Check if entry is already not exists, then OK, otherwise ignore duplication
:if ( [/ip firewall address-list find where address=$Buffer] = "") do={ 

# Fetch DNS names for the entries
:local sitednsname [/ip dns cache get $i name] ;

# Print name in LOG window
:log info ("added entry: $sitednsname $Buffer");

# Add IP addresses and there names to the address list
/ip firewall address-list add address=$Buffer list=$LISTNAME comment=$sitednsname;
}
}

FOR YOUTUBE ~

# Script to add target web sites DNS IP addresses into address list
# Tested with Mikrotik 6.3x
# Syed Jahanzaib / aacable@hotmail.com
# List name
:local LISTNAME "youtube"

# Web site names which will be added in address list
:local TARGET1 "youtube.com"
:local TARGET2 "googlevideo.com"

# 1st time runner, check if address list is not created previously and add entries in it for 1st time usage
:if ( [/ip firewall address-list find where list=$LISTNAME] = "") do={
:log warning "No address list for $TARGET1 and $TARGET2 found ! creating and adding resolved entry for 1st time usage ... zaib"

:resolve $TARGET1
:resolve $TARGET2

/ip firewall address-list add list=$LISTNAME
} else={
:log warning "Previous List for $LISTNAME found ! moving forward and checking if DNS entries can be added in it ..."
}

# Check DNS entries and collect matching names
:foreach i in=[/ip dns cache all find where (name~"$TARGET1" || name~"$TARGET2") && (type="A") ] do={

# Get IP Address from the names and hold it in temporary buffer
:local Buffer [/ip dns cache get $i address];
delay delay-time=10ms

# Check if entry is already not exists, then OK, otherwise ignore duplication
:if ( [/ip firewall address-list find where address=$Buffer] = "") do={ 

# Fetch DNS names for the entries
:local sitednsname [/ip dns cache get $i name] ;

# Print name in LOG window
:log info ("added entry: $sitednsname $Buffer");

# Add IP addresses and there names to the address list
/ip firewall address-list add address=$Buffer list=$LISTNAME comment=$sitednsname;
}
}

SCHEDULER:

Schedule the script to run after every 5 minutes.

/system scheduler
add disabled=no interval=5m name=facebook-script-run-schedule on-event=facebook policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api start-date=feb/11/2014 start-time=00:00:00
add disabled=no interval=5m name=youtube-script-run-schedule on-event=youtube policy=ftp,reboot,read,write,policy,test,winbox,password,sniff,sensitive,api start-date=feb/11/2014 start-time=00:00:00

FILTER RULE:

Now create a FIREWALL FILTER rule which will actually DROP the request (in FORWARD CHAIN) going to facebook OR youtube address list.

[Make sure to move this rule on TOP , or before any general accept rule in Filter section)

/ip firewall filter
add action=drop chain=forward comment=Filter Rule to block FB address LIST : ) disabled=no dst-address-list=facebook
add action=drop chain=forward comment=Filter Rule to block YOUTUBE address LIST : ) disabled=no dst-address-list=youtube

[/sourcecode]

Now try to access the facebook, it may be open as usual, but as soon as the script will run, a address list will be created with the FB ip address list, & its access will be blocked.
As showed in the image below …

fir

filter-rule

 


TIP#1

TIME BASE FILTER RULE

You can also use this technique to block FB in some specific timings only. For example you want to block access to FB from 9am to 10:am then use the following filter rule.

/ip firewall filter
add action=drop chain=forward comment=Filter Rule to block FB address LIST : ) disabled=no dst-address-list=facebook time=9h-10h,sun,mon,tue,wed,thu,fri,sat

TIP#2

Force / Redirect users to use your DNS

/ip firewall nat
add action=redirect chain=dstnat comment="FORCE DNS TO LOCAL MIKROTIK DNS SERVER" dst-port=53 protocol=udp to-ports=53

TIP#3

Create Windows Update List using Scheduled Script (run every 5 minutes and fetch servers list from local dns cache) [Older post]

Note: Make sure your users are using mikrotik as there primary dns server

# Script to add target web sites DNS IP addresses into address list
# Tested with Mikrotik 6.4x
# Syed Jahanzaib / aacable@hotmail.com
# List name
:local LISTNAME "windowsupdateslist"
# Web site names which will be added in address list
:local TARGET1 "update.microsoft.com"
:local TARGET2 "download.windowsupdate.com"
:local TARGET3 "download.microsoft.com"
:local TARGET4 "windowsupdate.com"
:local TARGET5 "ntservicepack.microsoft.com"
:local TARGET6 "wustat.windows.com"
:local TARGET7 "stats.microsoft.com"
:local TARGET8 "mp.microsoft.com"
:local TARGET9 "ws.microsoft.com"
:local TARGET10 "sls.update.microsoft.com.akadns.net"
:local TARGET11 "vortex.data.microsoft.com"
:local TARGET12 "vortex-win.data.microsoft.com"
:local TARGET13 "fe2.update.microsoft.com.akadns.net"
:local TARGET14 "statsfe2.update.microsoft.com.akadns.net"

# 1st time runner, check if address list is not created previously and add entries in it for 1st time usage
:if ( [/ip firewall address-list find where list=$LISTNAME] = "") do={
:log warning "No address list for $TARGET1 found ! creating and adding resolved entry for 1st time usage ... zaib"

:resolve $TARGET1

/ip firewall address-list add list=$LISTNAME
} else={
:log warning "Previous List for $LISTNAME found ! moving forward and checking if DNS entries can be added in it ..."
}

# Check DNS entries and collect matching names
:foreach i in=[/ip dns cache all find where (name~"$TARGET1" || name~"$TARGET2" || name~"$TARGET3" || name~"$TARGET4" || name~"$TARGET5" || name~"$TARGET6" || name~"$TARGET7" || name~"$TARGET8" || name~"$TARGET9" || name~"$TARGET10" || name~"$TARGET11" || name~"$TARGET12" || name~"$TARGET13" || name~"$TARGET14") && (type="A") ] do={

# Get IP Address from the names and hold it in temporary buffer
:local Buffer [/ip dns cache get $i address];
delay delay-time=10ms

# Check if entry is already not exists, then OK, otherwise ignore duplication
:if ( [/ip firewall address-list find where address=$Buffer] = "") do={

# Fetch DNS names for the entries
:local sitednsname [/ip dns cache get $i name] ;

# Print name in LOG window
:log info ("added entry: $sitednsname $Buffer");

# Add IP addresses and there names to the address list
/ip firewall address-list add address=$Buffer list=$LISTNAME comment=$sitednsname;
}
}

Schedule above script in scheduler to run every few minutes. Then you can use this list to perform various functions like block them, or queue them by marking pkts. ZAIB


If this method helped you, please do let me know. your comments, tips for improvements etc are most welcome.

Regard’s
Syed Jahanzaib

50 Comments »

  1. Hello Sayed,

    Its cool checking it out.

    For https blocking intrusion prevention system like snort/suricata also work well.

    Am the author of simplewallsoftware. Simplewall is integration of squid + suricata for https blocking.

    Liked by 1 person

    Comment by chetan M — February 11, 2014 @ 9:28 AM

    • HI

      After upgrading to 6.18 script adds more than just facebook entries from the dns cache.

      Like

      Comment by Daryl — August 4, 2014 @ 6:26 PM

  2. Great post Jahanzeb Bhai !

    Just want to know if you can help me that how to block the facebook on certain IPs or IP Pool or specific IP ? If you mention this it will be more helpful. Thanks in Advance

    Like

    Comment by Qamar — February 11, 2014 @ 1:22 PM

    • if you want to block the access for some users only, then simply create a address list with those users (or pool) and in src-address (or src-address list) add them specifically.

      Like

      Comment by Syed Jahanzaib / Pinochio~:) — February 11, 2014 @ 2:00 PM

    • Thanks alot Jahanzeb bhai. In addition to Mikrotik also can you help me with UTM, that which one UTM is best for Mini ISPs ?? I have googled alot and I am going to give a try to Untangle and Sophos ?? Whats your suggestion?

      Like

      Comment by Qamar — February 11, 2014 @ 7:11 PM

  3. Very good idea. I like it. It’s a nice hack-style 🙂
    Congrats

    Like

    Comment by Eol — February 11, 2014 @ 1:41 PM

  4. Things are not working with me properly Jahanzeb Bhai, might be i am not using NAT thats why. The script runs after every 2 minute interval but did not add any IP of Facebook in Firewall/address list

    Kindly post some of the topics regarding the PUBLIC IPs configuration. Also if possible then post the method of configuring the above script if MT is in bridge state or without NAT.

    Like

    Comment by Qamar — February 15, 2014 @ 12:50 PM

  5. hello,
    thank you for your script. Is it possible change it for more webpages? What I have to change to block facebook, badoo, pornhub …. in your script? Thank you for replay. I am sorry for my English.

    Like

    Comment by Zdenda — April 3, 2014 @ 12:55 PM

  6. Hello! Great script! In my contry goverment block many sites, and i use this script to automated add ip’s to block sites address list(i’m use routing policy and vpn)).
    I would like the script to read a list of domains from a file stored at the mikrotik. Could you help me with this?
    I apologize for my English. Translated through google.com.

    Like

    Comment by poisons — April 24, 2014 @ 8:58 PM

  7. Thanks Jahanzeb bhai for your nice idea for blocking https://facebook.com. But, I want to block https://youtube.com in same way. Is it possible?

    Like

    Comment by Hasan Shahriar — August 6, 2014 @ 10:15 AM

  8. HI

    After upgrading to 6.18 script adds more than just facebook entries from the dns cache.

    Is it fixable.

    Like

    Comment by Amer — August 6, 2014 @ 5:32 PM

  9. Hi.
    Thanks for your great idea for blocking.
    But script doesn’t work correctly since ROS v 6.17 or 6.18. Perhaps, there was some upgrades in console i think. Could you fix it?

    Like

    Comment by Ananas — August 29, 2014 @ 10:55 PM

  10. Sorry

    Not working

    Like

    Comment by afistan — September 14, 2014 @ 12:20 PM

  11. Salam Syed any updates concerning the script? it is not working for version 6.19 as well
    Regards,

    Like

    Comment by Maroon — October 2, 2014 @ 5:34 PM

  12. This script not work in Routeros 6.18 , please correct

    Like

    Comment by Mateito — October 3, 2014 @ 7:34 AM

  13. i try this script to block https://twitter.com but not working. My Riuter V 5.26

    Like

    Comment by Zulkifli — October 28, 2014 @ 5:06 PM

  14. Dear sir, May i ask you the questions please? I want to allow Only 11:30am – 1:00pm LAN-Client can access on Facebook and i do not allow them for work time 1:30pm-5:00pm every day. can you help me?

    Like

    Comment by Bin Sophon — October 29, 2014 @ 2:55 PM

  15. And I want to do it on mikrotik router but when i tried for long time is still not complete yet, even with firewall or proxy server for mikrotik. Hope you will understand.

    Like

    Comment by Bin Sophon — October 29, 2014 @ 3:03 PM

  16. hello syed jahanzaib,

    i have scenario like this :
    i have vpn server (in mikrotik) with static ip, i have rule in my mikrotik only client in address-list can access my vpn server, usually i add manualy when client connect to internet they (our staff info to me about ip public then i add manualy in address-list)
    so i want allow client (our staff) to access where the client have ip internet is dynamic, without info to me about ip public. i want the ip internet from the client is automatic add to adress-list when ip is change.

    can i implement this script to my scenario ? if can, can you explain how can i do this one or you some tutorial like i want

    Best Regards
    Agam

    Like

    Comment by Agam — November 7, 2014 @ 6:07 AM

  17. good work man … 🙂

    Liked by 1 person

    Comment by Costavo Srour — November 14, 2014 @ 7:36 PM

  18. Dear Jahanzeb Bhai, its the great work to block FACEBOOK. But i am having some other problem, as my router is in bridge mode and i am forwarding public IPs. When i apply this rule then it works in case where the client is directly using public ip in their computer. But if the IP is Natted further like the client is using the IP on theif WiFi Router then this rule doesnt work.
    Can you please help with this ??

    Like

    Comment by Qamar — January 5, 2015 @ 2:42 PM

  19. I have some problem when I firewall filter enable for blocking facebook. Some Website are slow down like as booking2.airasia.com . Please answer me how to do that.
    Thank
    Nyinyi

    Like

    Comment by Nyi Nyi — March 21, 2015 @ 1:06 PM

  20. This script not work in Routeros 6.29.1 , please correct
    Greetings from Venezuela

    Like

    Comment by Alfredo Chavez — June 14, 2015 @ 11:26 AM

  21. Dear Syed jhanzab bhai i have problem how i can block video streaming in youtube and specially for facebook. its major problem for me .i am looking for ur feedback…

    Like

    Comment by Muhammad Bilal — February 17, 2016 @ 9:28 AM

  22. Hello Syed
    Would you please explain,
    what the meaning (type=”A”) ??in section # Check DNS entries and collect matching names

    Like

    Comment by Mahdi HarisMahdi — July 29, 2016 @ 3:28 PM

  23. work well. thanks for the script & sharing!

    Like

    Comment by wai — January 18, 2017 @ 12:08 PM

  24. Salam All,

    Facebook script is working fine on latest firmware but script for youtube is not working,

    Like

    Comment by ali shahzad — February 1, 2017 @ 1:02 PM

  25. please guide how to block youtube, if facebook script is working fine then why youtube is not blocked

    Like

    Comment by ali shahzad — February 1, 2017 @ 1:07 PM

  26. thanks Sir, now i can block Youtube, Facebook and dailymotion. Your both scripts are working fine.

    Like

    Comment by ali shahzad — February 1, 2017 @ 2:42 PM

  27. I used the script but do not work well, do no add all DNS entry to the Address List, I can see the entry in the dns cache but in the address list just have 3 entry
    2 of facebook.com, and one for fbcd.net

    this one is in the DNS Cache

    3-edge-chat.facebook.com

    I edit the script for to check the CNAME too

    name~”$TARGET1″ || name~”$TARGET2″) && (type=”CNAME” || type=”A”)

    Like

    Comment by netwolf — February 4, 2017 @ 4:48 AM

  28. Update: still have the same, but is block facebook from the machine that I test when I flush the machine DNS cache

    Like

    Comment by netwolf — February 4, 2017 @ 5:00 AM

    • the list works fine.
      because this scripts depends on DNS , make sure all of your clients are using mikrotik dns as their primary dns. or create a dns redirect rule that redirects all dns traffic to your mikrotik dns. once user will start using your dns, the scheduled script will run and pick the dns name from dns cache and will start to build the list, and eventually it will collect the required addresses.

      Like

      Comment by Syed Jahanzaib / Pinochio~:) — February 7, 2017 @ 9:13 AM

  29. Dear Syed,

    Would you Help me with my case?
    I have 20 users.
    And I would like to apply some rules together simultaneously
    1st rule: Specific user with specific address range, I would like to block YouTube only (allow all other website)
    2nd rule: Specific user with specific address range, I would like to allow YouTube only (block all other website).

    What should I do?

    PS: I can’t use web proxy because I caused my router getting slow.

    Sincerely Yours..

    Like

    Comment by adminpawondasinem — May 9, 2017 @ 8:25 AM

    • you can create youtube address list.
      then create users address list. like usergroup1 and usergroup2.
      now create filter rules and allow the specific lists to specific group.
      you can choose allow and then block, or block all except approach , which ever works for you.

      Like

      Comment by Syed Jahanzaib / Pinochio~:) — May 10, 2017 @ 8:26 AM

  30. […] also another method in which you forcefully divert users dns traffic to your mikrotik dns and use script to fetch ip addresses associated with any URL having whatsapp in it, but I am not discussing it here at a […]

    Like

    Pingback by Blocking WhatsApp in Mikrotik | Syed Jahanzaib Personal Blog to Share Knowledge ! — June 7, 2017 @ 1:26 PM

  31. […] also another method in which you forcefully divert users dns traffic to your mikrotik dns and use script to fetch ip addresses associated with any URL having whatsapp in it, but I am not discussing it here at a […]

    Like

    Pingback by Blocking WhatsApp in Mikrotik – emekzen — June 7, 2017 @ 4:23 PM

  32. […] another method in which you forcefully divert users dns traffic to your mikrotik dns and use script to fetch ip addresses associated with any URL having whatsapp in it, but I am not discussing it here at a […]

    Like

    Pingback by Blocking WhatsApp in Mikrotik | emek — June 14, 2017 @ 4:28 PM

  33. I have place the script and set the scheduler,but the address list has no addresses after many run counts..I am using mikrotik 5.20..
    Please help me Thanks in advance.

    Like

    Comment by Zain — August 19, 2017 @ 7:26 AM

  34. Hello, nice article however I was not able to accomplish the task.
    Unfortunately opendns is now part of cisco hence it will only give 14 days trial.
    That said I have a situation where I need to make my mikrotik as a hotspot as well as filter few sites like facebook, youtube and adult rated sites.
    these sites are https hence no solution worked for me, maybe I did something wrong.
    My wan is Eth1 , my lan1 is ether2 and my hotspot is on ether3
    Could someone give me a full script for mikrotik ?

    Liked by 1 person

    Comment by Taha — September 18, 2017 @ 8:32 PM

  35. Nice Script that helped me but had to make some corrections:

    Put “;” after statements would be better and for it to work you have to move the “:resolve $TARGETn” outside of the “:if” block just after the :local TARGETn declaration.

    Like

    Comment by Pierre Surmont — July 2, 2019 @ 7:11 AM

  36. Hi Thanks for your kind post. I am trying to block youtube and facebook via Layer 7 Protocol. Everything is working fine but youtube is not disabling in google chrome. Please help in this regard.

    Like

    Comment by Muhammad Fawad — March 19, 2020 @ 11:42 PM

  37. not working with latest mikrotik Ver

    Like

    Comment by Sajawal Sarwar — January 3, 2022 @ 12:57 AM


RSS feed for comments on this post. TrackBack URI

Leave a comment