Настройка mikrotik firewall ftp
Network Address Translation is an Internet standard that allows hosts on local area networks to use one set of IP addresses for internal communications and another set of IP addresses for external communications. A LAN that uses NAT is referred as natted network. For NAT to function, there should be a NAT gateway in each natted network. The NAT gateway (NAT router) performs IP address rewriting on the way a packet travel from/to LAN.
There are two types of NAT:
- source NAT or srcnat. This type of NAT is performed on packets that are originated from a natted network. A NAT router replaces the private source address of an IP packet with a new public IP address as it travels through the router. A reverse operation is applied to the reply packets travelling in the other direction.
- destination NAT or dstnat. This type of NAT is performed on packets that are destined to the natted network. It is most comonly used to make hosts on a private network to be acceesible from the Internet. A NAT router performing dstnat replaces the destination IP address of an IP packet as it travel through the router towards a private network.
Hosts behind a NAT-enabled router do not have true end-to-end connectivity. Therefore some Internet protocols might not work in scenarios with NAT. Services that require the initiation of TCP connection from outside the private network or stateless protocols such as UDP, can be disrupted. Moreover, some protocols are inherently incompatible with NAT, a bold example is AH protocol from the IPsec suite.
To overcome these limitations RouterOS includes a number of so-called NAT helpers, that enable NAT traversal for various protocols.
Interface Lists
Two interface lists will be used WAN and LAN for easier future management purposes. Interfaces connected to the global internet should be added to the WAN list, in this case, it is ether1!
5. Оригиналы источников информации.
-
«Защита Mikrotik от взлома». «Закрываем 53й порт DNS на роутере Mikrotik от внешних запросов».
Хочешь уметь больше? Научиться тонкостям настройки MikroTik можно из русскоязычного онлайн-курса по MikroTik от автора курсов Дмитрия Скромнова. Здесь можно изучить MikroTik и RouterOS самостоятельно по курсу «Настройка оборудования MikroTik». Курс основан на официальной программе MTCNA, но содержит больше информации. Это 162 видеоурока и большая практическая задача, разбитая на 45 лабораторных работ. Время на изучение неограниченно – все материалы передаются бессрочно и их можно пересматривать сколько нужно. Первые 25 уроков можно посмотреть бесплатно, оставив заявку на странице курса.
From everything we have learned so far, let's try to build an advanced firewall. In this firewall building example, we will try to use as many firewall features as we can to illustrate how they work and when they should be used the right way.
Most of the filtering will be done in the RAW firewall, a regular firewall will contain just a basic rule set to accept established, related, and untracked connections as well as dropping everything else not coming from LAN to fully protect the router.
Masquerade Local Network
For local devices behind the router to be able to access the internet, local networks must be masqueraded. In most cases, it is advised to use src-nat instead of masquerade, however in this case when the WAN address is dynamic it is the only option.
Notice the disabled policy matcher rule, the same as in firewall filters IPSec traffic must be excluded from being NATed (except specific scenarios where IPsec policy is configured to match NAT`ed address). So whenever IPsec tunnels are used on the router this rule must be enabled.
3. Разрешаем порты в Firewall.
Заходим IP —> Firewall —> NAT
Делаем разрешение FTP на Firewall — внешний IP адрес + произвольный порт.
Делаем разрешение FTP на Firewall — внешний IP адрес + диапазон портов пассивного режима.
IPv6 RAW Rules
Raw IPv6 rules will perform the following actions:
- add disabled accept rule - can be used to quickly disable RAW filtering without disabling all RAW rules;
- drop packets that use bogon IPs;
- drop from invalid SRC and DST IPs;
- drop globally unroutable IPs coming from WAN;
- drop bad ICMP;
- accept everything else coming from WAN and LAN;
- drop everything else, to make sure that any newly added interface (like PPPoE connection to service provider) is protected against accidental misconfiguration.
Notice that the optional ICMP chain was used. If you want a very strict firewall then such strict ICMP filtering can be used, but in most cases, it is not necessary and simply adds more load on the router's CPU. ICMP rate limit in most cases is also unnecessary since the Linux kernel is already limiting ICMP packets to 100pps
2. Исходные данные.
FTP в локальной сети на порту 21 (для пассивного режима диапазон портов 30000-35000). MikroTik в качестве шлюза.
Basic examples
Carrier-Grade NAT (CGNAT) or NAT444
To combat IPv4 address exhaustion, new RFC 6598 was deployed. The idea is to use shared 100.64.0.0/10 address space inside carrier's network and performing NAT on carrier's edge router to sigle public IP or public IP range.
Because of nature of such setup it is also called NAT444, as opposed to a NAT44 network for a 'normal' NAT environment, three different IPv4 address spaces are involved.
CGNAT configuration on RouterOS does not differ from any other regular source NAT configuration:
- 2.2.2.2 - public IP address,
- public_if - interface on providers edge router connected to internet
The advantage of NAT444 is obvious, less public IPv4 addresses used. But this technique comes with mayor drawbacks:
- The service provider router performing CGNAT needs to maintain a state table for all the address translations: this requires a lot of memory and CPU resources.
- Console gaming problems. Some games fail when two subscribers using the same outside public IPv4 address try to connect to each other.
- Tracking of users for legal reasons means extra logging, as multiple households go behind one public address.
- Anything requiring incoming connections is broken. While this already was the case with regular NAT, end users could usually still set up port forwarding on their NAT router. CGNAT makes this impossible. This means no web servers can be hosted here, and IP Phones cannot receive incoming calls by default either.
- Some web servers only allow a maximum number of connections from the same public IP address, as a means to counter DoS attacks like SYN floods. Using CGNAT this limit is reached more often and some services may be of poor quality.
- 6to4 requires globally reachable addresses and will not work in networks that employ addresses with limited topological span.
More on things that can break can be read in this article [1]
Packets with Shared Address Space source or destination addresses MUST NOT be forwarded across Service Provider boundaries. Service Providers MUST filter such packets on ingress links. In RouterOS this can be easily done with firewall filters on edge routers:
Service providers may be required to do logging of MAPed addresses, in large CGN deployed network that may be a problem. Fortunately RFC 7422 suggests a way to manage CGN translations in such a way as to significantly reduce the amount of logging required while providing traceability for abuse response.
RFC states that instead of logging each connection, CGNs could deterministically map customer private addresses (received on the customer-facing interface of the CGN, a.k.a., internal side) to public addresses extended with port ranges.
In RouterOS described algorithm can be done with few script functions. Lets take an example:
Inside IP | Outside IP/Port range |
100.64.1.1 | 2.2.2.2:2000-2099 |
100.64.1.2 | 2.2.2.2:2100-2199 |
100.64.1.3 | 2.2.2.2:2200-2299 |
100.64.1.4 | 2.2.2.2:2300-2399 |
100.64.1.5 | 2.2.2.2:2400-2499 |
100.64.1.6 | 2.2.2.2:2500-2599 |
Instead of writing NAT mappings by hand we could write a function which adds such rules automatically.
After pasting above script in the terminal function "addNatRules" is available. If we take our example, we need to map 6 shared network addresses to be mapped to 2.2.2.2 and each address uses range of 100 ports starting from 2000. So we run our function:
Сегодняшний пост будет продолжением начатой темы о подключение USB накопителя к роутеру MikroTik и поднятии на нём файлового сервера SMB. Речь пойдёт о том, как получить доступ к данным, размещённым на флешке или жестком диске удалённо из сети Интернет. Сразу оговорюсь, что я не сторонник подобного решения из соображений безопасности, потому воспринимайте данный материал чисто в академических целях и пользуйтесь облачными хранилищами.
Мне так и не удалось открыть SMB-сервер на MikroTik наружу, хоть и ставил в настройках слушать на всех интерфейсах, пробовал открывать порты 137-139 и 445 в настройках файервола - всё бестолку (если знаете способ заставить микрот принимать SMB соединения снаружи, напишите к комментариях).
Настройка FTP сервера на MikroTik стала самым простым решением проблемы доступа к данными на флешке, подключенной к роутеру из Интернет. Делается это буквально в пару кликов, но понадобится ещё создать правило для файервола.
1. Постановка задачи.
Задача: Пробросить FTP наружу c локального IP адреса.
1:1 mapping
If you want to link Public IP subnet 11.11.11.0/24 to local one 2.2.2.0/24, you should use destination address translation and source address translation features with action=netmap.
Same can be written using different address notation, that still have to match with the described network
Активация FTP-сервера и настройка Firewall на MikroTik
Для начала активируем сам FTP сервер на роутере MikroTik, для чего переходим в меню IP -> Services и переводим сервис ftp в активное положение. Как обычно, я показываю все действия в web-интерфейсе.
Собственно, ftp-сервер у нас уже работает. Это можно легко проверить набрав в браузере или в проводнике внутренний адрес вашего роутера, например ftp://192.168.88.1 и входим с именем и паролем администратора. Но нам нужен доступ снаружи, а вот тут облом.
Чтобы разрешить подключение снаружи, нужно в файерволе разрешить доступ к 21 порту на интерфейсе ether1-gateway и переместить данное правило выше всех запрещающих правил.
Переходим в IP -> Firewall и на вкладке Filter Rules добавляем новое правило:
- Chain (Цепочка) -> Input
- Protocol -> tcp
- Dst. Port -> 21
- In. Interface -> ваше соединение с провайдером (pрpe, wan, ether1-gateway - в зависимости от версии прошивки или типа соединения с провайдером)
- Action -> Accept
Подробнее о значении полей при настройке файервола можно узнать из статьи "Проброс портов на MikroTik". То же самое можно сделать из командной строки:
/ip firewall filter add chain=input action=accept protocol=tcp in-interface=ether1-gateway dst-port=21
Не забываем переместить данное правило выше запрещающих. Теперь у нас есть доступ снаружи к нашей флешке по FTP. Остались небольшие штрихи.
IPv4 RAW Rules
Raw IPv4 rules will perform the following actions:
- add disabled "accept" rule - can be used to quickly disable RAW filtering without disabling all RAW rules;
- accept DHCP discovery - most of the DHCP packets are not seen by an IP firewall, but some of them are, so make sure that they are accepted;
- drop packets that use bogon IP`s;
- drop from invalid SRC and DST IP`s;
- drop globally unroutable IP`s coming from WAN;
- drop packets with source-address not equal to 192.168.88.0/24 (default IP range) coming from LAN;
- drop packets coming from WAN to be forwarded to 192.168.88.0/24 network, this will protect from attacks if the attacker knows internal network;
- drop bad ICMP, UDP, and TCP;
- accept everything else coming from WAN and LAN;
- drop everything else, to make sure that any newly added interface (like PPPoE connection to service provider) is protected against accidental misconfiguration.
Notice that we used some optional chains, the first TCP chain to drop TCP packets known to be invalid.
And another chain for ICMP. Note that if you want a very strict firewall then such strict ICMP filtering can be used, but in most cases, it is not necessary and simply adds more load on the router's CPU. ICMP rate limit in most cases is also unnecessary since the Linux kernel is already limiting ICMP packets to 100pps.
4. Проброс портов в NAT.
Заходим IP —> Firewall —> NAT
Делаем проброс с локального IP адреса + 21 порта на внешний IP адрес + произвольный порт.
Делаем проброс с локального IP адреса + диапазон портов пассивного режима на внешний IP адрес + диапазон портов пассивного режима.
Menu specific commands
Property | Description |
---|---|
reset-counters (id) | Reset statistics counters for specified firewall rules. |
reset-counters-all ( ) | Reset statistics counters for all firewall rules. |
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 поступающих на порты которые смотрят в сеть провайдера и разрешить обрабатывать запросы только из локальной сети.
2. Закрываем 2000 порт.
На этом порту у нас живет Btest Server. Он служит для оценки эффективности работы сетевого оборудования путем измерения фактической полосы трафика проходящего через сетевые коммутаторы и маршрутизаторы компания Mikrotik предлагает использовать утилиту BTest.
Закрывается он так: зайдите в Tools —> BTest Server, снять галочку Enabled.
5. Оригиналы источников информации.
Хочешь уметь больше? Научиться тонкостям настройки MikroTik можно из русскоязычного онлайн-курса по MikroTik от автора курсов Дмитрия Скромнова. Здесь можно изучить MikroTik и RouterOS самостоятельно по курсу «Настройка оборудования MikroTik». Курс основан на официальной программе MTCNA, но содержит больше информации. Это 162 видеоурока и большая практическая задача, разбитая на 45 лабораторных работ. Время на изучение неограниченно – все материалы передаются бессрочно и их можно пересматривать сколько нужно. Первые 25 уроков можно посмотреть бесплатно, оставив заявку на странице курса.
Хочешь уметь больше? Научиться тонкостям настройки MikroTik можно из русскоязычного онлайн-курса по MikroTik от автора курсов Дмитрия Скромнова. Здесь можно изучить MikroTik и RouterOS самостоятельно по курсу «Настройка оборудования MikroTik». Курс основан на официальной программе MTCNA, но содержит больше информации. Это 162 видеоурока и большая практическая задача, разбитая на 45 лабораторных работ. Время на изучение неограниченно – все материалы передаются бессрочно и их можно пересматривать сколько нужно. Первые 25 уроков можно посмотреть бесплатно, оставив заявку на странице курса.
Properties
For example, if router receives Ipsec encapsulated Gre packet, then rule ipsec-policy=in,ipsec will match Gre packet, but rule ipsec-policy=in,none will match ESP packet.
- any - match packet with at least one of the ipv4 options
- loose-source-routing - match packets with loose source routing option. This option is used to route the internet datagram based on information supplied by the source
- no-record-route - match packets with no record route option. This option is used to route the internet datagram based on information supplied by the source
- no-router-alert - match packets with no router alter option
- no-source-routing - match packets with no source routing option
- no-timestamp - match packets with no timestamp option
- record-route - match packets with record route option
- router-alert - match packets with router alter option
- strict-source-routing - match packets with strict source routing option
- timestamp - match packets with timestamp
- count - maximum average packet rate measured in packets per time interval
- time - specifies the time interval in which the packet rate is measured (optional, 1s will be used if not specified)
- burst - number of packets which are not counted by packet rate
- WeightThreshold - total weight of the latest TCP/UDP packets with different destination ports coming from the same host to be treated as port scan sequence
- DelayThreshold - delay for the packets with different destination ports coming from the same host to be treated as possible port scan subsequence
- LowPortWeight - weight of the packets with privileged ( <1024) destination port
- HighPortWeight - weight of the packet with non-priviliged destination port
Matches source address type:
- unicast - IP address used for point to point transmission
- local - if address is assigned to one of router's interfaces
- broadcast - packet is sent to all devices in subnet
- multicast - packet is forwarded to defined group of devices
Protect the Device
The main goal here is to allow access to the router only from LAN and drop everything else.
Notice that ICMP is accepted here as well, it is used to accept ICMP packets that passed RAW rules.
IPv6 part is a bit more complicated, in addition, UDP traceroute, DHCPv6 client PD, and IPSec (IKE, AH, ESP) is accepted as per RFC recommendations.
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 флуда и канал теперь свободен. Добавив только эти два правила клиент увидел заявленную от провайдера скорость и был очень рад.
Но есть и другие сервисы и порты, которые в микротике по-умолчанию включены и принимают подключения.
Masquerade
Firewall NAT action=masquerade is unique subversion of action=srcnat , it was designed for specific use in situations when public IP can randomly change, for example DHCP-server changes it, or PPPoE tunnel after disconnect gets different IP, in short - when public IP is dynamic.
Every time interface disconnects and/or its IP address changes, router will clear all masqueraded connection tracking entries that send packet out that interface, this way improving system recovery time after public ip address change.
Unfortunately this can lead to some issues when action=masquerade is used in setups with unstable connections/links that get routed over different link when primary is down. In such scenario following things can happen:
- on disconnect, all related connection tracking entries are purged;
- next packet from every purged (previously masqueraded) connection will come into firewall as connection-state=new , and, if primary interface is not back, packet will be routed out via alternative route (if you have any) thus creating new connection;
- primary link comes back, routing is restored over primary link, so packets that belong to existing connections are sent over primary interface without being masqueraded leaking local IPs to a public network.
You can workaround this by creating blackhole route as alternative to route that might disappear on disconnect).
When action=srcnat is used instead, connection tracking entries remain and connections can simply resume.
Комментариев: 7
Вроде все доступно. Попробуем. Настраивал микротик на два канала имел много проблем, хотя тоже по описаниям ничего сложного. Надеюсь здесь будет все так же просто как описано. Спасибо.
Из вне НЕ работает, правило не помогает, пароль спрашивает и на этом кино заканчивается. В локалке - без проблем
Всё работает, у парня всё правильно описано, просто руки надо достать и правильно настроить изначально микрот, не для начинающих машинка-то.
Чтоб извне работало, нужен внешник на Up-link'e а не серый IP от провайдера.
Ftp как и smb шару, я бы рекомендовал делать исключительно для локального доступа. А для того чтобы был доступ снаружи, предварительно можно поднять vpn сервер l2tp например, и уже находясь внутри своей сети пользоваться файловым хранилищем.
Чтобы работал из-вне, нужно в Firewall в разделе Service Ports прописать порт FTP и включить его.
Мне так и не удалось открыть SMB-сервер на MikroTik наружу, хоть и ставил в настройках слушать на всех интерфейсах, пробовал открывать порты 137-139 и 445 в настройках файервола
Многие провайдеры в принципе фильтруют эти порты. Даже на внутрисетевых коммутаторах. Ибо некоторые пользователи работают без роутера, виндовой машиной, с выключенным фаерволом. Еще многие провайдеры фильтруют 25-й порт. До отдельной просьбы этого не делать. В силу тех же причин.
Хочешь уметь больше? Научиться тонкостям настройки MikroTik можно из русскоязычного онлайн-курса по MikroTik от автора курсов Дмитрия Скромнова. Здесь можно изучить MikroTik и RouterOS самостоятельно по курсу «Настройка оборудования MikroTik». Курс основан на официальной программе MTCNA, но содержит больше информации. Это 162 видеоурока и большая практическая задача, разбитая на 45 лабораторных работ. Время на изучение неограниченно – все материалы передаются бессрочно и их можно пересматривать сколько нужно. Первые 25 уроков можно посмотреть бесплатно, оставив заявку на странице курса.
Protect the Clients
Before the actual set of rules, let's create a necessary address-list that contains all IPv4/6 addresses that cannot be forwarded.
Notice that in this list multicast address range is added. It is there because in most cases multicast is not used. If you intend to use multicast forwarding, then this address list entry should be disabled.
In the same case for IPv6, if multicast forwarding is used then the multicast entry should be disabled from the address-list.
Forward chain will have a bit more rules than input:
- accept established, related and untracked connections;
- FastTrack established and related connections (currently only IPv4);
- drop invalid connections;
- drop bad forward IP`s, since we cannot reliably determine in RAW chains which packets are forwarded
- drop connections initiated from the internet (from the WAN side which is not destination NAT`ed);
- drop bogon IP`s that should not be forwarded.
We are dropping all non-dstnated IPv4 packets to protect direct attacks on the clients if the attacker knows the internal LAN network. Typically this rule would not be necessary since RAW filters will drop such packets, however, the rule is there for double security in case RAW rules are accidentally messed up.
IPv6 forward chain is very similar, except that IPsec and HIP are accepted as per RFC recommendations and ICMPv6 with hop-limit=1 is dropped.
Notice the IPsec policy matcher rules. It is very important that IPsec encapsulated traffic bypass fast-track. That is why as an illustration we have added a disabled rule to accept traffic matching IPsec policies. Whenever IPsec tunnels are used on the router this rule should be enabled. For IPv6 it is much more simple since it does not have fast-track support.
Another approach to solving the IPsec problem is to add RAW rules, we will talk about this method later in the RAW section
4. Закрываем любой порт.
Для того, что бы закрыть любой порт для подключения из внешней сети достаточно одного правила, которое по своей сути очень простое. В нем мы указываем тип трафика – снаружи, номер порта или диапазон портов, на каком интерфейсе слушать и что с этим трафиком делать.
Для примера давайте закроем порт 8080.
IP->Firewall->Filter Rules->New Firewall rule (синий плюсик).
Все! Вот так просто! Порт закрыт.
Но будьте предельно аккуратны, не стоит беспорядочно закрывать все. В MikroTik’e с завода идет принцип запрещено все, что не разрешено. Поэтому сильно заморачиваться нет необходимости.
Destination NAT
Forward all traffic to internal host
If you want to link Public IP 10.5.8.200 address to Local one 192.168.0.109, you should use destination address translation feature of the MikroTik router. Also if you want allow Local server to initiate connections to outside with given Public IP you should use source address translation, too.
Add Public IP to Public interface:
Add rule allowing access to the internal server from external networks:
Add rule allowing the internal server to initate connections to the outer networks having its source address translated to 10.5.8.200:
Port mapping/forwarding
If you would like to direct requests for a certain port to an internal machine (sometimes called opening a port, port mapping), you can do it like this:
This rule translates to: when an incoming connection requests TCP port 1234, use the DST-NAT action and redirect it to local address 192.168.1.1 and the port 1234
Port forwarding to internal FTP server
As you can see from illustration above FTP uses more than one connection, but only command channel should be forwarded by Destination nat. Data channel is considered as related connection and should be accepted with "accept related" rule if you have strict firewall. Note that for related connections to be properly detected FTP helper has to be enabled.
Note that active FTP might not work if client is behind dumb firewall or NATed router, because data channel is initiated by the server and cannot directly access the client.
If client is behind Mikrotik router, then make sure that FTP helper is enabled
Добавление пользователя FTP
Чтобы не лазить на наш ftp-сервер от имени администратора, можно создать другого пользователя с паролем, для чего открываем меню System -> Users и нажимаем Add New.
В поле Name вводим желаемое имя пользователя, например ftp_user, в списке Group выбираем read или write (если нужны права записи) и задаём пароль, желательно сложный из цифр букв в разных регистрах и символов.
И последний штрих, без которого наш пользователь не сможет авторизоваться. На вкладке Groups, откройте параметры выбранной группы write и проверьте, чтобы обязательно стояла галочка напротив ftp.
Если статья понравилась, ставь лайк и подписывайся на канал Дзен и паблик вконтакте.
Если считаете статью полезной,
не ленитесь ставить лайки и делиться с друзьями.
Проблема с удалением Kaspersky CRYSTAL Обход блокировок. Как без проблем скачивать фильмы с Рутрекера Пароль от «админки» для роутеров Ростелеком Проброс портов на MikroTik Как удалить Avast и почему из антивируса он превратился в такую дрянь Миф или правда: экраны современных телевизоров и мониторов не мерцают
Source NAT
Masquerade
If you want to "hide" the private LAN 192.168.0.0/24 "behind" one address 10.5.8.109 given to you by the ISP, you should use the source network address translation (masquerading) feature of the MikroTik router. The masquerading will change the source IP address and port of the packets originated from the network 192.168.0.0/24 to the address 10.5.8.109 of the router when the packet is routed through it.
To use masquerading, a source NAT rule with action 'masquerade' should be added to the firewall configuration:
All outgoing connections from the network 192.168.0.0/24 will have source address 10.5.8.109 of the router and source port above 1024. No access from the Internet will be possible to the Local addresses. If you want to allow connections to the server on the local network, you should use destination Network Address Translation (NAT).
Source nat to specific address
If you have multiple public IP addresses, source nat can be changed to specific IP, for example, one local subnet can be hidden behind first IP and second local subnet is masqueraded behind second IP.
IPv6 Address Lists
List of IPv6 addresses that should be dropped instantly
List of IPv6 addresses that are not globally routable
List of addresses as an invalid destination address
List of addresses as an invalid source address
IPv4 Address Lists
Before setting RAW rules, let's create some address lists necessary for our filtering policy. RFC 6890 will be used as a reference.
First, address-list contains all IPv4 addresses that cannot be used as src/dst/forwarded, etc. (will be dropped immediately if such address is seen)
Another address list contains all IPv4 addresses that cannot be routed globally.
And last two address lists for addresses that cannot be as destination or source address.
Masquerade
Firewall NAT action=masquerade is unique subversion of action=srcnat , it was designed for specific use in situations when public IP can randomly change, for example DHCP-server changes it, or PPPoE tunnel after disconnect gets different IP, in short - when public IP is dynamic.
Every time interface disconnects and/or its IP address changes, router will clear all masqueraded connection tracking entries that send packet out that interface, this way improving system recovery time after public ip address change.
Unfortunately this can lead to some issues when action=masquerade is used in setups with unstable connections/links that get routed over different link when primary is down. In such scenario following things can happen:
- on disconnect, all related connection tracking entries are purged;
- next packet from every purged (previously masqueraded) connection will come into firewall as connection-state=new , and, if primary interface is not back, packet will be routed out via alternative route (if you have any) thus creating new connection;
- primary link comes back, routing is restored over primary link, so packets that belong to existing connections are sent over primary interface without being masqueraded leaking local IPs to a public network.
You can workaround this by creating blackhole route as alternative to route that might disappear on disconnect).
When action=srcnat is used instead, connection tracking entries remain and connections can simply resume.
Stats
/ip firewall nat print stats will show additional read-only properties
Property | Description |
---|---|
bytes (integer) | Total amount of bytes matched by the rule |
packets (integer) | Total amount of packets matched by the rule |
By default print is equivalent to print static and shows only static rules.
To print also dynamic rules use print all.
Or to print only dynamic rules use print dynamic
Читайте также: