Wall of fire. Learning to set up a firewall using MikroTik as an example.

Lord777

Professional
Messages
2,581
Reputation
15
Reaction score
1,322
Points
113
xmge2Qdj0HE.jpg


The content of the article
  • Connection Tracking
  • Configuration Recommendations
  • Trouble shooting
  • Outcomes
The purpose of the firewall is traffic filtering and packet manipulation. It is he who becomes the first and, unfortunately, in many cases the last bastion of the network. The Internet is full of recommendations on how to configure this part of the system. But mindlessly copying someone else's rules can do more harm than good. Therefore, first you need to understand how a firewall works and what a RouterOS firewall can do.

The firewall, like much else in RouterOS, came from Linux and is a modified iptables. Therefore, many manuals for configuring iptables can be easily converted to the RouterOS format. The firewall consists of the following tables:
  • Filter - deals with traffic filtering - determines whether to let a packet into the network or drop it. We will only consider the operation of this table;
  • NAT - Network Address Translation. Modifies passing packets. Changing the source address or destination port is the business of this particular table. It is mainly used to provide Internet access from LAN and vice versa. Sometimes it is impossible to work without NAT in poorly designed networks, and sometimes it is used as a "crutch";
  • Mangle - classifies and marks traffic and can change some header fields (TTL, ToS, DF). It is used to build complex traffic paths (for example, when two providers are connected or different traffic paths are needed for RDP and VoIP);
  • Raw - processes packets before they get into Connection Tracking. Useful for DoS protection or when working with large volumes of traffic.

Tables are made up of strings. Chains in different tables may differ. A little later it will become clear why. Our Filter table has three chains:
  • input - traffic to the router itself. A prerequisite for getting into input is that the destination address of the packet must be one of the router's addresses, the broadcast address of the network, or the broadcast address of the service running on the router. This includes WinBox, SSH, WebFig, ping, VPN and other traffic destined for the router. You can see the full list on the wiki. In this chain, we must protect the router itself;
  • output - traffic from the router. Replies to incoming packets or new packets from the router (ping, VPN, SSH session from the router itself). This chain is rarely used because the router is often considered a trusted link and the packets it generates are legitimate by default. But, as the history of hacks shows, control of outgoing traffic can detect infection at the initial stages;
  • forward - traffic passing through the router (when a packet arrives at one interface and departs from another or the same one). Traffic from LAN to Internet, from Internet to LAN, from one LAN VLAN to another;
  • user chains - user chains. The admin can create chains of rules at his own discretion. This is useful for decomposing large configurations. For example, you can wrap all traffic to ports 80 and 443 in a separate WEB chain and make dozens of rules for filtering in it - this will visually simplify the configuration, although it will not qualitatively affect the traffic flow.

HDozE7Ce-gg.jpg


There are two important points to keep in mind.

The first moment. Traffic in forward always has incoming and outgoing interfaces - traffic flowed into input, processed by the routing process and should go to output. Incoming traffic cannot have an outgoing interface - it will be processed inside the router and will not fly anywhere further. Also, the outgoing traffic cannot have an incoming interface - this traffic is generated by the router itself (this is either new traffic, or a response created by the router to the traffic that came to the input).

The second moment. Traffic has no "outside" or "inside" interfaces. The router does not care what you consider to be external - it has an interface to which the traffic entered, and an interface from which the traffic leaves.

Rules form chains. Each rule can have only one chain. By default, all chains have a policy - everything is allowed. Rules are triggered in tables depending on their order: first, the packet is processed by the first rule, then by the second, and so on. It is considered good practice to order the rules within tables in chains: first - a bunch of input rules, then - forward, at the end - output.

Traffic will pass according to the rules only within its own chain. And if input goes first, then forward, then input again, then the input traffic will never get into forward, that is, such an arrangement of the rules will not affect the traffic flow, but will only confuse the admin. Within the same table, the package will not jump from one chain to another until the administrator explicitly indicates this.

KR6ryHm5mOs.jpg


Connection Tracking
Another important thing to understand how a firewall works is the mechanism for determining the state of connections - Connection Tracking (or simply ConnTrack). RouterOS has a special table that stores data about the state of the connections. It makes NAT and many other parts of the firewall work.

ConnTrack mechanisms check if the packet arriving at the router belongs to any of the streams in order to apply the policies of the entire stream to it or somehow order the packets within one or several streams (for example, to cut the speed).

wZtD81yz_Q0.jpg


There are four packet states for ConnTrack:
  • new is a new package that does not belong to any known thread. This can be the first packet to connect to the RDP server, or the first packet in a WinBox stream, or a DNS query. The system remembers Source IP, Source Port, Destination IP, Destination Port and some other parameters and writes these data into the table. The next packet with the same data will refer to the recorded stream;
  • established is a package belonging to an existing thread. That is, a packet whose Source IP, Source Port, Destination IP, Destination Port match one of the entries in the ConnTrack table (or return packet);
  • related - a package originated by another thread. Some protocols, such as FTP, SIP, PPTP, use multiple streams to work. For example, FTP control commands go over TCP port 21, but data is transmitted from TCP port 20. When you try to receive or send data to FTP in a stream on port 21, the server reports: “Now I will open port 20, and you take data from him ", after that the client sends the packet to the 20th port of the server. This packet will be considered related since it originated from the port 21 stream;
  • invalid - anything that does not apply to the conditions listed above. Example: the session was closed correctly, but due to routing errors, some of the packets from the middle of the session flew away in a different way. When they arrived, their session was already closed and the router knew nothing about them. They are not new and do not refer to existing connections, so we consider them invalid.
Stream state is not related to TCP flags: SYN, ACK, FIN. For UDP and other stateless protocols, the ConnTrack table also contains all possible states.

oVEZ1R6Ut_0.jpg

Connstate

ConnTrack is CPU intensive and can be CPU intensive with high traffic volumes. But ConnTrack is not needed everywhere, and you can turn it off. For example, providers at the junction with a superior provider have routers that grind tens of gigabits of traffic. On these routers, as a rule, there is no NAT (direct routing), and the traffic is filtered at a lower level so as not to overload the already loaded border. That is, in this case, there is no need to check each packet for belonging to any stream.

By clicking the Tracking button, you can disable the ConnTrack mechanism or tweak the timers. In most cases, you will not need to go into these settings, but you need to know about them. There are three ConnTrack modes: what is yesand no, I think, is clear, and in autoConnTrack mode it is disabled until at least one packet gets into the existing rules of the NAT or Filter table.

Disabled ConnTrack breaks NAT and firewall features based on stream tracking: connection-bytes, connection-mark, connection-type, connection-state, connection-limit, connection-rate, layer7-protocol, new-connection-mark, tarpit.

7JAcZHnjk6E.jpg


Configuration Recommendations
Let's move on to customization practice. In this article I will talk about the Filter table - the one that deals with traffic filtering. As we found out just above, the input chain is responsible for the traffic to the router itself, and the forward chain is responsible for the traffic that passes through the router. Let's take care of protecting the router itself.

The first and most important thing to remember when working with a firewall was described in the lost chapter "Words about Igor's Campaign": "Remote configuration of a firewall - to a long journey." So respect your ancestors - honor their precepts and use Safe Mode.

This mode works like this: you press the Safe Mode button in the interface, and it remains pressed. Then you do everything that you intend to, but these changes will be applied only when you click on the button again. If they lead to a break in the interaction between the router and the WinBox configurator (for example, if you have filtered your own packets or disabled the interface), then the router will return to the state it was before entering Safe Mode.

Only 100 actions are remembered, but this will be enough for most cases. There will be no reboot - the rollback is instant. From the console, this mode is activated by Ctrl-X.

GEDL0UqGvck.jpg


