Mikrotik отключить dynamic dns

Обновлено: 06.07.2024

DNS cache is used to minimize DNS requests to an external DNS server as well as to minimize DNS resolution time. This is a simple DNS cache with local items.

Contents

Specifications

  • Packages required: system
  • License required: Level1
  • Submenu level: /ip dns
  • Standards and Technologies: DNS
  • Hardware usage: Not significant

Description

A MikroTik router with DNS feature enabled can be set as a DNS server for any DNS-compliant client. Moreover, MikroTik router can be specified as a primary DNS server under its dhcp-server settings. When the remote requests are enabled, the MikroTik router responds to TCP and UDP DNS requests on port 53.

DNS Cache Setup

Sub-menu: /ip dns

DNS facility is used to provide domain name resolution for router itself as well as for the clients connected to it.

Properties

Property Description
allow-remote-requests (yes | no; Default: no) Specifies whether to allow network requests
cache-max-ttl (time; Default: 1w) Maximum time-to-live for cache records. In other words, cache records will expire unconditionally after cache-max-ttl time. Shorter TTL received from DNS servers are respected.
cache-size (integer[64..4294967295]; Default: 2048) Specifies the size of DNS cache in KiB
max-concurrent-queries (integer; Default: 100) Specifies how much concurrent queries are allowed
max-concurrent-tcp-sessions (integer; Default: 20) Specifies how much concurrent TCP sessions are allowed
max-udp-packet-size (integer [50..65507]; Default: 4096) Maximum size of allowed UDP packet.
query-server-timeout (time; Default: 2s) Specifies how long to wait for query response from one server
query-total-timeout (time; Default: 10s) Specifies how long to wait for query response in total. Note that this setting must be configured taking into account query-server-timeout and number of used DNS server.
servers (list of IPv4/IPv6 addresses; Default: ) List of DNS server IPv4/IPv6 addresses

Property Description
cache-used (integer) Shows the currently used cache size in KiB
dynamic-server (IPv4/IPv6 list) List of dynamically added DNS server from different services, for example, DHCP.

When both static and dynamic servers are set, static server entries are more preferred, however it does not indicate that static server will always be used (for example, previously query was received from dynamic server, but static was added later, then dynamic entry will be preferred).

Note: If allow-remote-requests is used make sure that you limit access to your server over TCP and UDP protocol.

Example

To set 159.148.60.2 as the primary DNS server and allow the router to be used as a DNS server, do the following:

Cache Monitoring

Description

This menu provides a list with all address (DNS type "A") records stored on the server

Property Description

All DNS Entries

Description

This menu provides a complete list with all DNS records stored on the server

Property Description

Static DNS Entries

Description

The MikroTik RouterOS has an embedded DNS server feature in DNS cache. It allows you to link the particular domain names with the respective IP addresses and advertize these links to the DNS clients using the router as their DNS server. This feature can also be used to provide fake DNS information to your network clients. For example, resolving any DNS request for a certain set of domains (or for the whole Internet) to your own page.

The server is capable of resolving DNS requests based on POSIX basic regular expressions, so that multiple requets can be matched with the same entry. In case an entry does not conform with DNS naming standards, it is considered a regular expression and marked with ‘R’ flag. The list is ordered and is checked from top to bottom. Regular expressions are checked first, then the plain records.

Property Description

Notes

Reverse DNS lookup (Address to Name) of the regular expression entries is not possible. You can, however, add an additional plain record with the same IP address and specify some name for it.

Remember that the meaning of a dot (.) in regular expressions is any character, so the expression should be escaped properly. For example, if you need to match anything within example.com domain but not all the domains that just end with example.com, like www.another-example.com, use regexp=".*\\.example\\.com\$"

Regular expression matching is significantly slower than of the plain entries, so it is advised to minimize the number of regular expression rules and optimize the expressions themselves. Example

It is also possible to forward specific DNS requests to a different server using FWD type. This will fordward all subdomains of "example.com" to server 10.0.0.1:

Note: regexp entries are case sensitive, but since DNS requests are not case sensitive, RouterOS converts DNS names to lowercase, you should write regex only with lowercase letters.

Flushing DNS cache

Command Description

Example

Example

It is advised to import the root CA certificate of the DoH server you have chosen to use for increased security.

Warning: We strongly suggest not use third-party download links for certificate fetching. Use the Certificate Authority's own website.

There are various ways to find out what root CA certificate is necessary. The easiest way is by using your WEB browser, navigating to the DoH site and checking the websites security. Using Firefox we can see that DigiCert Global Root CA is used by CloudFlare DoH server. You can download the certificate straight from the browser or navigate to DigiCert website and fetch the certificate from a trusted source.

Rootca.PNG

Download the certificate and import it:

Configure the DoH server:

Note that you need at least one regular DNS server configured for the router to resolve the DoH hostname itself. If you do not have any dynamical or static DNS server configured, you can configure a static DNS entry like this:

Note: RouterOS prioritize DoH over DNS server if both are configured on the device.



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

Модернизируя сетевую инфраструктуру одного из заказчиков, мы столкнулись с настоящим телеком динозавром из семейства «for home use only». На границе периметра был засунут старенький роутер Asus, основное назначение которого было выполнение роли DDNS клиента. Так получилось, что в компании давно были настроены внутренние сетевые ресурсы и с интернет провайдером заключен договор о лизинге белого динамического IP. Со временем в инфраструктуре многое поменялось, но из-за твердого не желания заказчика вмешиваться в существующие, налаженные годами процессы, настройки клиентской стороны не менялись, и Asus работал себе и работал, сообщая внешнему DDNS сервису свой текущий адрес. В этом месте вспоминается разговор у костра с одним коллегой, который поведал мне о увиденном им лично коммутаторе Cisco с uptime в целых 11 лет, хотите верьте, хотите нет. Настал черед выйти Asus-у на пенсию и уступить место оборудованию от MikroTik. В этом месте мы столкнулись с инженерной задачей, готового решения которого в интернете найдено не было. В связи с чем, было проведено небольшое исследование, которое может кому-то поможет сэкономить время.

▍Техническая часть

Протокол DDNS отвечает за автоматизированное преобразование доменного имени в динамические IP адреса. Прошивки роутеров Asus имеют функционал по настройке DDNS клиента, в котором зашиты определенные сервисы.


Настройка DDNS клиента


Отключение брандмауэра для WAN порта


Настройка DHCP клиента для WAN порта

Если все сделано верно, тогда в лизинге увидим нужный нам IP.


Настраивая на MikroTik снифер, мы выбрали наиболее простой вариант /tool sniffer с сохранением дампа в память роутера:


Активируем DDNS клиент на Asus и смотрим трафик, а там все как на ладони.



Работа DDNS клиента


Все данные у нас есть, верстаем скрипт на RouterOS, заголовки Authorization и User-Agent пропускаем для простоты:


Сервер нам выдает ошибку 401 Unauthorized, все понятно, добавляем в скрипт данные для аутентификации, как есть, в сыром виде. И DDNS сервис от Asus заработал, но уже на оборудовании MikroTik:


Не забываем скрипт засунуть в планировщик заданий:



Декодированный заголовок Authorization



MAC адрес WAN порта

А вот откуда берется пароль, нам выяснить не удалось. В системных логах загрузки роутера ничего подобного не упоминалось. Даже не поленились посмотреть под корпусом, ничего похоже и там не нашли. После обновления версии операционной системы он не изменился, поэтому будем считать, что она берет эту информацию откуда-то изнутри железа. Что интересно, сервер DDNS проверяет на валидность только первые 6 знаков (для шестнадцатеричного представления, разумеется) и наличие ":" после 12 знака, остальное можно опустить или изменить, но аутентификацию так не пройти.

▍Заключение

В работе технических специалистов постоянно возникают различного рода нестыковки, иногда в самых неожиданных местах. Тогда в дело вступает светлая голова, ровные руки, везение и качественное оборудование, на котором приятно работать. Немного добавим про безопасность такой вот реализации DDNS клиента. На наш взгляд, все хорошо. Чтобы злоумышленнику попытаться стравить IP адрес, ему придется ввести данные для аутентификации. Если с MAC адресом вроде как все это проще, то пароль точно не подобрать. Да и вообще на дворе 2021 год и пора давно бы отказаться от DDNS, в корпоративной среде уж точно, как-то не серьезно.

Если в магазине вас угораздило купить роутер MikroTik себе домой и вы не знаете зачем он вам, а отравление DNS кэша вашим провайдером не дает вам спать по ночам, то этот пост для вас.

Можно не мучаться и поставить DNS от Yandex, Google, Adquard и прочее, а можно пойти более сложным путем:


Если их несколько, выбираем какой больше нравится вам :)

1. Первым делом удаляем автополучение DNS провайдера:


открываем настройки интерфейса и убираем галочку "use peer dns"

2. В настройке DNS (IP -> DNS), вводим IP DNS сервера (начиная с сервера который у вас в городе). Размер кэша укажите сколько не жалко (учитывайте свободное место).


На этом можно было бы закончить, но мы пойдем далее.


Далее открываем терминал и добавляем статические маршруты

/ip dns static add comment="OpenNIC" forward-to=185.121.177.177,169.239.202.202,2a05:dfc7:5::53::1,2a05:dfc7:5::5353::1 regexp=".*(\\.bbs|\\.chan|\\.cyb|\\.dyn|\\.geek|\\.gopher|\\.indy|\\.libre|\\.neo|\\.null|\\.o)\$" type=FWD

/ip dns static add comment="OpenNIC" forward-to=185.121.177.177,169.239.202.202,2a05:dfc7:5::53::1,2a05:dfc7:5::5353::1 regexp=".*(\\.oss|\\.oz|\\.parody|\\.pirate|\\.opennic.glue|\\.dns\\.opennic\\.glue)\$" type=FWD


В настройках DNS делаем очистку кэша.


Если пользуетесь Microsoft Edge, отключаем "улучшайзеры", в других браузерах аналогично.


Ребутим все что можно отребутить :)


Что мне это дало? Нормально заработали уведомления от mihome, перестали "тупить" китайские лампочки. Ну и немного ощущаешь себя кулхацкером чуть более независимым от своего провайдера.

upd: корневой сервер DNS (в городе) не является публичным резолвером и не отвечает на запросы, нужно вводить ip публичного резолвера данного корневого сервера DNS.

Wed Jul 31, 2019 11:38 am

Hi Friends,
I'm using a Mikrotik SXT LTE kit (product code RBSXTR&R11e-LTE).
I've added DNS primary and secondary both by OpenDns, now I would like to remove the provider Dynamic Server.
Could you suggest the right way?
I've search on the documentation with no luck

cosmogoniA
n o p r o v a r e n o f a r e o n o n f a r e n o n c e p r o v a r e Posts: 891 Joined: Wed Jun 12, 2013 1:59 pm

Wed Jul 31, 2019 11:43 am

/ip dhcp-client set use-peer-dns=no

Posts: 25 Joined: Thu Jun 06, 2019 10:36 am Location: Italy Contact:

Wed Jul 31, 2019 12:00 pm

Hi erlinden and thanks for your reply!
I've try:

1) /ip dhcp-client set use-peer-dns=no
2) numbers: 0

Script Error: action cancelled

"0" to the question "numbers" was that what you wanted to say?

cosmogoniA
n o p r o v a r e n o f a r e o n o n f a r e n o n c e p r o v a r e Posts: 1802 Joined: Tue Oct 12, 2010 3:23 am Location: Antwerp, BE

Wed Jul 31, 2019 12:04 pm

Posts: 25 Joined: Thu Jun 06, 2019 10:36 am Location: Italy Contact:

Wed Jul 31, 2019 12:31 pm

Well, this second command did not give me errors, but how can I check if Dynamic Server has been removed?
Looking into webfig -> IP -> DNS It is still present:

Dynamic Servers 83.158.240.241

cosmogoniA
n o p r o v a r e n o f a r e o n o n f a r e n o n c e p r o v a r e Posts: 891 Joined: Wed Jun 12, 2013 1:59 pm

Wed Jul 31, 2019 1:28 pm

Can you show /ip dns print?

WebFig might have an caching thingie.

Posts: 25 Joined: Thu Jun 06, 2019 10:36 am Location: Italy Contact:

Wed Jul 31, 2019 1:32 pm

cosmogoniA
n o p r o v a r e n o f a r e o n o n f a r e n o n c e p r o v a r e Posts: 2353 Joined: Tue Feb 18, 2014 12:56 am Location: Netherlands / Nīderlande

Wed Jul 31, 2019 1:48 pm

I can't also not shed those and made a feature request for that.

Loving my freedom and so, no Twitter, no Meta/Facebook/Instagram/WhatsApp, no Apple and no Alphabet/Google, no Amazon/Cloudfront/AWS. However, 'happy' with giving money to Italy.

Running: RouterOS 7.1rc5 and 6.49RC / Winbox 3.31 64bits

Posts: 891 Joined: Wed Jun 12, 2013 1:59 pm

Wed Jul 31, 2019 1:58 pm

Can you post a /export hide-sensitive please?
What version are you running?

Читайте также: