Tuesday, February 28, 2017

How to Block Youtube and Facebook Using Mikrotik DNS Cache

Create script to check DNS cache in Mikrotik, put ni system - scheduler, make it run every 1 minute.
:local ADDRLIST "BLOCKWEBSITE"
:local DOMAIN "youtube.com|facebook.com|fbcdn.net"
# Find CNAME record
:local DOMAINNAME
:foreach i in=[/ip dns cache all find where (name~"($DOMAIN)") && (type="CNAME") ] do={
  :set DOMAINNAME [/ip dns cache all get $i data];
  :set DOMAIN "$DOMAIN|$DOMAINNAME";
   delay delay-time=10ms
}
# Find A record
:foreach i in=[/ip dns cache all find where (name~"($DOMAIN)") && (type="A") ] do={
  :local DOMAINIP [/ip dns cache get $i address];
  delay delay-time=10ms
  :if ( [/ip firewall address-list find where address=$DOMAINIP] = "") do={
    /ip firewall address-list add address=$DOMAINIP list=$ADDRLIST timeout="00:10:00" comment=[/ip dns cache get $i name];
  }
}
Block request to public DNS outside Mikrotik
/ip firewall nat
add chain=dstnat action=dst-nat to-addresses=192.168.123.8 to-ports=53 protocol=tcp dst-port=53
add chain=dstnat action=dst-nat to-addresses=192.168.123.8 to-ports=53 protocol=udp dst-port=53
Block the desired IPs that already listed in address list
/ip firewall filter
add action=drop chain=forward comment="Block Website" disabled=no dst-address-list=BLOCKWEBSITE