Mikrotik dns allow remote requests что это
Thu Dec 25, 2014 10:07 pm
merry xmas everyone
i m trying to make a tutorial about mikrotik and i would like to know what does Allow Remote Requests mean?
i know i need it check up to have internet. Please can you answer with one or two examples of how it work.
thank you
Thu Dec 25, 2014 10:42 pm
You mean the one in the "/ip dns" menu?
This is whether to let other devices use RouterOS as a DNS server. If this option is not checked, client devices must use another device set as their DNS server. Regardless of this option, requests originating from RouterOS itself (e.g. from a script via the ":resolve" command) will check up the DNS entries defined there, and use the defined servers if the router doesn't know the answer.
You don't need to have this option enabled to have internet. If you disable it, you can give your client devices a different DNS, such as Google's 8.8.8.8 for example. That's what the DNS setting in "/ip dhcp-server network" is for. Or if you don't use DHCP, you can instruct clients to enter that other IP in their network settings.
A DNS server in general is not required to be in the same subnet. Only the default gateway must be.
Fri Dec 26, 2014 2:15 am
thank you very much for the answer.
here it is picture i upload.
so in few words it means that option let the router solve dns?
what is the remote requests? does it mean it permit or allow requests from outside of the LAN network to the server or internet?
or when i got a host in my network requesting a data outside of my lan to internet ,mikrotik will let that data get into my network.
let's say i do ping to yahoo, from my pc, then the data goes outside to yahoo server and when it want to come back, if that option is not set they packet wont be able to return if that option is not check.
Fri Dec 26, 2014 6:06 am
These settings apply only when clients use router's own address as DNS resolver.
If your clients use some external resolver, these settings will not influence them in any way.
If you do not check Allow Remote Requests, router will resolve names only for itself (e.g. when you have hostname in its VPN client, etc..). If you do check it, router will act as resolver for *any* other machine that asks for it.
Unfortunately there's no option to allow just LAN clients (there's a feature request, but who knows if it ever gets implemented). So when you enable Allow Remote Requests, you have to make sure that you allow incoming port 53 only for your clients and block the rest of the world using firewall. Otherwise you'll create open resolver and it's a bad thing.
Fri Dec 26, 2014 2:08 pm
When you ping yahoo.com from a client device, the client device first makes a connection to the DNS server defined in its own settings, asking it for the IP that "yahoo.com" corresponds to.
If your client device (e.g. 192.168.88.254) has 8.8.8.8 defined as their DNS server, it will contact the default gateway (e.g. 192.168.88.1), and ask it to forward a packet to 8.8.8.8, and send back the reply. The gateway connects to 8.8.8.8 via the internet, and eventually gives the client back the reply. The client only then asks the default gateway to make a connection to the IP that it just received via DNS.
That same procedure happens if the client device's DNS server is set to 192.168.88.1, but if the "Allow remote requests" option is not checked, the DNS exchange with 192.168.88.1 will fail, and thus you wouldn't be able to ping "yahoo.com". If you already knew the IP that "yahoo.com" is on, you can still ping to that IP, since it doesn't require a DNS lookup.
Wed Jul 11, 2018 10:44 am
Ok sorry for bumping but basically i check "allow remote requests" and added public IP address of that mikrotik router as dns server for "outside" computer and he cant resolve the DNS. im using RouterOS v6.40.8 . I even made a firewall rule, chain - dstnat, protocol - udp, dst.port - 53, action - redirect, to ports - 53
. what im missing ? why i cant use my router as an extrenal dns and use static routes in it ?
Wed Jul 11, 2018 10:53 am
Ok sorry for bumping but basically i check "allow remote requests" and added public IP address of that mikrotik router as dns server for "outside" computer and he cant resolve the DNS. im using RouterOS v6.40.8 . I even made a firewall rule, chain - dstnat, protocol - udp, dst.port - 53, action - redirect, to ports - 53
You don't do dstnat for connections to the router itself. Rather you add FW rule to chain=input allowing particular connection. Something like
perhaps adding src-address=xx.yy.ww.zz to allow connections only from select remote hosts (don't forget to allow LAN hosts!).
Wed Jul 11, 2018 11:35 am
Ok sorry for bumping but basically i check "allow remote requests" and added public IP address of that mikrotik router as dns server for "outside" computer and he cant resolve the DNS. im using RouterOS v6.40.8 . I even made a firewall rule, chain - dstnat, protocol - udp, dst.port - 53, action - redirect, to ports - 53
You don't do dstnat for connections to the router itself. Rather you add FW rule to chain=input allowing particular connection. Something like
perhaps adding src-address=xx.yy.ww.zz to allow connections only from select remote hosts (don't forget to allow LAN hosts!).
Tried with those firewall rules (i tought if u dont set that rule it will accept automaticly !?).
The thing is that i put public IP directly into DNS TCP/IP configuration of external computer of my router and it still doesnt resolve anything. even tho i can see some 285 UDP accepted packets with ur first firewall rule.
Dont know what im doing wrong. i thought i only need to check that "Allow Remote Requests" and its done (ofc with public IP on WAN interface)
Wed Jul 11, 2018 1:17 pm
I'm reading some topics here and someone said that router should not be in DNS "client" mode but in DNS Server mode. how can i check that, when is he operating as a client and when as a server ?
Wed Jul 11, 2018 3:03 pm
allow-remote-requests=yes solely permits the DNS process to listen for incoming requests at UDP port 53 and process these requests. The DNS process itself doesn't care about the source address of those requests. So whether a particular client will be served or not depends on firewall settings. A typical firewall ignores any packets coming from WAN side, except those it knows (thanks to connection-tracking) to be responses for packets previously sent out via the WAN interface. Order of rules in the firewall matters, so the rule action=accept chain=input protocol=udp dst-port=53 must be at the right place in the list to do what you expect it to do.
But opening a local DNS service for requests coming from anywhere in the internet is not a good idea as DNS is a UDP service so it is easy to make your device participate in a DDoS attack if it is configured to send a packet back to the source address of an incoming packet. So if I want to attack UDP port X on address x.x.x.x, it is enough to send to your UDP port 53 a DNS query packet with source address x.x.x.x and source port X; your device will send the DNS response to that address and port and my own address remains invisible to the target - from the target's perspective, it is you who attacks him.
Don't write novels, post /export hide-sensitive file=x. Use find&replace in your favourite text editor to systematically replace all occurrences of each public IP address potentially identifying you by a distinctive pattern such as my.public.ip.1.
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
Description
This menu provides a complete list with all DNS records stored on the server
Cache Monitoring
Description
This menu provides a list with all address (DNS type "A") records stored on the server
Property Description
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.
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.
For every complex problem, there is a solution that is simple, neat, and wrong.
5. Оригиналы источников информации.
-
«Защита Mikrotik от взлома». «Закрываем 53й порт DNS на роутере Mikrotik от внешних запросов».
Хочешь уметь больше? Научиться тонкостям настройки MikroTik можно из русскоязычного онлайн-курса по MikroTik от автора курсов Дмитрия Скромнова. Здесь можно изучить MikroTik и RouterOS самостоятельно по курсу «Настройка оборудования MikroTik». Курс основан на официальной программе MTCNA, но содержит больше информации. Это 162 видеоурока и большая практическая задача, разбитая на 45 лабораторных работ. Время на изучение неограниченно – все материалы передаются бессрочно и их можно пересматривать сколько нужно. Первые 25 уроков можно посмотреть бесплатно, оставив заявку на странице курса.
Кэширующий DNS в микротике это хорошо и просто. Настраивается быстро, используется легко и непринужденно. Опишу на примере и чуток поделюсь опытом.
Итак, начнем. Если вы используете winbox, то первый этап выполняется в несколько кликов: IP->DNS. В появившемся окне указываете серверы пересылки, не забыв при этом поставить галку «Allow remote requests».
…или в терминале выполнить
Этого достаточно, чтобы Mikrotik стал принимать DNS-запросы из локальной сети, пересылать их на указанные серверы и возвращать IP-адреса любимых сайтов конечным пользователям в вашей локалке. Т.е. с этого момента вы можете указывать ваш роутер не только шлюзом но и сервером DNS в настройке соединения.
Конечно, не все запросы будут пересылаться, для этого есть кэш. Он же cache. О проблеме с кэшем (мелочь, а неприятно), с которой я столкнулся, напишу ниже.
Все работает, но… Есть моменты, на которых я хотел бы заострить внимание.
Давайте не будем использовать только дефолт. Обезопасим себя и роутер от лишнего и абсолютно ненужного траффика.
При такой дефолтной настройке mikrotik будет отвечать на DNS запросы по всем интерфейсам. (Конечно же в том случае, если вы еще не настроили firewall) Нужны ли такие «левые» запросы? Конечно нет.
Поэтому в настройке firewall до «всеобщего DROP» в цепочке INPUT надо либо явно указать интерфейсы, с которых принимать DNS запросы (по одному правилу на интерфейс), либо указать диапазон IP, с которого принимать эти запросы):
add chain = input comment = "Allow DNS from ether2" dst - port = 53 in - interface = ether2 protocol = udp
Либо разрешить DNS на всех интерфейсах, кроме «внешнего». Вот так, например:
add chain = input comment = "Allow DNS from ether2" dst - port = 53 in - interface = ! myISP protocol = udp
Либо… Либо… Способов много, firewall заслуживает отдельной большой темы даже для базовой настройки. Поэтому углубляться я тут не буду. Просто изложу принципы.
Допустим, мы написали нужные правила, определили откуда можно присылать DNS-запросы, все остальное отсекли. И тут DNS перестал работать. Все верно, т.к. мы забыли очень важную вещь: мы забыли разрешить серверам пересылки отвечать нашему роутеру. Т.е. mikrotik получает запрос из локалки, пересылает запрос, например, гуглу (8.8.8.8), гугл пытается ответить нашему роутеру и этот ответ отсекается последним правилом
Нехорошо. Надо разрешить. Добавляем еще правило перед последним. Здесь я разрешу только серверу 8.8.8.8 ответить на запрос нашего роутера. Это для примера. Можно не указывать src-address, если вы не хотите писать отдельное правило для каждого сервера.
add chain = input comment = "Allow DNS request" in - interface = myISP protocol = udp src - address = 8.8.8.8 src - port = 53
Обратите внимание, что надо указывать src-port=53 а не dst-port=53. Наш роутер обратится к 8.8.8.8 с произвольного порта, а вот гугл будет отвечать именно с 53-го.
В конечном виде правила будут выглядеть следующим образом.
add action = drop chain = input comment = "Drop DNS from !ether2" dst - port = 53 in - interface = ! ether2 protocol = udp
add chain = input comment = "Allow DNS request" in - interface = myISP protocol = udp src - port = 53
Кто-то пытливый обратил внимание, что в примерах отсутствуют action=accept. Accept используется по-умолчанию. Поэтому, когда мы хотим что-то разрешить, явно указывать «разрешаю» не обязательно.
Если у вас в локалке есть какие-то ресурсы, которым вы хотите присвоить имя, то вы можете добавить запись IP->DNS->Static. Когда это нужно? Да повсеместно. Например, у вас в сети есть файловый сервер или другой внутренний-ресурс, который постоянно мигрирует по разным IP-адресам и вам лень каждый раз перенастраивать подключение у каждого клиента.
Нажимаете «Static» и устанавливаете взаимосвязь между IP и именем хоста. Чтобы не листать наверх, вот вам еще раз рисунок из начала страницы:
Увидите следующее окно и, нажимая «+», добавляйте свои записи. Вот, собственно:
Или через терминал:
Гораздо легче будет потом жить. Ваши пользователи будут обращаться к file-serv-1.lcl, а вы втихую менять его IP на микротике в случае переезда сервера.
Есть еще кнопка Cache, нажав которую, вы увидите, что в данный момент закешировал mikrotik и сможете этот кеш очистить, нажав в открывшемся окне Flush cache.
С настройкой вкратце все. Теперь мелкая неприятность, с которой я как-то столкнулся. Кроется она во взаимодействии кэша DNS микротика и статических записей. Не знаю, на каких версиях это еще проявляется, я словил на CCR1036-8G-2S+ RouterOS v6.15. Может, я вообще единственный, кто это наблюдал. Но, тем не менее, поделюсь. Вдруг кому поможет.
Если сменился IP хоста и вам надо отредактировать статическую запись, то лучше удалить старую и создать новую. Если просто отредактировать существующую, то в кэше могут остаться старые записи и ни кнопка Flush cache не поможет, ни /ip dns cache flush через терминал.
Глюк проявляется не систематически, но как-то раз заставил меня изрядно напрячь мозг, прежде чем я понял, в чем дело. Проверяйте кэш после редактирования статических записей. Если видите старое в дополнение к новому, то надо заново создать старую запись и удалить ее. Тогда она также удалится и из кэша.
MikroTik. Смена MAC адреса. Как сменить mac-адрес интерфейса MikroTik? Вопрос совсем для новичков. Но раз вы сюда попали, то материал для вас и вы найдете здесь ответ на свой воп.
Проброс портов в MikroTik Нередко у нас возникает необходимость дать доступ снаружи к компьютерам, которые находятся за NAT-ом в нашей локальной сети. Будь то веб-сервер или пе.
Mikrotik safe mode Скорее всего, ответ на ваш вопрос такой: mikrotik в режиме safe mode откатывается обратно где-то через 9 минут по тайм-ауту TCP. Если я не угадал сход.
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:
Example
Command Description
3. Отключаем стандартные порты.
Обычные пользователи не обращают на них внимания, но я рекомендую всем либо выключить к ним доступ, либо настроить правила фильтрации. Самое простое, как закрыть порты:
Заходим IP —> Services и видим список портов.
Я всегда закрываю все, кроме Winbox потому что мне нет в них необходимости. Можно просто выключить, а можно изменить номер порта на тот, который вам нравится, но стоит быть внимательными, не советую менять порты 443, 80. Это служебные порты и их изменение может привести к потере доступа в Интернет.
У меня выглядит вот так:
Советую и вам так сделать. Это означает что к роутеру можно присоединиться только через винбокс и только из внутренней сети (вместо 192.168.10.0 — должна стоять ваша сеть).
Еще у MikroTik по-умолчанию включен вот такой пункт IP -> DNS:
Allow Remote Requests заставляет слушать DNS-сервис на всех портах маршрутизатора. Таким образом при включении сервиса мы становились отличным хостом для атаки ботами и прочей нечистью из Интернетов.
А так как у меня была статика IP последние 2 месяца, то я был вообще идеальным DNS… к слову на работе все галки были сняты сразу, так как на тот момент я про нее уже знал.
После снятия галочки, картина такая:
Иногда снятие галочки Allow Remote Requests приводит к некоторым «нерабочим» сайтам по интернету, так как мы выдаём собственный DNS в локальную сеть.
Allow Remote Requests можно поставить если Вы хотите чтоб микротик выступал в роли кэширующего DNS, но в этом случае необходимо запретить обработку запросов DNS поступающих на порты которые смотрят в сеть провайдера и разрешить обрабатывать запросы только из локальной сети.
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.
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.
All DNS Entries
Property Description
Specifications
- Packages required: system
- License required: Level1
- Submenu level: /ip dns
- Standards and Technologies: DNS
- Hardware usage: Not significant
4. Закрываем любой порт.
Для того, что бы закрыть любой порт для подключения из внешней сети достаточно одного правила, которое по своей сути очень простое. В нем мы указываем тип трафика – снаружи, номер порта или диапазон портов, на каком интерфейсе слушать и что с этим трафиком делать.
Для примера давайте закроем порт 8080.
IP->Firewall->Filter Rules->New Firewall rule (синий плюсик).
Все! Вот так просто! Порт закрыт.
Но будьте предельно аккуратны, не стоит беспорядочно закрывать все. В MikroTik’e с завода идет принцип запрещено все, что не разрешено. Поэтому сильно заморачиваться нет необходимости.
2. Закрываем 2000 порт.
На этом порту у нас живет Btest Server. Он служит для оценки эффективности работы сетевого оборудования путем измерения фактической полосы трафика проходящего через сетевые коммутаторы и маршрутизаторы компания Mikrotik предлагает использовать утилиту BTest.
Закрывается он так: зайдите в Tools —> BTest Server, снять галочку Enabled.
Flushing DNS cache
Property Description
Allow remote request - зло или необходимость?
Allow remote request - зло или необходимость?
Привет!
На Пикабу прочитал статью, что у топикстартера стояла галка на Allow remote request и был неестественный внешний трафик.
У меня дома интернет от Ростелекома идет через pppoe, проверяю настройки DNS - галка напротив злосчастного пункта стоит, снимаю - инет пропадает. Отсюда вопрос - нужен ли Allow remote request в моем случае или пропадание интернета связано с кривыми настройками? Кстати, на просторах интернета инструкции по настройке pppoe интернета от Ростелеком не доходили до DNS.
В интернете прочел, что при включенной галке Allow remote request роутер становиться уязвимым от внешних запросов, то 53 порт UDP должен быть закрыт. Короче немного обезопасил себя, в IP Service List включил только Winbox, а в правилах фаервола запретил все, кроме разрешенных (53 порт протокола UDP дропается предпоследним правилом, но вполне возможно, что правила настроил криво, нужно мнение профессионала, правильно ли настроил):
Доброго. Всё — зло, если не понимать, что творишь. Allow Remote Requests — разрешает роутеру работать DNS-сервером для сторонних клиентов (будь то локальные или из Интернета).
Для дома есть два варианта: либо не заморачиваемся на роутере и выдаём всем DNS'ы провайдера/гугла/яндекса/другие внешние, либо выдаём адрес роутера, на роутере разрешаем Allow Remote Requests, а в фильтре файрвола открываем доступ к роутеру по 53-му порту (UDP, можно и TCP, но уже по желанию, не критично) только для локалки (чтобы атаки DNS Amplification из Интернета не пролезли).
снимаю галку - попадает инет, пинги с хоста не идут =(
Почему так произошло, ведь внешние DNS я указал!?
Под "выдаём" я имел в виду DHCP и выдачу клиентам (IP -> DHCP Server -> Networks), а не настройку DNS'ов на самом роутере. В вашем случае (когда клиенты получают адрес роутера как DNS-сервер) вам надо оставить Allow Remote Requests.
Хочешь уметь больше? Научиться тонкостям настройки MikroTik можно из русскоязычного онлайн-курса по MikroTik от автора курсов Дмитрия Скромнова. Здесь можно изучить MikroTik и RouterOS самостоятельно по курсу «Настройка оборудования MikroTik». Курс основан на официальной программе MTCNA, но содержит больше информации. Это 162 видеоурока и большая практическая задача, разбитая на 45 лабораторных работ. Время на изучение неограниченно – все материалы передаются бессрочно и их можно пересматривать сколько нужно. Первые 25 уроков можно посмотреть бесплатно, оставив заявку на странице курса.
1. Закрываем 53 порт для доступа из вне.
Итак, начнем с простого. Поскольку микротик имеет на борту свой собственный DNS сервер, то 53 порт смотрит у него наружу и просит его использовать. Чем грозит открытый 53 порт?
Рано или поздно, у MikroTik с белым IP адресом, можно заметить нагрузку на процессор и утечку трафика, которая вызвана внешними запросами к Вашему DNS серверу.
Падением скорости вашего интернет-соединения. В моей практике был случай, когда в качестве роутера стоял MikroTik RB951Ui. Провайдер давал 80 мегабит канал, а фактическая скорость у клиента не превышала 2-3 мегабита. Клиент ругался с провайдером, приезжали монтажники, проверяли линию, но все тщетно.
Когда я приехал, то сделал следующее.
Подключаемся к нашему пациенту по Winbox и открываем раздел IP->Firewall->Filter Rules. На скриншоте ниже у меня уже добавлены необходимые правила для обработки трафика на 53 порту.
Что бы сделать так же, добавляем первое правило, которое будет заносить все IP флудильщиков в специальный список IP адресов.
- Chain – input;
- Protocol – 17 (udp);
- Dst.port – 53;
- In.interface – ваш интерфейс, куда включен шнурок провайдера. В моем случае это PPPoE-соединение Ростелекома;
- Action – add src to address list;
- Address List – DNS_FLOOD (название может быть любым).
И второе правило, которое и будет ограничивать.
На этом все. Ваш микротик защищен от DNS флуда и канал теперь свободен. Добавив только эти два правила клиент увидел заявленную от провайдера скорость и был очень рад.
Но есть и другие сервисы и порты, которые в микротике по-умолчанию включены и принимают подключения.
Static DNS Entries
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.
Читайте также: