Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: typos

Table of Contents

Overview

Introduction

Image Added

...

languageros

...

The firewall implements stateful (by utilizing connection tracking) and stateless packet filtering and thereby provides security functions that are used to manage data flow to, from, and through the router. Along with the Network Address Translation (NAT), it serves as a tool for preventing unauthorized access to directly attached networks and the router itself as well as a filter for outgoing traffic.

Network  Network firewalls keep outside threats away from sensitive data available inside the network. Whenever different networks are joined together, there is always a threat that someone from outside of your network will break into your LAN. Such break-ins may result in private data being stolen and distributed, valuable data being altered or destroyed, or entire hard drives being erased. Firewalls are used as a means of preventing or minimizing the security risks inherent in connecting to other networks. Properly A properly configured firewall plays a key role in efficient and secure network infrastructure deployment.

Firewall filter

Chains

The firewall operates by means of firewall rules. Each rule consists of two parts - the matcher which matches traffic flow against given conditions and the action which defines what to do with the matched packet.

There are three predefined chains, which cannot be deleted:

  • input - used to process packets entering the router through one of the interfaces with the destination IP address which is one of the router's addresses. Packets passing through the router are not processed against the rules of the input chain
  • forward - used to process packets passing through the router
  • output - used to process packets originated from the router and leaving it through one of the interfaces. Packets passing through the router are not processed against the rules of the output chain

When processing a chain, rules are taken from the chain in the order they are listed there from top to bottom. If a packet matches the criteria of the rule, then the specified action is performed on it, and no more rules are processed in that chain (the exception is the passthrough action). If a packet has not matched any rule within the built-in chain, then it is accepted.

Custom chain

A packet should be matched against the IP address:port pair. Of course, it could be achieved by adding as many rules with IP address:port match as required to the forward chain, but a better way could be to add one rule that matches traffic from a particular IP address, e.g.: /ip firewall filter add src-address=1.1.1.2/32 jump-target="mychain" and in case of successful match passes control over the IP packet to some other chain, id est mychain in this example. Then rules that perform matching against separate ports can be added to mychain chain without specifying the IP addresses.

Properties

...

  • accept - accept the packet. The packet is not passed to the next firewall rule.
  • add-dst-to-address-list - add destination address to address list specified by address-list parameter
  • add-src-to-address-list - add source address to address list specified by address-list parameter
  • drop - silently drop the packet
  • fasttrack-connection - process packets from a connection using FastPath by enabling FastTrack for the connection
  • jump - jump to the user defined chain specified by the value of jump-target parameter
  • log - add a message to the system log containing the following data: in-interface, out-interface, src-mac, protocol, src-ip:port->dst-ip:port and length of the packet. After a packet is matched it is passed to next rule in the list, similar as passthrough
  • passthrough - if packet is matched by the rule, increase counter and go to next rule (useful for statistics)
  • reject - drop the packet and send an ICMP reject message
  • return - passes control back to the chain from where the jump took place
  • tarpit - captures and holds TCP connections (replies with SYN/ACK to the inbound TCP SYN packet)

...

  • established - a packet which belongs to an existing connection
  • invalid - a packet that does not have determined state in connection tracking (usually - severe out-of-order packets, packets with wrong sequence/ack number, or in case of resource over usage on router), for this reason invalid packet will not participate in NAT (as only connection-state=new packets do), and will still contain original source IP address when routed. We strongly suggest to drop all connection-state=invalid packets in firewall filter forward and input chains
  • new - the packet has started a new connection, or otherwise associated with a connection which has not seen packets in both directions.
  • related - a packet which is related to, but not part of an existing connection, such as ICMP errors or a packet which begins FTP data connection
  • untracked - packet which was set to bypass connection tracking in firewall RAW tables.

...

  • unicast - IP address used for point to point transmission
  • local - if dst-address is assigned to one of the router's interfaces
  • broadcast - packet is sent to all devices in subnet
  • multicast - packet is forwarded to a defined group of devices

...

  • count - packet count per time interval per flow to match
  • time - specifies the time interval in which the packet count per flow cannot be exceeded (optional, 1s will be used if not specified)
  • burst - initial number of packets per flow to match: this number gets recharged by one every time/count, up to this number
  • mode - this parameter specifies what unique fields define flow (src-address, dst-address, src-and-dst-address, dst-address-and-port, addresses-and-dst-port)
  • expire - specifies interval after which flow with no packets will be allowed to be deleted (optional)

...

  • auth - matches authenticted HotSpot client packets
  • from-client - matches packets that are coming from the HotSpot client
  • http - matches HTTP requests sent to the HotSpot server
  • local-dst - matches packets that are destined to the HotSpot server
  • to-client - matches packets that are sent to the HotSpot client

...

  • in - valid in the PREROUTING, INPUT and FORWARD chains
  • out - valid in the POSTROUTING, OUTPUT and FORWARD chains
  • ipsec - matches if the packet is subject to IpSec processing;
  • none - matches packet that is not subject to IpSec processing (for example, IpSec transport packet).

For example, if a router receives an IPsec encapsulated Gre packet, then rule ipsec-policy=in,ipsec will match Gre packet, but rule ipsec-policy=in,none will match the 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 - packet or bit count per time interval to match
  • time - specifies the time interval in which the packet or bit count cannot be exceeded (optional, 1s will be used if not specified)
  • burst - initial number of packets or bits to match: this number gets recharged every 10ms so burst should be at least 1/100 of rate per second
  • mode - packet or bit mode

...

  • 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-privileged destination port

...

Matches source address type:

  • unicast - IP address used for point to point transmission
  • local - if an address is assigned to one of the router's interfaces
  • broadcast - packet is sent to all devices in subnet
  • multicast - packet is forwarded to a defined group of devices

...

  • ack - acknowledging data
  • cwr - congestion window reduced
  • ece - ECN-echo flag (explicit congestion notification)
  • fin - close connection
  • psh - push function
  • rst - drop connection
  • syn - new connection
  • urg - urgent data

...

Filter stats

Code Block
languageros
/ip firewall filter print stats

Will show additional read-only properties

...

Code Block
languageros
[admin@mikrotik] /ip firewall mangle> print stats
Flags: X - disabled, I - invalid, D - dynamic 
 #   CHAIN              ACTION                  BYTES           PACKETS        
 0   prerouting         mark-routing            17478158        127631         
 1   prerouting         mark-routing            782505          4506    
To print also dynamic rules use print all.
Code Block
languageros
[admin@mikrotik] /ip firewall mangle> print all stats
Flags: X - disabled, I - invalid, D - dynamic 
 #   CHAIN              ACTION                  BYTES           PACKETS        
 0   prerouting         mark-routing            17478158        127631         
 1   prerouting         mark-routing            782505          4506           
 2 D forward            change-mss              0               0              
 3 D forward            change-mss              0               0              
 4 D forward            change-mss              0               0              
 5 D forward            change-mss              129372          2031  
Or to print only dynamic rules use print dynamic
Code Block
languageros
[admin@mikrotik] /ip firewall mangle> print stats dynamic 
Flags: X - disabled, I - invalid, D - dynamic 
 #   CHAIN              ACTION                  BYTES           PACKETS        
 0 D forward            change-mss              0               0              
 1 D forward            change-mss              0               0              
 2 D forward            change-mss              0               0              
 3 D forward            change-mss              132444          2079 

Firewall NAT

Code Block
languageros
/ip firewall nat

Network Address Translation (NAT) 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 commonly used to make hosts on a private network to be accessible from the Internet. A NAT router performing dstnat replaces the destination IP address of an IP packet as it travels 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.

Masquerade

Firewall NAT action=masquarade is a 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, the router will clear all masqueraded connection tracking entries that send a 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 links when the 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 a 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 the 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 work around this by creating a blackhole route as an alternative to route that might disappear on disconnect).

When action=srcnat is used instead, connection tracking entries remain and connections can simply resume.

Properties

...

  • accept - accept the packet. Packet is not passed to the next NAT rule.
  • add-dst-to-address-list - add destination address to Address list specified by address-list parameter
  • add-src-to-address-list - add source address to Address list specified by address-list parameter
  • dst-nat - replaces destination address and/or port of an IP packet to values specified by to-addresses and to-ports parameters
  • jump - jump to the user defined chain specified by the value of jump-target parameter
  • log - add a message to the system log containing the following data: in-interface, out-interface, src-mac, protocol, src-ip:port->dst-ip:port and length of the packet. After a packet is matched it is passed to next rule in the list, similar as passthrough
  • masquerade - replaces source port of an IP packet to one specified by to-ports parameter and replace the source address of an IP packet to IP determined by routing facility. 
  • netmap - creates a static 1:1 mapping of one set of IP addresses to another one. Often used to distribute public IP addresses to hosts on private networks
  • passthrough - if packet is matched by the rule, increase counter and go to next rule (useful for statistics).
  • redirect - replaces destination port of an IP packet to one specified by to-ports parameter and destination address to one of the router's local addresses
  • return - passes control back to the chain from where the jump took place
  • same - gives a particular client the same source/destination IP address from a supplied range for each connection. This is most frequently used for services that expect the same client address for multiple connections from the same client
  • src-nat - replaces source address of an IP packet to values specified by to-addresses and to-ports parameters

...

  • Value of none-dynamic (00:00:00) will leave the address in the address list till reboot
  • Value of none-static will leave the address in the address list forever and will be included in configuration export/backup

...

  • unicast - IP address used for point to point transmission
  • local - if dst-address is assigned to one of the router's interfaces
  • broadcast - packet is sent to all devices in subnet
  • multicast - packet is forwarded to a defined group of devices

...

  • count - maximum average packet rate measured in packets per time interval
  • time - specifies the time interval in which the packet rate is measured (optional)
  • burst - number of packets which are not counted by packet rate
  • mode - the classifier for packet rate limiting
  • expire - specifies interval after which recorded IP address /port will be deleted (optional)

...

  • auth - matches authenticated HotSpot client packets
  • from-client - matches packets that are coming from the HotSpot client
  • http - matches HTTP requests sent to the HotSpot server
  • local-dst - matches packets that are destined to the HotSpot server
  • to-client - matches packets that are sent to the HotSpot client

...

  • in - valid in the PREROUTING, INPUT and FORWARD chains
  • out - valid in the POSTROUTING, OUTPUT and FORWARD chains
  • ipsec - matches if the packet is subject to IpSec processing;
  • none - matches packet that is not subject to IpSec processing (for example, IpSec transport packet).

For example, if a router receives an IPsec encapsulated Gre packet, then rule ipsec-policy=in,ipsec will match Gre packet, but rule ipsec-policy=in,none will match the 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-privileged destination port

...

Matches source address type:

  • unicast - IP address used for point to point transmission
  • local - if an address is assigned to one of the router's interfaces
  • broadcast - packet is sent to all devices in subnet
  • multicast - packet is forwarded to a defined group of devices

...

NAT stats

Code Block
languageros

/ip firewall nat print stats

Will show additional read-only properties

...

Firewall Mangle

Firewall Mangle marks packets for future processing in the device with special marks. Many other facilities in RouterOS make use of these marks, e.g. queue trees, NAT, routing. They identify a packet based on its mark and process it accordingly. The mangle marks exist only within the router, they are not transmitted across the network.

Additionally, the mangle facility is used to modify some fields in the IP header, like TOS (DSCP) and TTL fields.

Properties

...

  • accept - accept the packet. The packet is not passed to the next firewall rule.
  • add-dst-to-address-list - add destination address to address list specified by address-list parameter
  • add-src-to-address-list - add source address to address list specified by address-list parameter
  • change-dscp - change Differentiated Services Code Point (DSCP) field value specified by the new-dscp parameter
  • change-mss - change Maximum Segment Size field value of the packet to a value specified by the new-mss parameter
  • change-ttl - change Time to Live field value of the packet to a value specified by the new-ttl parameter
  • clear-df - clear 'Do Not Fragment' Flag
  • fasttrack-connection - shows Fasttrack counters, useful for statistics
  • jump - jump to the user defined chain specified by the value of jump-target parameter
  • log - add a message to the system log containing the following data: in-interface, out-interface, src-mac, protocol, src-ip:port->dst-ip:port and length of the packet. After a packet is matched it is passed to next rule in the list, similar as passthrough
  • mark-connection - place a mark specified by the new-connection-mark parameter on the entire connection that matches the rule
  • mark-packet - place a mark specified by the new-packet-mark parameter on a packet that matches the rule
  • mark-routing - place a mark specified by the new-routing-mark parameter on a packet. This kind of marks is used for policy routing purposes only
  • passthrough - if packet is matched by the rule, increase counter and go to next rule (useful for statistics).
  • return - pass control back to the chain from where the jump took place
  • route - forces packets to a specific gateway IP by ignoring normal routing decision (prerouting chain only)
  • set-priority - set priority specified by the new-priority parameter on the packets sent out through a link that is capable of transporting priority (VLAN or WMM-enabled wireless interface). 
  • sniff-pc - send a packet to a remote RouterOS CALEA server.
  • sniff-tzsp - send packet to a remote TZSP compatible system (such as Wireshark). Set remote target with sniff-target and sniff-target-port parameters (Wireshark recommends port 37008)
  • strip-ipv4-options - strip IPv4 option fields from IP header, action does not actually remove IPv4 options but rather replaces all option octets with NOP, further matcher with ipv4-options=any will still match the packet.

...

  • Value of none-dynamic (00:00:00) will leave the address in the address list till reboot
  • Value of none-static will leave the address in the address list forever and will be included in configuration export/backup

...

  • established - a packet which belongs to an existing connection
  • invalid - a packet that does not have determined state in connection tracking (usually - severe out-of-order packets, packets with wrong sequence/ack number, or in case of resource over usage on router), for this reason invalid packet will not participate in NAT (as only connection-state=new packets do), and will still contain original source IP address when routed. We strongly suggest to drop all connection-state=invalid packets in firewall filter forward and input chains
  • new - the packet has started a new connection, or otherwise associated with a connection which has not seen packets in both directions
  • related - a packet which is related to, but not part of an existing connection, such as ICMP errors or a packet which begins FTP data connection
  • untracked packet which was set to bypass connection tracking in Firewall RAW tables.

...

  • unicast - IP address used for point to point transmission
  • local - if dst-address is assigned to one of the router's interfaces
  • broadcast - packet is sent to all devices in subnet
  • multicast - packet is forwarded to a defined group of devices

...

  • count - maximum average packet rate measured in packets per time interval
  • time - specifies the time interval in which the packet rate is measured (optional)
  • burst - number of packets which are not counted by packet rate
  • mode - the classifier for packet rate limiting
  • expire - specifies interval after which recored ip address /port will be deleted (optional)

...

  • auth - matches authenticted HotSpot client packets
  • from-client - matches packets that are coming from the HotSpot client
  • http - matches HTTP requests sent to the HotSpot server
  • local-dst - matches packets that are destined to the HotSpot server
  • to-client - matches packets that are sent to the HotSpot client

...

  • in - valid in the PREROUTING, INPUT and FORWARD chains
  • out - valid in the POSTROUTING, OUTPUT and FORWARD chains
  • ipsec - matches if the packet is subject to IpSec processing;
  • none - matches packet that is not subject to IpSec processing (for example, IpSec transport packet).

For example, if a router receives an IPsec encapsulated Gre packet, then rule ipsec-policy=in,ipsec will match Gre packet, but rule ipsec-policy=in,none will match the 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-privileged destination port

...

Matches source address type:

  • unicast - IP address used for point to point transmission
  • local - if an address is assigned to one of the router's interfaces
  • broadcast - packet is sent to all devices in subnet
  • multicast - packet is forwarded to a defined group of devices

...

  • ack - acknowledging data
  • cwr - congestion window reduced
  • ece - ECN-echo flag (explicit congestion notification)
  • fin - close connection
  • psh - push function
  • rst - drop connection
  • syn - new connection
  • urg - urgent data

...

Stats

Code Block
languageros

/ip firewall filter print stats 

Will show additional read-only properties

...

[admin@dzeltenais_burkaans] /ip firewall mangle> print stats
Flags: X - disabled, I - invalid, D - dynamic 
 #   CHAIN              ACTION                  BYTES           PACKETS        
 0   prerouting         mark-routing            17478158        127631         
 1   prerouting         mark-routing            782505          4506           

To print also dynamic rules use print all.

[admin@dzeltenais_burkaans] /ip firewall mangle> print all stats
Flags: X - disabled, I - invalid, D - dynamic 
 #   CHAIN              ACTION                  BYTES           PACKETS        
 0   prerouting         mark-routing            17478158        127631         
 1   prerouting         mark-routing            782505          4506           
 2 D forward            change-mss              0               0              
 3 D forward            change-mss              0               0              
 4 D forward            change-mss              0               0              
 5 D forward            change-mss              129372          2031  

Or to print only dynamic rules use print dynamic

