Архив метки: Mikrotik

Securing MikroTik Router with Port Knocking

MikroTik Router usually sits between untrusted public network and trusted local network. So, it is so important to apply security in MikroTik Router otherwise MikroTik Router can be compromised by the hackers. There are various firewall techniques in MikroTik RouterOS those can be applied to secure MikroTik Router. In my previous articles, I discussed how to harden MikroTik RouterOS with restricting login services and restricting MikroTik login users. In this article I will discuss how to secure MikroTik RouterOS with Port Knowing.




Port Knocking




Port knocking is a method that enables access to the router only after receiving a sequenced connection attempts on a set of prespecified closed ports. Once the correct sequence of the connection attempts is received, the RouterOS dynamically adds the knocking host source IP to the allowed address list and the allowed host will be able to connect to MikroTik Router.




In port knocking method, all incoming requests are kept blocked and only the correct sequence maintained host is allowed to MikroTik Router. Hackers usually cannot scan the router and cannot do brute forcing. So, MikroTik Router keeps safe by implementing port knocking method.




How to Implement Port Knocking in MikroTik Router




It is so easy to implement port knocking in MikroTik RouterOS. MikroTik Firewall is enough to implement port knocking in RouterOS. Applying the following four firewall rules, a simple port knocking system can be implemented in MikroTik RouterOS. It is also possible to make more complex port knocking system although.




Rule 1: Creating First Port Knocking Firewall Rule




In the first firewall rule, we will create a firewall filter rule that will add the knocking host IP address to an address list if any host knocked on TCP port 9000. You can use any TCP or UDP port. I am using TCP port 9000 for this article configuration. The following steps will show how to create first knocking firewall rule in MikroTik RouterOS.






  • Login to MikroTik Router with Winbox using full permission user credential.
  • Go to IP > Firewall menu item. Firewall window will appear.
  • Click on Filter Rules and then click on PLUS SIGN (+). New Filter Rule window will appear.
  • Click on General tab and choose input from Chain drop down menu. Click on Protocol drop down menu and choose 6(tcp) and then put 9000 in Dst. Port input box.
  • From Action drop down menu, choose add src to address list option and put address list name (example: port:9000) in Address List input box and then put 1m duration(00:01:00) in Timeout input box. So, it will wait one minute to get second legitimate port knocking.
  • Click Apply and OK button.




Creating First Port Knocking Sequence
Creating First Port Knocking Sequence




First port knocking firewall rule has been created. We will now create second firewall rule to determine legitimate host.




Rule 2: Creating Second Port Knocking Firewall Rule




After creating first port knocking firewall rule, we will now create second port knocking rule that will add the knocking host IP address to another address list if the knocked host IP address was listed in the previous address list and the knocking port is TCP port 8000 [You can use any TCP or UDP port here]. The following steps will show how to create firewall rule to get second port knocking.




  • Click on Filter Rules tab again and then click on PLUS SIGN (+). New Filter Rule window will appear.
  • Click on General tab and choose input from Chain drop down menu. Click on Protocol drop down and choose 6(tcp) and then put 8000 in Dst. Port input box.
  • From Advanced tab, choose the previous address list (port:9000, that we created in Rule 1) from Src. Address List drop down menu.
  • From Action drop down menu, choose add src to address list option and put address list name (example: secure) in Address List input box and then put 30m duration(00:30:00) in Timeout input box. So, the host can use MikroTik RouterOS for 30 minutes.
  • Click Apply and OK button.




Creating Second Port Knocking Sequence
Creating Second Port Knocking Sequence




Second port knocking rule has also been created. Now if any host send request on TCP port 9000 and then TCP port 8000, the host IP will be added in secure address list. We will now create third firewall rule that will allow access if the host IP keeps in secure address list.




Rule 3: Allowing Host That Knocked Maintaining Correct Sequence




We will now allow that host which will follow correct port knocking sequence. From the above two rules, we can see that if any host follow correct sequence, the host will be added to secure address list. Now we will allow the host which is in secure address list. The following steps will show how to allow host which is in secure address list.




  • Click on Filter Rules tab again and then click on PLUS SING (+). New Filter Rule window will appear.
  • From General tab, chose input from Chain drop down menu.
  • From Advanced tab, choose secure from Src. Address List drop down menu.
  • From Action tab, choose accept from Action drop down menu.
  • Click Apply and OK button.