There are two approaches to configuring a firewall:
  • everything that is not prohibited is allowed;
  • everything that is not allowed is prohibited.
None of them can be called unequivocally correct. I am an adherent of the second approach, but in unfamiliar networks I use the first.

To allow the desired traffic, you need to decide on this very traffic. In the case of input, this is fairly easy to do. Here's what you need for the router to work correctly.
  1. Management: WinBox, SSH, in some cases WebFig, for example, to view load graphs.
  2. If the provider issues an address via DHCP, then enable this protocol on the external interface.
  3. If the router is a DHCP server, then enable this protocol on internal interfaces.
  4. It's the same with DNS.
  5. If we are going to raise the tunnels, then we will allow them.
  6. OSPF.
  7. ICMP.
  8. NTP.
  9. Neighbor Discovery.
  10. SNMP.
  11. Other services.
Have you decided? We open the necessary and close everything else.

The firewall works on the principle of "if [condition], then [action]". If the conditions specified in the General, Advanced, Extra tabs are met, then the action from the Action tab is applied to the package. For today, the conditions src / dst address, protocol, src / dst port, in / out interface, connection-state will be enough for us. Their meanings are clear from the name, but if it is suddenly unclear - go ahead and read about the basics of TCP / IP. The most common actions: accept - allowed, drop - forbidden (the packet will simply be destroyed), reject - forbidden, but the sender will receive information that the packet was destroyed for the reason specified in the reject-with.

Each rule in the packet's path wastes CPU time. And if in small networks this is not critical, then with serious traffic volumes, this point must be taken into account. Let's look at an example.

Code:
/ ip firewall filter
add action = accept chain = input dst-port = 8291 protocol = tcp src-address = 10.0.0.0 / 24
add action = accept chain = input dst-port = 8291 protocol = tcp src-address = 10.10.0.0 / 24
add action = accept chain = input dst-port = 8291 protocol = tcp src-address = 10.11.0.0 / 24
add action = accept chain = input dst-port = 22 protocol = tcp src-address = 10.0.0.0 / 24
add action = accept chain = input dst-port = 22 protocol = tcp src-address = 10.10.0.0 / 24
add action = accept chain = input dst-port = 22 protocol = tcp src-address = 10.11.0.0 / 24
add action = drop chain = input

In this case, when trying to connect to the router via SSH from the address 10.11.0.11, the firewall will ask the CPU six times to ask whether to let this traffic through. It looks something like this: “8291 is not our port - we skip further. 10.0.0.0/24 - not our subnet, skip further. The same for 10.10.0.0/24, and only the sixth rule is appropriate. " At the sixth step, the firewall will understand that the traffic is legitimate and can be passed.

FTP packets and all other unauthorized traffic will jerk the CPU seven times - the first six and the last drop. And this is in a fictitious example of seven rules. In real life, there are an order of magnitude or two more rules.

The first thing we can do is combine the two ports in one rule:

Code:
/ ip firewall filter
add action = accept chain = input dst-port = 8291.22 protocol = tcp src-address = 10.0.0.0 / 24
add action = accept chain = input dst-port = 8291.22 protocol = tcp src-address = 10.10.0.0 / 24
add action = accept chain = input dst-port = 8291.22 protocol = tcp src-address = 10.11.0.0 / 24
add action = drop chain = input

owcdY96vj5s.jpg


Reduced the load a little. But there are three identical rules with the only difference in addresses. With the help of the Address List, we can combine them into one.

Address List is a RouterOS feature that allows you to combine IP addresses, subnets and DNS names into one record.
We create three entries in one Address List.

bni2iJKhYHM.jpg

Make Address List/ ip firewall address-list

Code:
add address = 10.0.0.0 / 24 list = MGMT
add address = 10.10.0.0 / 24 list = MGMT
add address = 10.11.0.0 / 24 list = MGMT
And we apply it to our rule.

