Mikrotik: Use host names in the firewall

In case there is a service that should be allowed for disconnected customers is running on a dynamic IP and we can not predict that IP Mikrotik router must be able to recognize the service by the host name it is running on. It is possible on the Mikrotik with a little bit of scripting.

Below are the steps to get it set up (example: www.azotel.com)


(1) Firewall -> Filter Rules

- add two entries that matches address list in both "Src. Address List" and "Dst. Address List"



(3) System -> Script

- add the following script (you can take it from here) with name "resolvehostnames" and "read/write" policy

#delete old address lists
:foreach a in=[/ip firewall address-list find list=host_azotel] do={
  /ip firewall address-list remove $a;
}

:local popServers {"www.azotel.com"};

:foreach popServer in=$popServers do={
  :resolve $popServer;

#get any A records and add them directly
  :foreach aRecord in=[/ip dns cache all find where (name=$popServer && type="A")] do={
    /ip firewall address-list add list=host_azotel address=[/ip dns cache all get $aRecord data] comment=$popServer;
  }

#Check for CNAME
  :local cname;
  :local nextCname
  :set cname [/ip dns cache all find where (name=$popServer && type="CNAME")];
  :set nextCname [/ip dns cache all find where (name=[/ip dns cache all get $cname data] && type="CNAME")];

  :while ($nextCname != "") do={
        :set cname $nextCname;
        :set nextCname [/ip dns cache all find where (name=[/ip dns cache all get $cname data] && type="CNAME")];
  }
 
  :foreach aRecord in=[/ip dns cache all find where (name=[/ip dns cache all get $cname data] && type="A")] do={
    /ip firewall address-list add list=host_azotel address=[/ip dns cache all get $aRecord data] comment=$popServer;
  }
}




(3) System -> Scheduler

- Add the script to the scheduler and run it as often as required



(4) Once the script runs it will automatically create appropriate entries under Firewall -> Access List




Comments