[admin@dzeltenais_burkaans] /ip firewall mangle> print stats dynamic 
Flags: X - disabled, I - invalid, D - dynamic 
 #   CHAIN              ACTION                  BYTES           PACKETS        
 0 D forward            change-mss              0               0              
 1 D forward            change-mss              0               0              
 2 D forward            change-mss              0               0              
 3 D forward            change-mss              132444          2079 

Menu specific commands

...

Firewall RAW

Code Block
languageros
/ip firewall raw

Firewall RAW table allows us to selectively bypass or drop packets before connection tracking that way significantly reducing load on CPU. The tool is very useful for DOS/DDOS attack mitigation.

The RAW table does not have matchers that depend on connection tracking ( like connection-state, layer7, etc.).
If a packet is marked to bypass connection tracking packet de-fragmentation will not occur.

Chains

There are two predefined chains in RAW tables:

  • prerouting - used to process any packet entering the router
  • output - used to process packets originated from the router and leaving it through one of the interfaces. Packets passing through the router are not processed against the rules of the output chain

Properties

...

  • accept - accept the packet. The packet is not passed to next firewall rule.
  • add-dst-to-address-list - add destination address to address list specified by address-list parameter
  • add-src-to-address-list - add source address to address list specified by address-list parameter
  • drop - silently drop the packet
  • jump - jump to the user defined chain specified by the value of jump-target parameter
  • log - add a message to the system log containing the following data: in-interface, out-interface, src-mac, protocol, src-ip:port->dst-ip:port and length of the packet. After a packet is matched it is passed to next rule in the list, similar as passthrough
  • notrack - do not send packet to connection tracking.
  • passthrough - ignore this rule and go to the next one (useful for statistics).
  • return - passes control back to the chain from where the jump took place

...

  • Value of none-dynamic (00:00:00) will leave the address in the address list till reboot
  • Value of none-static will leave the address in the address list forever and will be included in configuration export/backup

...

  • unicast - IP address used for point to point transmission
  • local - if dst-address is assigned to one of the router's interfaces
  • broadcast - packet is sent to all devices in subnet
  • multicast - packet is forwarded to a defined group of devices

...

  • count - packet count per time interval per flow to match
  • time - specifies the time interval in which the packet count per flow cannot be exceeded (optional, 1s will be used if not specified)
  • burst - initial number of packets per flow to match: this number gets recharged by one every time/count, up to this number
  • mode - this parameter specifies what unique fields define flow (src-address, dst-address, src-and-dst-address, dst-address-and-port, addresses-and-dst-port)
  • expire - specifies interval after which flow with no packets will be allowed to be deleted (optional)

...

  • in - valid in the PREROUTING chain
  • out - valid in the OUTPUT chain
  • ipsec - matches if the packet is subject to IPsec processing;
  • none - matches packet that is not subject to IPsec processing (for example, IpSec transport packet).

For example, if a 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 - packet or bit count per time interval to match
  • time - specifies the time interval in which the packet or bit count cannot be exceeded (optional, 1s will be used if not specified)
  • burst - initial number of packets or bits to match: this number gets recharged every 10ms so burst should be at least 1/100 of rate per second
  • mode - packet or bit mode

...

  • 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-privileged destination port

...

Matches source address type:

  • unicast - IP address used for point to point transmission
  • local - if an address is assigned to one of the router's interfaces
  • broadcast - packet is sent to all devices in subnet
  • multicast - packet is forwarded to a defined group of devices

...

  • ack - acknowledging data
  • cwr - congestion window reduced
  • ece - ECN-echo flag (explicit congestion notification)
  • fin - close connection
  • psh - push function
  • rst - drop connection
  • syn - new connection
  • urg - urgent data

...

Service Ports

Code Block
languageros
/ip firewall service-port

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.

To overcome these limitations RouterOS includes a number of NAT helpers, that enable NAT traversal for various protocols.

Properties

Note that it is not possible to add new services, only existing service modifications are allowed.

...

Connections

Code Block
languageros
/ip firewall connection tracking

There are several ways to see what connections are making their way through the router.

Image Removed

Properties

All properties in connection list are read-only

...

  • "established"
  • "time-wait"
  • "close"
  • "syn-sent"
  • "syn-received"

...

Connection tracking settings

Code Block
languageros
/ip firewall connection tracking

Properties

...

MikroTik RouterOS has a very powerful firewall implementation with features including:


  • stateful packet inspection
  • peer-to-peer protocols filtering
  • traffic classification by:
    • source MAC address
    • IP addresses (network or list) and address types (broadcast, local, multicast, unicast)
    • port or port range
    • IP protocols
    • protocol options (ICMP type and code fields, TCP flags, IP options, and MSS)
    • interface the packet arrived from or left through
    • internal flow and connection marks
    • DSCP byte
    • packet content
    • rate at which packets arrive and sequence numbers
    • packet size
    • packet arrival time

And much more!

How It works

The firewall operates by means of firewall rules. Each rule consists of two parts - the matcher which matches traffic flow against given conditions and the action which defines what to do with the matched packet.

RouterOS utilizes 5 sub-facilities of the firewall:

  • Connection tracking
  • Filters
  • NAT
  • Mangle
  • RAW

Connection states

To completely understand firewall rules, first, you have to understand various states which might apply to a particular network packet. There are five connection states in RouterOS:

  • NEW - The NEW state tells us that the packet is the first packet that we see. This means that the first packet that the conntrack module sees, within a specific connection, will be matched. For example, if we see a SYN packet and it is the first packet in a connection that we see, it will match;
  • ESTABLISHED - The ESTABLISHED state has seen traffic in both directions and will then continuously match those packets. ESTABLISHED connections are fairly easy to understand. The only requirement to get into an ESTABLISHED state is that one host sends a packet and that it, later on, gets a reply from the other host. The NEW state will upon receipt of the reply packet to or through the firewall change to the ESTABLISHED state;
  • RELATED - A connection is considered RELATED when it is related to another already ESTABLISHED connection. For a connection to be considered as RELATED, we must first have a connection that is considered ESTABLISHED. The ESTABLISHED connection will then spawn a connection outside of the main connection. The newly spawned connection will then be considered RELATED, for example, a packet that begins the FTP data connection;
  • INVALID - The INVALID state means that the packet can't be identified or that it does not have any state.  It is suggested to DROP everything in this state;
  • UNTRACKED - A packet that was set to bypass connection tracking in the Firewall RAW table;


Configuration Example

Let's look at the basic firewall setup to protect the router. By default RouterOS firewall accepts everything, blocking is achieved by adding a filter rule to drop everything at the end of all rules. For our router we want to allow only ICMP, ssh, and Winbox and drop the rest:

Code Block
languageros
/ip firewall filter
add chain=input connection-state=invalid action=drop comment="Drop Invalid connections"
add chain=input connection-state=established,related,untracked action=accept comment="Allow Established/Related/Untracked connections"
add chain=input protocol=icmp action=accept comment="Allow ICMP"
add chain=input protocol=tcp ports=8291,22 action=accept comment="Allow Winbox and SSH"
add chain=input action=drop comment="Drop everything else"

RouterOS also allows filtering packets before connection tracking and selectively sends only specific traffic to connection tracking. This allows us to significantly reduce the load on the CPU and mitigate DOS/DDoS attacks. Configuration of such rules is done in the RAW filtering table.

Additional /ip firewall filter configuration examples are found under the Building Your First Firewall section.

Connection Tracking

Connection tracking allows the kernel to keep track of all logical network connections or sessions, and thereby relate all of the packets which may make up that connection. NAT relies on this information to translate all related packets in the same way. Because of connection tracking, you can use stateful firewall functionality even with stateless protocols such as UDP.

A list of tracked connections can be seen in the /ip firewall connection for ipv4 and /ipv6 firewall connection for IPv6.

Code Block
languageros
[admin@MirkoTik] /ip firewall connection> print
Flags: S - seen-reply, A - assured
# PR.. SRC-ADDRESS DST-ADDRESS TCP-STATE TIMEOUT
0 udp 10.5.8.176:5678 255.255.255.255:5678 0s
1 udp 10.5.101.3:646 224.0.0.2:646 5s
2 ospf 10.5.101.161 224.0.0.5 9m58s
3 udp 10.5.8.140:5678 255.255.255.255:5678 8s
4 SA tcp 10.5.101.147:48984 10.5.101.1:8291 established 4m59s