FYhTij0DWic.jpg


Code:
/ ip firewall filter
add action = accept chain = input dst-port = 8291.22 protocol = tcp src-address-list = MGMT
add action = drop chain = input

So out of seven rules, we got two and got rid of the unnecessary load. By analogy with address lists, interface lists work (I considered them in the previous article - " Protecting MikroTik"): we combine interfaces of different providers into one interface list and hang the rules not on the interfaces themselves, but on the lists. So we will not only reduce the load, but also simplify the life of the administrator: the fewer the rules, the more convenient it is to maintain the system.

Another way to make it easier for your firewall is to use ConnTrack. It is clear that there will be many more established packages than new, related and invalid combined. And since we allowed the first packet from the stream, then all other packets in this stream can be considered legitimate. So we just create an "allow established" rule and put it at the very top.

ix7KKADf18E.jpg


Choose the protocols and ports you need, create the corresponding lists of addresses and interfaces. Open everything you need and set the last rule to drop all. This completes the basic setup of the input chain.

By the way, by default, the firewall is equipped with a fairly strong setting - it is quite enough for a network of almost any size to work normally. But there are always some peculiarities and any config can be improved taking into account your conditions.

For example configuration you can take my template.

Trouble shooting
When the firewall doesn't work or doesn't work the way it was configured, it's the admin's fault. There is no magic. The first thing to look out for when troubleshooting is packet counters. If the counter does not increase, then the traffic does not get into it. And if the traffic does not reach, then either this traffic is simply not there, or it was processed by the above rule.

FCgLKGllfiM.jpg

Counters

Do you remember that firewall rules work according to the principle "who got up first - that and the slippers"? If the packet falls under the rule, then it will not go further. This means that we need to look for the problem above. We just copy our rule, set the action to accept (for troubleshooting, do not drop - so when checking, you can break your access or disrupt the network) and gradually move it up until the first increase in the counters in this rule. If traffic has already passed through this rule, then the counters will be non-zero and you can skip the packets we need - just reset the counters in this rule or in all with the Reset Counters buttons.

1QKxiaJnK0I.jpg


Code:
/ ip firewall filter reset-counters-all
or
Code:
/ ip firewall filter reset-counters numbers = <rule number>

Suppose we have found a rule that our traffic falls into, but should not. You need to understand why this is happening. The Log option will help us with this. In the Action tab, check the Log box (you can write a prefix for the rule to make it easier to catch it in the logs) and look at the logs, where all the characteristics of the packets that fall under the rule are written. Among the characteristics: chain, inbound and outbound interfaces, source and destination addresses and ports, protocol, flags, packet size, NAT actions.

-W3fJC_tWds.jpg

Log

If even at the very top in the rule the counters will not increase, remove the rules from the condition one by one. Start with interfaces - admins are often confused in their ideas about where or where traffic should go (for example, when connecting to a provider via PPPoE or in tunnels between branches or complex routing). Are the counters off? We turn on the log and look at the interfaces and other parameters.

If that doesn't help, it's time for heavy artillery. Go to Tools → Torch and study the traffic on the router. Maybe there is no expected traffic at all. Another cool tool is tcpdump analog - Tools → Packet Sniffer. Analysis of the work of these tools draws on a separate article (if you are interested in it, let us know in the comments to the article).

To simplify troubleshooting, you can use the comment function. If, because of the comments, the window becomes too large and it interferes with looking at the rules, use Inline Comments. So the comments will appear with the rule in one line and more rules will fit into the window.

WUGLjG9gBWs.jpg

Inline Comments

I also recommend distributing the rules in order, following some specific logic. And try to support it on all routers.

Outcomes
This article only covers the basics of firewall configuration and general diagnostic methods. Apart from RouterOS, these principles apply to Linux as well. In the next article, we will analyze more complex rules that allow us to protect ourselves from not the most simple attacks, and analyze the Forward chain, as well as create our own chains.
 
Top