With this firewall rule, only those hosts will get access which will keep in secure address list. Now we will create another firewall rule that will block any request that will try to access in MikroTik RouterOS.




Rule 4: Creating Access Blocking Rule




We will now create the last firewall rule that will block any incoming request which is not in secure address list group. The following steps will show how to create blocking firewall rule in MikroTik RouterOS.




  • Click on Filters Rules tab and then click on PLUS SIGN (+). New Filter Rule window will appear.
  • From General tab, choose input from Chain drop down menu.
  • From Action tab, choose drop from Action drop down menu.
  • Click Apply and OK button.




So, now any incoming request will be dropped except those who are in secure address list group. Make sure the created rules are in the following order otherwise port knocking will not work.




Firewall Filter Rules for Port Knocking
Firewall Filter Rules for Port Knocking




After creating the above rule, your Winbox will be disconnected and cannot be logged in until port knocking. So, we have to now know how to do port knocking in MikroTik Router. In the following section we will learn how to do port knocking in MikroTik Router OS.




Port Knocking Methods in MikroTik RouterOS




There are a lot of methods those can be applied to do port knocking. Among these, I will mention only three simple and easy port knocking methods here.




Method 1: Port Knocking from Browser




Web Browser is the basic and easiest port knocking client. Just open your favorite web browser and type Router IP address and Port combination [http://ip_address:port_number] in the URL bar. Your browser will do port knocking and you will be able to do logged in MikroTik Router. Make sure you have followed the correct port sequence. For example, according to our above configuration, first type https://ip_address:9000 and hit enter key and then type http://ip_address:8000 within one minute and then hit enter key. After successful port knocking, dynamic address list will be created like the following image.




Dynamic address list created by port knocking
Dynamic address list created by port knocking




Method 2: Port Knocking from Winbox




Winbox can also be used to do port knocking. Open winbox and type ip_address:port_number combination in Connect To input box and then click Connect button. Winbox will do port knocking and you will be able to connect MikroTik Router. Make sure you are following the correct port sequence.




Port Knocking from Winbox
Port Knocking from Winbox




Method 3: Port Knocking with Windows Port Knocking Application




Greg Sowell provides a windows based port knock application which is amazing. Download [http://gregsowell.com/?download=5695] port knock application from their website and unzip it. If it asks to provide password, put portknock. Run the application and provide IP address and port sequence and then hit Knock button. It will do port knocking and you will be able to login to MikroTik Router.




Windows Based Port Knocking Application
Windows Based Port Knocking Application




How to secure MikroTik Router with Port Knocking has been discussed in this article. I hope, you will now be able to implement port knocking in MikroTik Router. However, if you face any confusion to implement port knocking, feel free to discuss in comment or contact me from Contact page. I will try my best to stay with you.



2021-03-21T23:29:19
MikroTik Router Tutorials & Guides

Маркировка роутеров Mikrotik

У каждого роутера или свича фирмы Mikrotik есть коммерческое название и маркировка аппаратной платформы (Product code). Например маршрутизатор «hEX» имеет Product code — RB750Gr3. В этой статье разберем что означает каждая буква в маркировке Product code.





Читать далее…

Использование префикса /31 или маски 255.255.255.254 для соединения точка-точка

В связи с постоянно растущим давлением по сохранению пространства IP-адресов на Интернет, могут быть внедрены в практику для повышения эффективности нумерации. Смысл заключается в сокращении вдвое использование адресного диапазона, назначаемого для соединений точка-точка.

В большинстве кейсов пронумерованные подсети Интернета не используют больше, чем 30-битную маску подсетей (/30). Для которой требуется четыре адреса на стык – два адреса хоста, один адрес сети и один широковещательный. Это плохо для соединений точка-точка, поскольку имеют только два полезных адреса из четырех.

Но что мешает нам использовать префикс /31? Давайте попробуем в этом разобраться.

Рассмотрим использование префикса /30 и /31:

172.16.0.1/30



Адрес: 172.16.0.1

Bitmask: 30

Netmask: 255.255.255.252

Network: 172.16.0.0

Broadcast: 172.16.0.3

Hostmin: 172.16.0.1

Hostmax: 172.16.0.2

/30 Маска разрешает использовать 4 адреса. Первый будет адресом сети, последний бродкастом, оставшихся два полезные, используются для соединения.

172.16.0.1/31



Адрес: 172.16.0.1

Bitmask: 31

Netmask: 255.255.255.254

Network: 172.16.0.0

Broadcast: 172.16.0.1

Hostmin: 172.16.0.0

Hostmax: 172.16.0.1

/31 Маска разрешает использовать 2 адреса. Первый будет адресом сети, последний бродкастовым, ну а для соединения узлов используем все те же адреса.

Ограничения при использовании префикса /31:

1. Перестают работать протоколы использующие L3 brodcast.

На самом деле на текущий момент протоколов использующих в своей работе L3 brodcast практически не осталось. Основные актуальные на сегодняшний день протоколы такие как OSPF, IS-IS, EIGRP, BGP используют в работе multicast или unicast адреса.

Вообще это ограничение можно даже записать в плюс, потому что повышается устойчивость к DoS атакам основанных на рассылке бродкаст трафика.

2. Не все устройства поддерживают префиксы /31

На Juniper и Cisco вы можете смело использовать маску /31, хотя cisco при этом выдает предупреждение (% Warning: use /31 mask on non point-to-point interface cautiously).

А вот ZyXEL уже не дает выбрать маску /31.

Mikrotik официально так же не поддерживает /31, но на практике иногда получается использовать /31 с некоторыми ухищрениями.

В итоге накладываются дополнительные ограничения на эксплуатацию сети, использования оборудования разных производителей и даже на использование оборудования одного вендора но с разными версиями прошивок.

Если вас не пугают приведенные ограничения то смело экономьте адреса используя префикс /30

Использование префикса /31 детально описано в RFC 3021 Using 31-Bit Prefixes on IPv4 Point-to-Point Links.



2021-03-12T11:34:24
other

MikroTik – Firewall защита доступа

К каким результатам мы пришли:

У нас встает вопрос безопасности нашей локальной сети, ведь китайские боты не спят и постоянно сканируют доступное сетевое пространство на наличие дыр и уязвимостей.
Имея статический IP мы подвержены риску быть взломанными. Т.к. наш статический IP доступен в интернете, он может подвергаться различного рода «атакам из вне».

Поэтому нам нужно сделать так, чтобы только мы могли подключаться к нашим роутерам и другим сервисам в локальной сети. Читать

MikroTik RouterOS – Списки интерфейсов “Interface List”

Данная статья будет небольшой и она будет посвящена Спискам интерфейсов в MikroTik RouterOS. В ней я постараюсь рассказать, что такое “Списки интерфейсов” и для чего они нужны.

Все действия производились на прошивке 6.42.9 (Long-Term)
Описание на MikroTik WIki: Manual:Interface/List [ENG]

Сами списки интерфейсов в RouterOS V6 (на 10.10.2018) присутствуют довольно давно, тогда они еще были очень простыми. Читать

Балансировка двух WAN на Mikrotik используя PCC

Начальные условия




  • 2 канала WAN от разных провайдеров, с разными скоростями
  • Провайдер1 WAN1 (192.168.1.1) — 10 Мбит
  • Провайдер2 WAN2 (192.168.2.1) — 20 Мбит




Необходимо реализовать




  • Основной канал WAN2 и он должен использоваться интенсивнее (2/3 всего объема трафика)
  • Балансировку нагрузки между каналами
  • Роутер должен отвечать на запросы (пришедшие с любого провайдера) именно с того интерфейса, откуда пришел запрос




/ip address
add address=192.168.0.1/24 network=192.168.0.0 broadcast=192.168.0.255 interface=Local
add address=192.168.1.2/24 network=192.168.1.0 broadcast=192.168.1.255 interface=WAN1
add address=192.168.2.2/24 network=192.168.2.0 broadcast=192.168.2.255 interface=WAN2
 
/ip firewall mangle
add chain=input in-interface=WAN1 action=mark-connection new-connection-mark=WAN1_conn
add chain=input in-interface=WAN2 action=mark-connection new-connection-mark=WAN2_conn
 
add chain=output connection-mark=WAN1_conn action=mark-routing new-routing-mark=to_WAN1
add chain=output connection-mark=WAN2_conn action=mark-routing new-routing-mark=to_WAN2
 
add chain=prerouting dst-address=192.168.1.0/24 action=accept in-interface=Local
add chain=prerouting dst-address=192.168.2.0/24 action=accept in-interface=Local
 
add chain=prerouting dst-address-type=!local in-interface=Local per-connection-classifier=both-addresses-and-ports:2/0 action=mark-connection new-connection-mark=WAN1_conn passthrough=yes
add chain=prerouting dst-address-type=!local in-interface=Local per-connection-classifier=both-addresses-and-ports:2/1 action=mark-connection new-connection-mark=WAN2_conn passthrough=yes
 
add chain=prerouting connection-mark=WAN1_conn in-interface=Local action=mark-routing new-routing-mark=to_WAN1
add chain=prerouting connection-mark=WAN2_conn in-interface=Local action=mark-routing new-routing-mark=to_WAN2
 
/ip route
add dst-address=0.0.0.0/0 gateway=192.168.1.1 routing-mark=to_WAN1 check-gateway=ping
add dst-address=0.0.0.0/0 gateway=192.168.2.1 routing-mark=to_WAN2 check-gateway=ping
 
add dst-address=0.0.0.0/0 gateway=192.168.1.1 distance=1 check-gateway=ping
add dst-address=0.0.0.0/0 gateway=192.168.2.1 distance=2 check-gateway=ping
 
/ip firewall nat
add chain=srcnat out-interface=WAN1 action=masquerade
add chain=srcnat out-interface=WAN2 action=masquerade




Если каналы неравны (как у меня), то нужно изменить




add chain=prerouting dst-address-type=!local in-interface=Local per-connection-classifier=both-addresses-and-ports:2/0 action=mark-connection new-connection-mark=WAN1_conn passthrough=yes

add chain=prerouting dst-address-type=!local in-interface=Local per-connection-classifier=both-addresses-and-ports:2/1 action=mark-connection new-connection-mark=WAN2_conn passthrough=yes




на




add chain=prerouting dst-address-type=!local in-interface=Local per-connection-classifier=both-addresses-and-ports:3/0 action=mark-connection new-connection-mark=WAN1_conn passthrough=yes

add chain=prerouting dst-address-type=!local in-interface=Local per-connection-classifier=both-addresses-and-ports:3/1 action=mark-connection new-connection-mark=WAN2_conn passthrough=yes

add chain=prerouting dst-address-type=!local in-interface=Local per-connection-classifier=both-addresses-and-ports:3/2 action=mark-connection new-connection-mark=WAN2_conn passthrough=yes




Определенный порт через определенного провайдера




Спасибо за подсказку maxim.naidenov:




;;; Winbox
chain=prerouting action=mark-routing new-routing-mark=to_WAN1 passthrough=no protocol=tcp dst-address-type=!local in-interface=bridge-local dst-port=8291 connection-mark=no-mark

;;; Wargaming, RU9
chain=prerouting action=mark-routing new-routing-mark=to_WAN2 passthrough=no dst-address=xxx.xxx.xxx.0/24 dst-address-type=!local in-interface=bridge-local connection-mark=no-mark




Балансировка каналов и IPSEC




При эксплуатации IPSEC и балансировке каналов выяснился интересный факт: при установке IPSEC не получается обменяться всеми ключами. IPSEC вроде бы как и поднимается, но работать не работает. Если посмотреть IP → IPsec → Installed SAs — можно увидеть что счетчик «Current Bytes» для одного из ключей равен 0, т.е. обмен ключами все-таки не прошел. Для правильной работы необходимо добавить еще два правила:




> /ip firewall mangle

> add chain=output action=mark-routing new-routing-mark=ISP1_conn passthrough=no connection-mark=ISP1_conn

> add chain=output action=mark-routing new-routing-mark=ISP2_conn passthrough=no connection-mark=ISP2_conn




При этом в таблице маршрутизации должны быть маршруты с соответствующими Routing Mark




Было (неверно):




> add chain=output action=mark-connection new-connection-mark=ISP1_conn passthrough=no out-interface=WAN1

> add chain=output action=mark-connection new-connection-mark=ISP2_conn passthrough=no out-interface=WAN2




Еще полезная статейка: https://habr.com/post/313342/




Взято отсюда: https://wiki.rtzra.ru/software/mikrotik/mikrotik-dual-wan-pcc



2021-03-07T18:12:26
Network