[admin@MirkoTik] /ipv6 firewall connection> print
Flags: S - seen reply, A - assured
# PRO.. SRC-ADDRESS DST-ADDRESS TCP-STATE
0 udp fe80::d6ca:6dff:fe77:3698 ff02::1
1 udp fe80::d6ca:6dff:fe98:7c28 ff02::1
2 ospf fe80::d6ca:6dff:fe73:9822 ff02::5


Based on connection table entries arrived packet can get assigned one of the connection states: new, invalid, established, related, or untracked.

There are two different methods when the packet is considered new. The first one is in the case of stateless connections (like UDP) when there is no connection entry in the connection table. The other one is in the case of a stateful protocol (TCP). In this case, a new packet that starts a new connection is always a TCP packet with an SYN flag.

If a packet is not new it can belong to either an established or related connection or not belong to any connection making it invalid. A packet with an established state, as most of you already guessed, belongs to an existing connection from the connection tracking table. A related state is very similar, except that the packet belongs to a connection that is related to one of the existing connections, for example, ICMP error packets or FTP data connection packets.

Connection state notrack is a special case when RAW firewall rules are used to exclude connection from connection tracking. This one rule would make all forwarded traffic bypass the connection tracking engine speeding packet processing through the device.

Any other packet is considered invalid and in most cases should be dropped.

Based on this information we can set a basic set of filter rules to speed up packet filtering and reduce the load on the CPU by accepting established/related packets, dropping invalid packets, and working on more detailed filtering only for new packets.

Code Block
languageros
ip firewall filter
add chain=input connection-state=invalid action=drop comment="Drop Invalid connections"
add chain=input connection-state=established,related,untracked action=accept comment="Allow Established/Related/Untracked connections


Note

Such a rule set must not be applied on routers with asymmetric routing, because asymmetrically routed packets may be considered invalid and dropped.

FastTrack

IPv4 FastTrack handler is automatically used for marked connections. Use firewall action "fasttrack-connection" to mark connections for FastTrack. Currently, only TCP and UDP connections can be actually FastTracked (even though any connection can be marked for FastTrack). IPv4 FastTrack handler supports NAT (SNAT, DNAT, or both).

Note that not all packets in a connection can be FastTracked, so it is likely to see some packets going through a slow path even though the connection is marked for FastTrack. This is the reason why fasttrack-connection is usually followed by an identical "action=accept" rule. FastTrack packets bypass firewall, connection tracking, simple queues, queue tree with parent=global, IP accounting, IPSec, hotspot universal client, and VRF assignment, so it is up to the administrator to make sure FastTrack does not interfere with other configuration.

Requirements

IPv4 FastTrack is active if the following conditions are met:

  • no mesh, metarouter interface configuration;
  • sniffer, torch, or traffic generator is not running;
  • /tool mac-scan is not actively used;
  • /tool ip-scan is not actively used;
  • FastPath and Route cache is enabled under IP/Settings

Example

For example, for SOHO routers with factory default configuration, you could FastTrack all LAN traffic with this one rule placed at the top of the Firewall Filter. The same configuration accept rule is required:

Code Block
languageros
/ip firewall filter add chain=forward action=fasttrack-connection connection-state=established,related
/ip firewall filter add chain=forward action=accept connection-state=established,related


Tip
  • Connection is FastTracked until the connection is closed, timed-out, or router is rebooted.
  • Dummy rules will disappear only after FastTrack firewall rules will be deleted/disabled and the router rebooted.
  • While FastPath and FastTrack both are enabled on the device only one can be active at a time.


Note

Queues (except Queue Trees parented to interfaces), firewall filter, and mangle rules will not be applied for FastTracked traffic.

Services

This section lists protocols and ports used by various MikroTik RouterOS services. It helps you to determine why your MikroTik router listens to certain ports, and what you need to block/allow in case you want to prevent or grant access to certain services.

The default services are:

PropertyDescription
telnetTelnet service
ftpFTP service
wwwWebfig HTTP service
sshSSH service
www-sslWebfig HTTPS service
apiAPI service
winboxResponsible for Winbox tool access, as well as Tik-App smartphone app and Dude probe
api-sslAPI over SSL service

Properties

Note that it is not possible to add new services, only existing service modifications are allowed.

PropertyDescription
address (IP address/netmask | IPv6/0..128; Default: )List of IP/IPv6 prefixes from which the service is accessible.
certificate (name; default: none)The name of the certificate used by a particular service. Applicable only for services that depend on certificates (www-ssl, api-ssl)
name (name; default: none)Service name
port (integer: 1..65535; Default: )The port particular service listens on

To restrict Winbox service access to the device only from the 192.168.88.0/24 subnet, we have to configure the following:

Code Block
languageros
[admin@MikroTik] > ip service set [find name~"winbox"] address=192.168.88.0/24
[admin@MikroTik] > ip service print 
Flags: X - disabled, I - invalid 
# NAME PORT ADDRESS CERTIFICATE 
0 telnet 23
1 XI ftp 21
2 XI www 80
3 ssh 22
4 XI www-ssl 443 none 
5 XI api 8728
6 winbox 8291 192.168.88.0/24 
7 XI api-ssl 8729 none


Tip

We recommend disabling unused services.

Address List

...

Features affected by connection tracking

  • Firewall NAT
  • Firewall:
    • connection-bytes
    • connection-mark
    • connection-type
    • connection-state
    • connection-limit
    • connection-rate
    • layer7-protocol
    • new-connection-mark
    • tarpit

Address List

Code Block
languageros
/ip firewall address-list

Firewall address lists allow a user to create lists of IP addresses grouped together under a common name. Firewall filter, Mangle, and NAT facilities can then use those address lists to match packets against them. The address list records can also be updated dynamically via the action=add-src-to-address-list list or action=add-dst-to-address-list items found in NAT, Mangle, and Filter facilities.
Firewall rules with action add-src-to-address-list or add-dst-to-address-list works work in passthrough mode, which means that the matched packets will be passed to the next firewall rules.

Properties

...

A basic example of a dynamically created address-list:

Code Block
languageros
[admin@MirkoTik] > ip firewall address-list add address=www.mikrotik.com list=MikroTik
[admin@MirkoTik] > ip firewall address-list print
Flags: X - disabled, D - dynamic
# LIST ADDRESS CREATION-TIME TIMEOUT
0 MikroTik www.mikrotik.com oct/09/2019 14:53:14
1 D ;;; www.mikrotik.com
MikroTik 159.148.147.196 oct/09/2019 14:53:14

Layer7-protocol

Layer7-protocol is a method of searching for patterns in ICMP/TCP/UDP streams. It collects the first 10 packets of a connection or the first 2KB of a connection and searches for the pattern in the collected data. If the pattern is not found in the collected data, the matcher stops inspecting further. Allocated memory is freed and the protocol is considered unknown. You should take into account that a lot of connections will significantly increase memory and CPU usage. To avoid this, add regular firewall matches to reduce the amount of data passed to layer-7 filters repeatedly.

An additional requirement is that the

Note

If the timeout parameter is not specified, then the address will be saved to the list permanently to the disk. If a timeout is specified, the address will be stored on the RAM and will be removed after a system's reboot.

Layer7-protocol

Code Block
languageros
/ip firewall layer7-protocol

Layer7-protocol is a method of searching for patterns in ICMP/TCP/UDP streams. An additional requirement is that layer7 matcher must see both directions of traffic (incoming and outgoing). To satisfy this requirement l7 rules should be set in the the forward chain. If a rule is set in the input/prerouting chain then the same rule must be also set in the output/postrouting chain, otherwise, the collected data may not be complete resulting in an incorrectly matched pattern. Layer 7 matcher is case insensitive 

In some cases when layer 7 regular expression cannot be performed, RouterOS will log topic=firewall, warning with an error message stating the problem in the message

Note

The L7 matcher is very resource intensive. Use this feature only for very specific traffic. It is not recommended to use a Layer7 matcher for generic traffic, such as for blocking webpages. This will almost never work correctly and your device will exhaust it's resources, trying to catch all the traffic. Use other features to block webpages by URL

Properties

...

incorrectly matched pattern.

In this example, we will use a pattern to match RDP packets.

Code Block
languageros
/ip firewall layer7-protocol add name=rdp regexp="rdpdr.*cliprdr.*rdpsnd"


Tip

If the Layer7 matcher recognizes the connection, then the rule marks this connection as its "own" and other rules do not look at this connection anymore even if the two firewall rules with Layer7 matcher are identical.


Warning

When a user uses HTTPS, Layer7 rules will not be able to match this traffic. Only unencrypted HTTP can be matched

...

.