0% found this document useful (0 votes)
183 views525 pages

MikroTik RouterOS MTCTCSE

Uploaded by

darthrebel1999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
183 views525 pages

MikroTik RouterOS MTCTCSE

Uploaded by

darthrebel1999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 525

MikroTik Certified Security Engineer

and Traffic Control Engineer

Quick Access
Internet is available
SSID: Internet
Password: Internet

The manual can be downloaded from the MikroTikSA Training Site


https://training.mikrotiksa.co.za
Log in with your account and access the Training Manual resource under the MTCTCSE course 1
Housekeeping and Schedule
• Course materials
• Routers, cables
• Restrooms and smoking area locations
• 08:00 – 10:00 Morning Session I
• 10:00 – 10:20 Morning Break
• 10:20 – 12:00 Morning Session II
• 12:00 – 12:40 Lunch Break
• 12:40 – 14:00 Afternoon Session I
• 14:00 – 14:20 Afternoon Break
• 14:20 – 16:00 Afternoon Session II / Examination
• Crowthorne Gate Codes
àIN 5772# ßOUT 7878#
2
About MikroTik SA
• Independent Network Specialist company
• Not owned by / affiliated to MikroTik Latvia
• Official training and support partner for MikroTik
• Specialist in all forms of wireless and wired networking technologies
• Offers high speed PTP links, carrier independent backbone services,
high availability SLA's
• David Savage
• Is a MikroTik Certified Trainer and consultant
• Installs and manages all sizes of network
• Has over 21 years experience in the IT field
• Teaches general networking and MikroTik RouterOS
3
Introduce Yourself
• Please, introduce yourself to the class
• Your name
• Your Company
• Your previous knowledge about RouterOS
• Your previous knowledge about networking
• What do you expect from this course?

• Please, remember your class seat S number as per the next slide.
• You will also be assigned a group number G – this is the lower
number of the team

4
Numbering layout

20 21 22 23 24 25 26 27
20 22 24 26

10 11 12 13 14 15 16 17
10 12 14 16

5
In This Manual

• The LAB pages are practical exercises that


can be practised in class. Try them out now
and learn from your mistakes!

• TIPs indicate particularly important points


(with a good possibility of an exam
question). Note these well.

6
Exams and Certificate
• This course is about understanding RouterOS, the exam should be a secondary
concern
• The exam will be written on the afternoon of the last course day
• You must have an account on mikrotik.com and be enrolled in the training course
– If you do not please register during the course on http://www.mikrotik.com and ensure that the
trainer enrols you on the course
• You must pass the exam to obtain your certificate
– The passmark is 60%
– If you achieve between 50%-59% you may request to attempt the exam immediately again (1
rewrite per delegate)
• Certificates are issued online automatically and will be viewable in your account
• All delegates receive a complimentary CHR P1 MikroTik license which will be
available in your account after the course
7
Class Network
X – a unique number
given by the teacher.
Use it to avoid IP address
conflicts DHCP Enabled
DNS:10.1.1.254
Gateway:10.1.1.254

192.168.X.1/24

ether2 IP:192.168.X.254/24
ether1 IP:10.1.1.X/24

Free internet access is provided on


DHCP Band: 2.4 / 5 GHz a “responsible use” basis. Please
Access SSID: Internet
Point Pass: Internet don’t abuse it i.e. no massive movie
downloads, torrents etc. 8
Introduction

What is Security
Attacks, Mechanisms, Services
What is Security
• Security is about protection of assets.
– D. Gollmann, Computer Security, Wiley
• Confidentiality : Protecting personal privacy and proprietary
information.
• Integrity : Ensuring information non-repudiation and authenticity.
• Availability : Ensuring timely and reliable access to and use of
information

10
What is Security
• Prevention : take measures that prevent your assets from being
damaged (or stolen)
• Detection : take measures so that you can detect when, how, and by
whom an asset has been damaged
• Reaction : take measures so that you can recover your assets

11
Attacks, Mechanisms, Services
• Security Attack : Any action that compromises the security of
information
• Security Mechanism : a process / device that is designed to detect,
prevent or recover from a security attack.
• Security Service : a service intended to counter security attacks,
typically by implementing one or more mechanisms.

12
Security Threats and Attacks

NORMAL FLOW

Information Information
source destination

13
Security Threats and Attacks

INTERRUPTION

Information Information
source destination

“services or data become unavailable, unusable, destroyed, and so on, such as loss of
file, denial of service, etc.”

14
Security Threats and Attacks
INTERCEPTION

Information Information
source destination

Attacker

“an unauthorized 3rd party has gained access to an object, such as stealing data,
overhearing another's communication, etc.”

15
Security Threats and Attacks
MODIFICATION

Information Information
source destination

Attacker

unauthorized changing of data or tampering with services, such as alteration of data,


modification of messages, etc.

16
Security Threats and Attacks
FABRICATION

Information Information
source destination

Attacker

“additional data or activities are generated that would normally not exist, such as
adding a password to a system, replaying previously sent messages, etc.”

17
Threat and Attack Types

Interruption

Active Attacks / Threats Modification

Attack / Threats Fabrication

Passive Attacks /
Interception
Threats

18
Security Mechanisms
• Encryption : transforming data into something an attacker cannot
understand, i.e., providing a means to implement confidentiality, as
well as allowing the user to check whether data has been modified.
• Authentication : verifying the claimed identity of a user, such as user
name, password, etc.
• Authorization : checking whether the user has the right to perform
the action requested.
• Auditing : tracing which users accessed what, when, and which way.
In general, auditing does not provide protection, but can be a tool
for analysis of problems.

19
Common Threats
Botnet
“Collection of software robots, or 'bots', that creates an army of infected
computers (known as ‘zombies') that are remotely controlled by the
originator”

• What it can do :
• Send spam emails with viruses attached.
• Spread all types of malware.
• Can use your computer as part of a denial of service attack against
other systems.

21
DDoS
“A distributed denial-of-service (DDoS) attack — or DDoS attack — is when
a malicious user gets a network of zombie computers to sabotage a specific
website or server.”

• What it can do :
• The most common and obvious type of DDoS attack occurs when an
attacker “floods” a network with useless information.
• The flood of incoming messages to the target system essentially
forces it to shut down, thereby denying access to legitimate users.

22
Hacking
“Hacking is a term used to describe actions taken by someone to gain
unauthorised access to a computer.”

• What it can do :
• Find weaknesses (or pre-existing bugs) in your security settings and
exploit them in order to access your devices.
• Install a Trojan horse, providing a back door for hackers to enter and
search for your information.

23
Malware
“Malware is one of the more common ways to infiltrate or damage your computer, it’s software
that infects your computer, such as computer viruses, worms, Trojan horses, spyware, and adware.”

• What it can do :
• Intimidate you with scareware, which is usually a pop-up
message that tells you your computer has a security problem or other false information.
• Reformat the hard drive of your computer causing you to lose all your information.
• Alter or delete files.
• Steal sensitive information.
• Send emails on your behalf.
• Take control of your computer and all the software running on it.

24
Phishing
“Phishing is used most often by cyber criminals because it's easy to execute and
can produce the results they're looking for with very little effort.”

• What it can do :
• Trick you into giving them information by asking you to update, validate
or confirm your account. It is often presented in a manner than seems
official and intimidating, to encourage you to take action.
• Provides cyber criminals with your username and passwords so that they
can access your accounts (your online bank account, shopping accounts,
etc.) and steal your credit card numbers.
25
Ransomware
“Ransomware is a type of malware that restricts access to your computer
or your files and displays a message that demands payment in order for the
restriction to be removed.”

• What it can do :
• Lockscreen ransomware: displays an image that prevents you from
accessing your computer.
• Encryption ransomware: encrypts files on your system's hard drive
and sometimes on shared network drives, USB drives, external hard
drives, and even some cloud storage drives, preventing you from
opening them.
26
Spam
“Spam is one of the more common methods of both sending information out
and collecting it from unsuspecting people.”

• What it can do :
• Annoy you with unwanted junk mail.
• Create a burden for communications service providers and businesses to
filter electronic messages.
• Phish for your information by tricking you into following links or entering
details with too-good-to-be-true offers and promotions.
• Provide a vehicle for malware, scams, fraud and threats to your privacy.
27
Spoofing
“This technique is often used in conjunction with phishing in an attempt to
steal your information.”

• What it can do :
• Sends spam using your email address, or a variation of your email
address, to your contact list.
• Recreates websites that closely resemble the authentic site. This
could be a financial institution or other site that requires login or
other personal information.

28
Spyware and Adware
“This technique is often used by third parties to infiltrate your computer or steal
your information without you knowing it.”

• What it can do :
• Collect information about you without you knowing about it and give it
to third parties.
• Send your usernames, passwords, surfing habits, list of applications
you've downloaded, settings, and even the version of your operating
system to third parties.
• Change the way your computer runs without your knowledge.
• Take you to unwanted sites or inundate you with uncontrollable pop-up
ads.
29
Trojan Horse
“A malicious program that is disguised as, or embedded within, legitimate
software. It is an executable file that will install itself and run automatically once it's
downloaded.”

• What it can do :
• Delete your files.
• Use your computer to hack other computers.
• Watch you through your web cam.
• Log your keystrokes (such as a credit card number you entered in an
online purchase).
• Record usernames, passwords and other personal information.
30
Virus
“Malicious computer programs that are often sent as an email
attachment or a download with the intent of infecting your computer.”

• What it can do :
• Send spam.
• Provide criminals with access to your computer and contact lists.
• Scan and find personal information like passwords on your computer.
• Hijack your web browser.
• Disable your security settings.
• Display unwanted ads.
31
Worm
“A worm, unlike a virus, goes to work on its own without
attaching itself to files or programs. It lives in your computer memory,
doesn't damage or alter the hard drive and propagates by sending
itself to other computers in a network.”

• What it can do :
• Spread to everyone in your contact list.
• Cause a tremendous amount of damage by shutting down parts of
the Internet, wreaking havoc on an internal network and costing
companies enormous amounts of lost revenue.

32
RouterOS Default Configuration
• All RouterBOARDs from factory come with a default configuration. There
are several different configurations depending on the board type:
– CPE router
– LTE CPE AP router
– AP router (single or dual band)
– PTP Bridge (AP or CPE)
– WISP Bridge (AP in ap_bridge mode)
– Switch
– IP only
– CAP (Controlled Access Point)
• When should you remove the default-configuration and set up the router
from scratch?

33
Router Setup

• Check your current default setup


• Note settings in the following locations
– IP à Address
– IP à DHCP Client
– IP à Routes
– IP à DHCP Server
– IP à Neighbours à Discovery
– Interface à Interface List
– IP à Firewall Filter and NAT
34
CPE Router
• In this type of configurations router is configured as wireless client
device.
• WAN interface is Wireless interface.
• WAN port has configured DHCP client, is protected by IP firewall and
MAC discovery/connection is disabled.

35
CPE Router
• List of routers using this type of configuration:
– RB711, 911, 912, 921, 922 - with Level3 (CPE) license
– SXT
– QRT
– SEXTANT
– LHG
– LDF
– DISC
– Groove
– Metal

36
LTE CPE AP Router
• This configuration type is applied to routers that have both an LTE
and a wireless interface.
• The LTE interface is considered as a WAN port protected by the
firewall and MAC discovery/connection disabled.
• IP address on the WAN port is acquired automatically. Wireless is
configured as an access point and bridged with all available Ethernet
ports.
• List of routers using this type of configuration:
– wAP LTE kit
– LtAP mini kit

37
Home AP Router
• This type of configuration is applied to home access point routers to be
used straight out of the box without additional configuration (except
router and wireless passwords)
• First Ethernet port is configured as a WAN port (protected by firewall,
with a DHCP client and disabled MAC connection/discovery)
• Other Ethernet ports and wireless interfaces are added to local LAN
bridge with an IP 192.168.88.1/24 and a DHCP server
• In case of dual band routers, one wireless is configured as 5 GHz access
point and the other as 2.4 GHz access point.
• List of routers using this type of configuration:
– RB: 450, 751, 850, 951, 953, 2011, 3011, 4011
– mAP, wAP, hAP, OmniTIK

38
PTP Bridge (AP / CPE)
• Bridged ethernet with wireless interface
• Default IP address 192.168.88.1/24 is set on the bridge interface
• There are two possible options - as CPE and as AP
– For CPE wireless interface is set in "station-bridge" mode.
– For AP "bridge" mode is used.
• List of routers using this type of configuration:
– DynaDish - as CPE

39
WISP Bridge
• Configuration is the same as PTP Bridge in AP mode, except that wireless
mode is set to ap_bridge for PTMP setups.
• Router can be accessed directly using MAC address.
• If device is connected to the network with enabled DHCP server,
configured DHCP client configured on the bridge interface will get the IP
address, that can be used to access the router.
• List of routers using this type of configuration:
– RB 911,912,921,922 - with Level4 license
– cAP, Groove A, Metal A, RB711 A
– BaseBox, NetBox
– mANTBox, NetMetal

40
Switch
• This configuration takes advantage of the switch chip features to
configure the switch.
• All ethernet ports are added to switch group and default IP address
192.168.88.1/24 is set on master port.
• From RouterOS v6.41 and onwards uses Hardware Offload and adds
all ports into a bridge instead.
• List of routers using this type of configuration:
– FiberBox
– CRS without wireless interface

41
IP Only
• When no specific configuration is found, IP address 192.168.88.1/24
is set on ether1, or combo1, or sfp1.
• List of routers using this type of configuration:
– RB 411,433,435,493,800,M11,M33,1100
– CCRxxx

42
CAP
• This type of configuration is used when device is to be used as a
wireless access point which is controlled by the CAPsMAN
• When CAP default configuration is loaded, ether1 is considered as a
management port with a DHCP client
• All other Ethernet interfaces are bridged and all wireless interfaces
are set to be managed by the CAPsMAN
• None of the current boards come with the CAP mode enabled from
the factory
• The above mentioned configuration is applied to all boards with at
least one wireless interfaces when set to the CAP mode

43
IPv6
• Note. The IPv6 package by default is disabled on RouterOS v6
– In V7 it is included in the base package
• If the router configuration is reset with default-configuration=yes
and the IPv6 package is enabled then the default configuration will
be applied to the IPv6 firewall as well.

44
View Factory Default Conf
/system default-configuration print
• Shows the standard default configuration setup for the router

45
Default IP Firewall - INPUT
• Process only new connections to decrease load on a router
• Drop invalid connections
• Enable ICMP access
• Drop everything else not from local LAN
• LAN is set by Interface List and is all interfaces bridged together that
is not the WAN port
– WAN port is default ether1 and any LTE interface

46
Input Chain
add chain=input action=accept connection-
state=established,related,untracked comment="defconf: accept
established,related,untracked"
add chain=input action=drop connection-state=invalid
comment="defconf: drop invalid"
add chain=input action=accept protocol=icmp comment="defconf: accept
ICMP"
add chain=input action=accept dst-address=127.0.0.1 comment="defconf:
accept to local loopback (for CAPsMAN)"
add chain=input action=drop in-interface-list=!LAN comment="defconf:
drop all not coming from LAN"

47
IP Firewall for Client Chain
• Accept IPSEC in and out
• Established/related packets are added to fasttrack** for faster data
throughput
• firewall will process only new connection state packets
• Drop invalid connections
• Drop all incoming connections that are not DSTNATed

** note Fasttrack limitations for Queues and other facilities

48
Forward Chain
add chain=forward action=accept ipsec-policy=in,ipsec
comment="defconf: accept in ipsec policy"
add chain=forward action=accept ipsec-policy=out,ipsec
comment="defconf: accept out ipsec policy"
add chain=forward action=fasttrack-connection connection-
state=established,related comment="defconf: fasttrack"
add chain=forward action=accept connection-
state=established,related,untracked comment="defconf: accept
established,related, untracked"
add chain=forward action=drop connection-state=invalid
comment="defconf: drop invalid"
add chain=forward action=drop connection-state=new connection-nat-
state=!dstnat in-interface-list=WAN comment="defconf: drop all from
WAN not DSTNATed"
49
Router Setup
• Reset your router from the Terminal using
/system reset no-defaults=yes
• Click on Files and delete all backup and other files
• Get your router connected to the training router and the internet.
• Use the IP addresses as specified in the class setup
• 10.1.1.x/24 on ether 1, 192.168.x.254/24 on ether 2
• Use the training router 10.1.1.254 as the DNS server and Default
Gateway
• Make sure your laptop can access the Internet via your router

50
Router Setup II
• Set the system identity to XY_your_name
• E.g. 00_Big_Dave
• In Tools à RoMON enable the romon service with no password
• Upgrade your router to the latest MikroTik RouterOS version from System à
Packages
• Lab check – everyone visible in RoMON?
• Check KALI login account – trainer to confirm details
– User: student1
– Pass: P@ssword123
– SSH to 10.1.1.200
• Remember – with great power comes great responsibility - DBAD

51
Router Setup III
• Reset shared router with no default config
• Configure ether1 as the WAN port on IP 10.1.1.1x (confirm with trainer)
• Add a bridge called LAN_Bridge
• Add ports 2-5 to LAN_Bridge
• In Tools à RoMON enable the romon service with no password
• Upgrade your router to the latest MikroTik RouterOS version from System à
Packages
• Set the System Identity to X_Group-name

52
Hardening the Router
• Before installing the firewall we should ensure that some default
settings are changed
– The default router user is “admin” with no password and full access
capabilities
Access via System à Users
– Most IP Services are enabled by default
Check in IP à Services
– NTP Client is not setup – therefore we won't have accurate logging of
events
Check System à SNTP Client
53
Protecting the Router
• IP à Services controls which services run on the router
• New exploits are a constant threat
• Turn off un-needed services and protect needed services
from outside probe / attack
• Add edge firewall rules to prevent un-authorised ingress of
common attack protocols: SSH, DNS, Winbox, NTP, FTP,
Telnet etc. Service Encryption

• IP Services api No
api-ssl Yes
– Allow SSH but on a different port
ftp No
– Allow Winbox only from your internal network and selected ssh Yes
external addresses telnet No
– Block all other services winbox Yes
www No
www-ssl Yes 54
Other Client Services
/ip proxy set enabled=no
/ip socks set enabled=no
/ip upnp set enabled=no
/ip cloud set ddns-enabled=no update-time=no

• In addition to disabling client services, it is considered good practice


to disable all unused interfaces on the router until they are
specifically required

55
More Secure SSH
• Introduces following changes in the SSH configuration:
– Prefer 256 and 192 bit encryption instead of 128 bits
– Disable null encryption (must be done first)
– Prefer sha256 for hashing instead of sha1
– Disable md5
– Use 2048bit prime for Diffie Hellman exchange instead of 1024bit

• /ip ssh set allow-none-crypto=no


• /ip ssh set strong-crypto=yes
56
SSH Keys
• More secure than login name/password
• Public key is installed on router, private key kept by user
• No user/pass required, therefore no possibility for brute force
attacks
• Can be created using puttygen or other free utilities -
https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html

57
PuttyGen

58
SSH Keys
• Download the Putty suite and install
• Use Puttygen to create a public/private RSA key
• TIP: Do not use the Putty export function, rather copy and paste the
key into a text file
• Save to your laptop
• Add the public key to your router
– The public key is tied to a specific User account
– You can install a different key per User
• Attempt to SSH to the router using Putty with your private key
– In Putty this is specified in Connection à SSH à Auth
59
VRF
• Virtual routing and forwarding (VRF) is a technology included in IP
network routers that allows multiple instances of a routing table to
exist in a router and work simultaneously
• This increases functionality by allowing network paths to be
segmented without using multiple devices
• Traffic is automatically segregated, meaning VRF also increases
network security and can eliminate the need for encryption and
authentication
• ISPs often take advantage of VRF to create separate virtual private
networks (VPNs) for customers; thus the technology is also referred
to as VPN routing and forwarding.
60
VRF and Router Management
• By default router management is not possible from vrf side (winbox, ssh ...)
• RouterOS v7 allows you to specify a VRF for IP services
– Meaning management for that service is only possible from the VRF

61
VRF for Services
• When the interface is assigned to the VRF as well as connected routes it does
not mean that RouterOS services will automatically know which VRF to use just
by specifying the IP address in the configuration
• Each service needs VRF support to be added and explicit configuration
• Whether the service has VRF support and has VRF configuration options refer
to appropriate service documentation

62
Management VRF
• IP à Services can be used to attach any login service to a VRF
• VRF can be joined to physical interface, VLAN, EOIP tunnel, even PPP dial-in
• RouterOS management is then only available from the VRF

No access via
internal networks

63
L2TP and VLAN Management
• We can allow access to the device via a
dedicated L2TP dial-in
• Setup L2TP server as per standard
method
• Add PPP à Secrets user or setup via
RADIUS
• Add L2TP Server Binding to create an
interface to attach to the VRF
– The Binding user must match the dial-in
user exactly
64
PPPoE/PPTP/L2TP/SSTP Server Setup
• To quickly setup a L2TP server you can use the Default Encryption profile and a
PPP Secret to assign Local and Remote addresses

Local address Add support for


will define the IPSEC in the
management IP L2TP Server
used to access setting in PPP
the service in à L2TP Server
the VRF

Copyright 2016 MikroTikSA (Pty) Ltd 65


PPP Lab
• Add a PPP Secret on your LAN router specifying a local
(management) address and a remote (client) address
• Enable the L2TP Server
– Allow IPSEC and set and IPSEC Secret
• Create a dial-in connection from your laptop to connect to the
router
• Confirm normal operation
• Create a L2TP binding for your dial-in account by copying the
existing Dynamic session
Copyright 2016 MikroTikSA (Pty) Ltd 66
VRF Setup
• In IP à VRF add a new VRF along
with the interfaces that the device
needs to be managed from
• In IP à Services modify the VRF as
required

67
VRF Lab
• In IP à VRF create a new management VRF
• In IP à Services move the www service to the management VRF
• Confirm you can no longer access the router via Webmin

Copyright 2016 MikroTikSA (Pty) Ltd 68


VRF Management
• Now we can manage the device by dialling in and
connecting to the remote end point tunnel IP

69
VRF Lab
• Dial in using the L2TP client from your laptop
• Access the webmin console via http://[tunnel_endpoint_IP]
• Confirm that the service is available via the VRF

Copyright 2016 MikroTikSA (Pty) Ltd 70


System Logging
• Firewall rules are no good without the ability to check what is happening
and at what time
• You can setup logging to track what is happening on your system for most
services
Access via System à Logging
• Default logging tracks to memory – this will be lost when the router
reboots
• Setup logging to disk or a remote server to keep logs persistently

71
Logging Setup

• Change the log target to disk to keep


entries persistent
• Set number of log files and lines per log
to reasonable value
• Sequential logs will appear in the files
menu

72
Firewall Log
• Some logs will generate excessive traffic
• You can maintain separate logs for different services
• Add a disk entry for the separate item to log
• Remove the item from Info log (if required to avoid double entries)

73
Invert
firewall on
Info log to
avoid double
logging

Add a new
rule to log
only firewall
entries

Create a custom action for


logging firewall rules 74
Hardening the Router
• Create a new Full Access user and change the default account
permissions
• Use IP Services to disable all services not required
• Set your NTP Client to enable accurate logging of events
– NTP Server on 10.1.1.254
• Change the default log location to save to disk
– Set a reasonable number of lines to save
• Add a custom log for firewall entries
– Track at least 5 files of 2000 entries each
• Create a backup called backup-firewall and save to your desktop
75
MikroTik Neighbour Discovery Protocol
• MikroTik Neighbor Discovery protocol (MNDP) allows to "find" other
devices compatible with MNDP or CDP (Cisco Discovery Protocol) or
LLDP in Layer2 broadcast domain.
• Works on any interfaces that support IP protocol and has an IP
address; and on all ethernet-like interfaces with or without IP
addresses
• Is enabled by default for all new ethernet-like interfaces
• Uses UDP protocol port 5678

76
MNDP Attack
Yersinia can be used to send fake CDP packets on the local network

77
MNDP DOS
RouterOS is receiving information about thousands of “fake” neighbor
devices.

78
MNDP Effect

It’s exhausting the resources of the


router and impacting performance

tool profile freeze-frame-interval=1

system resource cpu print

79
Preventing MNDP Attacks
• To prevent attacks we must select which interfaces can
communicate using MNDP/CDP/LLDP.
• We can mitigate attacks by creating an Interface List and selecting
which interfaces to enable neighbor discovery on (MNDP)
• Note that since ROS v6.45 the amount of neighbour entries are
limited to (total RAM in megabytes)*16 per interface to avoid
memory exhaustion and limit the damage of these attacks

80
MNDP Attack Mitigation

Creating “interface-list” for accessing MikroTik Neighbor


Discovery Protocol

/interface list add name=NEIGHBOR


/interface list member
add interface=etherX list=NEIGHBOR
add interface=etherY list=NEIGHBOR

81
MNDP Attack Mitigation

• IP > Neighbors set Discovery Settings to created Interface List

/ip neighbor discovery-settings set discover-interface-list=NEIGHBOR

82
MNDP DOS
• Trainer will use Yersinia to demonstrate CDP flood attack
• Monitor IP neighbours to check results of attack
• Create an interface list to limit MNDP to only LAN interfaces
• Monitor the results

83
DNS Client and Cache
• DNS client is used by the router for web-proxy or hotspot configuration and any
other internal lookup
• Both IPv4 and IPv6 addresses are natively supported
• Dynamic servers (received via DHCP Client or PPPoE) will be looked up first,
followed by static entries in order
• By enabling the “Allow Remote Requests” option the DNS client is then enabled
as a caching-only DNS server
• DNS cache allows use of the router for DNS resolution instead of a remote DNS
server
– It caches all requests, thereby minimizing resolution time
• DNS cache also can act as a DNS server for local area network address resolution
– You can add manual (static) entries for internal network addresses such as printers and
file servers

84
DNS Client and Cache
• Max UDP packet size limits the request size to
avoid truncation by legacy systems
• Query timeouts limits lookup time per server
and in total
• Cache size sets the amount of memory to use
for caching requests
– You can increase this size on more powerful routers
• If your DNS server has a public routed address
there is a high risk of amplification attacks – see
firewall further in this course
85
Static DNS Entry
• Static entries will override entries that are cached or looked up against a
remote server
• This can be combined with firewall / Layer7 / Proxy rules to limit access to
websites
• You can use names or Regular Expressions
Enable caching
DNS Server mode

86
DNS Forced Redirect
• You can use the IP Firewall to force DNS lookup
on your local router
IP à Firewall à NAT
• DNS uses UDP port 53 for lookup (with legacy
failback to TCP:53)
• The firewall Redirect action can be used to
force network users to your caching server
• This limits bypassing your DNS to get to certain
sites

87
DNS Cache
• Enable your www service on the router
• Configure your router as a DNS cache
– Use 10.1.1.254 as the primary server
• Add a static DNS entry “www.your_name.mtza” pointing to your
router's Local IP address
• Add a static DNS entry “www.Neighbour_name.mtza” to neighbour
router’s WAN IP address
• Change your laptop’s DNS server address to your router’s address
• Try the configuration and monitor the cache list
88
DNS Redirect
• Add a static DNS entry for www.httpforever.com pointing to your
router
• Add a dstnat rule in IP Firewall Nat to redirect all DNS (UDP:53 and
TCP:53) packets to your router
• Change your laptops DNS server address to a random IP e.g 4.5.6.7
• Test the configuration, browse www.httpforever.com and other sites,
monitor the DNS cache
• Try adding a regexp for .example.com and test the result

89
DNS Safe Browsing
• Cloudflare for Families allows additional filtering of DNS content
• Allows a free and easy to configure filter for safer browsing options
• Malware Blocking Only
Primary DNS: 1.1.1.2
Secondary DNS: 1.0.0.2
• Malware and Adult Content
Primary DNS: 1.1.1.3
Secondary DNS: 1.0.0.3
For IPv6 use:
• Malware Blocking Only
Primary DNS: 2606:4700:4700::1112
Secondary DNS: 2606:4700:4700::1002
• Malware and Adult Content
Primary DNS: 2606:4700:4700::1113
Secondary DNS: 2606:4700:4700::1003
• Introducing 1.1.1.1 for Families (cloudflare.com) 90
DNS over HTTPS
From Wikipedia
DNS over HTTPS (DoH) is a protocol for performing remote Domain Name System
(DNS) resolution via the HTTPS protocol. A goal of the method is to increase user privacy and
security by preventing eavesdropping and manipulation of DNS data by man-in-the-middle
attacks by using the HTTPS protocol to encrypt the data between the DoH client and the DoH-
based DNS resolver.
• Starting from RouterOS v6.47 you can enable DNS over HTTPS (DoH).
• DoH uses HTTPS protocol to send and receive DNS requests for better
data integrity.
• Currently DoH is not compatible with FWD type static entries

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

92
Cloudflare Certificate

/tool fetch url="https://cacerts.digicert.com/DigiCertGlobalRootCA.crt.pem"


/certificate import file-name=DigiCertGlobalRootCA.crt.pem
/ip dns set use-doh-server=https://cloudflare-dns.com/dns-query verify-doh-cert=yes

93
DOH
• Update your setup to use DNS over HTTPS
• https://www.bleepingcomputer.com/news/microsoft/how-to-
enable-dns-over-https-doh-in-windows-10/

94
DHCP
● In TCP/IP based networks, an IP address must be assigned to each
computer
● An IP address is a unique numeric identifier that identifies computers on
the network.
● The Dynamic Host Configuration Protocol (DHCP) is a service that can be
implemented to automatically assign unique IP addresses to (DHCP-
enabled) clients.
● It does not have much built in security - thus it is constrained to trusted
networks
● DHCP server always listens on UDP port 67 DHCP client - on UDP port 68
95 95
DHCP Lease Process
• DHCPDISCOVER: This message is used to request an IP address lease from a DHCP
server; sent as a broadcast packet over the network, requesting for a DHCP server to
respond to it
• DHCPOFFER: This message is a response to a DHCPDISCOVER message, and is sent by
one or numerous DHCP servers.
• DHCPREQUEST: The client sends the initial DHCP server which responded to its
request a DHCP Request message.
• DHCPACK message: The DHCP Acknowledge message is sent by the DHCP server to
the DHCP client and is the process whereby which the DHCP server assigns the IP
address lease to the DHCP client.

96
DHCP client
IP à DHCP à Client
● The client can accept:

- IP address with respective netmask


- Default gateway
- Two DNS server addresses
- Two NTP server addresses
- Domain name
- WINS-server information
- CAPSMAN Server
● Use Peer DNS, Use Peer NTP, specifies whether the routers settings should be
updated with values obtained from the DHCP server (if offered)
● Add Default Route adds a default gateway (0.0.0.0/0 route)
● Default Route Distance specifies the cost of the DR 97
DHCP Client Identification
• DHCP servers are able to track the lease association with a particular client based
on identification
• The identification can be achieved in 2 ways
– Based on “caller-id” option (dhcp-client-identifier from RFC2132)
– Based on MAC address, if “caller-id” option is not specified
• The “hostname” option allow RouterOS clients to send additional identification to
the server, by default it is “system identity” of the router

98
DHCP Server
IP à DHCP-Server
• There can be only one DHCP server per interface/relay combination on
the router
• To create a DHCP server you must have
– An IP address on desired DHCP server interface
– Address pool for clients
– Information about planned DHCP network
• All 3 options must correspond
• To add a DHCP Relay you must have an IP from the network that the relay
is servicing on the specified relay interface
• “Lease on Disk” can be used to reduce the number of writes to the drive
(useful with flash drives)
99
DHCP Networks
• In the DHCP Networks menu you can configure specific DHCP options for
a particular network.
• Same of the options are integrated into RouterOS, others can be
assigned in raw form (specified in RFC’s)
• DHCP server can serve any option
• DHCP clients can receive supported options
IP à DHCP-Server à Networks

• Additional information at:

http://www.iana.org/assignments/bootp-dhcp-parameters/bootp-dhcp-parameters.xml 100
IP Address Pool
IP à Pool
• IP address pools are used to define ranges of IP addresses for dynamic
distribution (DHCP, PPP, Hotspot)
• Address pools must exclude already occupied addresses (such as a server
or statically assigned address, network and broadcast addresses)
• You can assign more that one range to a pool
• It is possible to chain several pools together by using the “Next Pool”
option

101
Address Pool in Action

102
Other DHCP Server Settings
• Src. Address – specifies the DHCP servers
address if the is more than one IP on the DHCP
server's interface
• Add ARP For Leases – allow adding of an ARP
entry for lease if interface ARP=reply-only
• Always Broadcast – allow communication with
non-standard clients like pseudo-bridges
• Bootp Support, Use RADIUS – as it says

103
Other DHCP Server Settings
• Insert Queue Before – If a bandwidth limitation is specified in a static
lease a dynamic queue will be created for the client in the specified
location
• Delay Threshold – prioritize one DHCP server over another (bigger delay
less priority), used in primary / backup server configurations
• Authoritative – allow DHCP server to reply on unknown client broadcast
and ask the client to restart the lease (client sends a broadcast only if
unicast to the server fails)
• Authoritative allows:
– Prevention of rogue DHCP server operation (attempts to force the client to only
message this server)
• Set to Always
– Faster network adaptation to DHCP configuration changes
104
Other DHCP Server Settings
• Conflict Detection – When the server tries to assign a lease it will
send ICMP and ARP messages to detect whether the address already
exists in the network. If a reply is received, then the address is
considered already used. Conflict detection must be disabled when
any kind of DHCP client limitation per port or per mac is used.
• Used Framed as Classless – Forward RADIUS Framed-Route as a
DHCP Classless-Static-Route to DHCP-client. Whenever both Framed-
Route and Classless-Static-Route is received Classless-Static-Route is
preferred.

105
DHCP Server
Group Router
• Work in groups, connect your Ether3
ports to the group router
10.x.0.0/24 • Setup a DHCP Server on LAN_Bridge,
manually configure the IP Pool, DHCP
Network and DHCP Server settings
• Install a DHCP Client on your router
192.168.x.0/24

192.168.x.0/24

ether3, specify a Hostname different to


system ID
– Monitor the status on the server and the
client
Laptop 1 Laptop 2 106
DHCP Server
• Bridge your Ether2 and Ether3 ports together, set your laptops to obtain
an IP Address automatically
• Make any changes necessary to maintain internet access
• Configure a 2nd DHCP Server on one of your LAN router bridges.
• Refresh your laptop IP’s – you must release before renewing
• Test what happens if you configure one server as authoritative, and if you
configure a delay
• In each case to test you must fully release your IP (or unplug the ether to
your laptop) before renewing
– This is because the Authoritative setting will try to force the client to the old
server
107
Static Lease

• Lease can be made static from DHCP à


Leases by using right click and Make Static
• Static leases have additional available options
– Block Access: Prevent MAC address from
obtaining a lease
– Allow Dual Stack Queue – For IPv6/v4 dual
limitation
– Rate Limit: Create a dynamic queue based on the
assigned IP
– Insert Queue Before: Where to place queue
– Address List: Add to specified firewall address list
108
DHCP Alert
• The MikroTik DHCP Server can detect rogue DHCP servers on a network segment
• This is useful for detecting accidental or purposeful setup of a different DHCP
server
• The system will write an entry to the Log when another (unknown) server is
detected
• You can add known servers to prevent false positives

109
DHCP Static
• Use the previous lab setup to create a static lease
– Set a 4M up/down limitation
– Add to a firewall address list
– Test the results
• Add a DHCP alert to the interface running DHCP server
– Check the log for results
• Configure a DHCP client on your LAN router bridge
• On the server, change the LAN router leases to static

110
DHCP Options
IP à DHCP-Server à Options
• Implemented DHCP options
– Subnet-Mask (option 1) - netmask
– Router (option 3) - gateway
– Domain-Server (option 6) - dns-server
– Domain-Name (option 15) - domain
– NTP-Servers (option 42) - ntp-server
– CAPS Managers – Centralised Access Point Manager server
– NETBIOS-Name-Server (option 44) - wins-server
• Custom DHCP options (Example:)
– Classless Static Route (option 121) - “0x100A270A260101” = “network=10.39.0.0/16
gateway=10.38.1.1”
– TFTP Server (option 150) = 10.1.1.254
– Use single quotes to enclose text values – e.g. ‘10.1.1.254’
111
DHCP Route Calculator
• The link below can be used to calculate a classless option
https://www.medo64.com/2018/01/configuring-classless-static-route-option/

112
DHCP Static
• Configure DHCP option 121 to create a route to 8.8.8.0/24 via
10.1.1.254
– If you use the route calculator you must include the default route option
• Add the option to the LAN router static lease and test

113
DHCP Relay
• DHCP Relay is a specific type of proxy that is able to receive a DHCP
discovery and request and resend them to the DHCP server
• DHCP communication with the relay does not require an IP address on
the relay if the relay's “local address” option is the same as the server's
“relay address” option (only when RouterOS is the server)
– Otherwise the relay interface must
have an IP address valid for that network
– If no IP is configured then the router
cannot be a gateway for that network
• If there is more than 1 IP address
on the relay network interface then the
Local Address option must be configured
114
DHCP Server
Group Router • Remove the bridge between Ether 2 &
3
DHCP Server is on
• Remove any LAN router DHCP servers
this segment with
additional LAN ranges • On WAN server bridge use the setup
wizard to add additional servers for
your Lan ranges
192.168.x.0/24

192.168.x.0/24
• Add a relay to your Ether2 port to
Relays are added on
local LAN segments distribute DHCP to your local LAN
segment
• Test the functionality of the relay
Laptop 1 Laptop 2 115
DHCP Starvation Attack
• An attack that works by broadcasting DHCP requests with spoofed
MAC addresses.
• DHCP starvation attack targets DHCP servers whereby forged DHCP
requests are crafted by an attacker with the intent of exhausting all
available IP addresses that can be allocated by the DHCP server

116
DHCP Starvation Attack
• This tool (yersinia) sends multiple “fake” DHCP
requests to the router

117
DHCP Starvation Attack

• Attacker exhausts DHCP leases with multiple dhcp-


requests to the router.

118
Preventing DHCP Starvation
• Attacker uses a new MAC address to request a new DHCP lease
• Restrict the number of MAC addresses on the port of switch.
• Will not be able to lease more IP addresses than MAC addresses allowed on
the port
• Not directly supported on ROS, however you can use bridge firewall to only
allow a specific MAC on a port
• SwitchOS has the capability to lock a port to a specific MAC on first binding
port-security
Router max 1 MAC
port-security
max 1 MAC

119
Rogue DHCP Server
• A rogue DHCP server is a DHCP server on a network which is not
under the administrative control.
• It is set up on a network by an attacker, for taking advantage from
clients.

120
Rogue DHCP Server

121
Rogue DHCP Server
• Server IP – the IP server, the name of which will send the answer the
DHCP (xxx.xxx.xxx.xxx);
• Start IP – initiaIP, , issued to customers -address address range
(xxx.xxx.xxx.xxx);
• End IP – IP , issued to customers -address address range (xxx.xxx.xxx.xxx);
• Time The Lease (secs) – The time in seconds for which the address is
given
• Time The Renew (secs) – The time in seconds how many clients must
renew the address lease
• Subnet Mask – Subnet mask for the clients (xxx.xxx.xxx.xxx);
• Router – router address issued to clients (xxx.xxx.xxx.xxx ,the address of a
fake router);
• DNS Server – DNS server provided to clients (xxx.xxx.xxx.xxx ,the address
of a fake DNS server);
• The Domain – a domain name in the local area network ( abc.def ); 122
Preventing Rogue DHCP Server
• Enable DHCP Snooping on the switch
– Set on the bridge
– Only CRS3xx can do snooping and VLAN filtering in hardware
• Make port facing router as DHCP Snooping Trusted
• Binding Address and MAC for known clients
• RouterOS DHCP alert is ONLY sending information, not stopping or preventing an attack.

DHCP Snooping enabled

Router trusted untrusted


untrusted

123
https://wiki.mikrotik.com/wiki/Manual:Interface/Bridge#DHCP_Snooping_and_DHCP_Option_82
DHCP Snooping
• Add ether1 to the bridge of the common router
• Disable DHCP server on the common router
• Bridge your LAN routers ether 2 and 3 together
• Trainer will configure DHCP server as Authoritative
• Set your laptop to DHCP and check IP address – should be 10.1.1.x
• Setup a DHCP server on the bridge of one of the LAN routers
• Configure DHCP Snooping to only allow only traffic from valid DHCP servers
• Test the configuration
• Restore original config when complete

124
ROUTEROS
SECURITY DEPLOYMENT
Firewall Types
IPS and IDS
Firewall vs IPS vs IDS

https://ipwithease.com/firewall-vs-ips-vs-ids/ 126
Firewall

Single device firewall


• Sits inline with the network
• Runs at layer3
• Uses packet inspection to compare a packet to a pre-defined
set of rules
• E.g. src/dst IP, protocol, port, in/out interface, packet rate
• Can provide stateful inspection to determine packet state
• Does not generally require high specification hardware 127
MikroTik as a Global Firewall Router

DATA CENTER

OFFICE
INTERNET

GUEST

128
MikroTik as a Global Firewall Router

Pro's
• Simple topology
• Easy to manage

Con's
• Single-point-of-failure
• Demands high resources (single CPU core utilized)
• CHR on high speed CPU (or version 7?)

129
MikroTik as a Specific Router Firewall

DATA CENTER

OFFICE
INTERNET

GUEST

130
MikroTik as a Specific Router Firewall

Pro's
• Less resource consumption on each router
• Only focusing security firewall on each network

Con's
• Different network segment, different treatment
• Need to configure firewall differently on each router
• Possible to configure double firewall rules across routers

131
IPS

Intrusion Prevention System


• Sits inline with the network
• Runs at layer7 and/or layer3
• Inspects traffic in real time and compares it to predefined
signatures and patterns
• Prevents traffic on detection
• Requires heavy duty hardware for real time detection

132
MikroTik as an IPS

DATA CENTER

OFFICE
INTERNET

GUEST

133
MikroTik as an IPS

Pros
• Clean firewall configuration on router, because all firewall
configuration already defined on an IPS (Intrusion Prevention
System) router

Cons
• A lot of resources will be needed to use RouterOS as an IPS
• Can be mitigated somewhat by using RAW table filtering

134
IDS

Intrusion Detection System


• Does not sit inline
• Runs at layer7
• Inspects traffic in real time and compares it to predefined
signatures and patterns
• Raises alert on detection and possibly updates firewall
• Requires medium duty hardware for real time detection 135
MikroTik with IDS as a trigger

DATA CENTER

OFFICE
INTERNET

GUEST
IDS SERVER

136
MikroTik with IDS as a trigger
Pro's
• All firewall rules are made automatically by API from IDS (Intrusion Detection
System) server
• MikroTik only drops traffic, so few resources required

Con's
• Additional device is needed to be triggered by the "bad" traffic
• A powerful device is needed for mirroring all traffic from networks
• MikroTik CRS3xx series has capability
• Need special scripting for sending information to router (no quick plugin software
yet)
• Expensive (compared to a standard router implementation)

137
Firewall Structure
• Firewall filter, mangle and nat rules are organized in chains
• There are default and user-defined chains
• There are default chains for each of the firewall functions
• Firewall Filter:
– input – processes packets sent to the router
– output – processes packets sent by the router
– forward – processes packets sent through the router
• Firewall NAT:
– srcnat – Source Nat chain for modifying the source IP:port pair
– dstnat– Destination Nat chain for modifying the destination IP:port pair
• Firewall Mangle:
– prerouting – mark packets before the Global-in queue
– postrouting – mark packets before the Global-out queue
– input – mark packets before the input chain
– output – mark packets before the output chain
– forward – mark packets before the forward chain
• Packets traversing the router must pass through at least one of the default chains
• User-defined chain can only be processed via one of the default chains 138
Router Packet Flow

139
Menu Location

140
Bridging Traffic Flow

141
Routing Traffic Flow

142
MPLS Traffic Flow

143
Normal Traffic Flow

144
PPPoE Out

145
PPPoE In

146
Bridge Firewall
Bridge Firewall
• The bridge firewall implements packet filtering and thereby provides
security functions that are used to manage data flow to, from and
through bridge.
• Traffic can be matched by Interface, MAC address, MAC protocol, IP
Protocol, Packet Mark, TLS Host, VLAN and other matchers
• Actions are similar to firewall filter, but also allows Set Priority for
e.g. setting VLAN priority
• NOTE: Bridge Firewall will not process packets that are Hardware
Offloaded

148
Bridge Filter
• /interface bridge filter print stats
• Implements packet filtering
• manage data flow
– To: Input Chain
– From: Output Chain
– Through: Forward Chain

149
Bridge Firewall

150
Filter Only PPPoE
• Working on the shared access router:
– Configure a PPP pool to assign IP address
– Configure a new PPP Profile with a local address as the router loopback and
remote address as the pool
– Configure a number of PPP secrets for dialup depending on group numbers
– Add a PPPoE server to the bridge
– Be sure to specify the correct profile

151
LAN Routers
• Configure a PPPoE client to connect to the server
• Add a masquerade rule to NAT out all-ppp interfaces
• Confirm that internet access is available via both PPPoE and DHCP
clients
– Disable/enable in turn to test

152
Chain Bridge Forward
• Configure bridge firewall filtering to only allow PPPoE traffic through
the bridge
– You will need to allow both pppoe-discovery and pppoe-session protocols
– Remember, it is traffic through the bridge, what is the correct chain for
that?
• Confirm that Internet access is still available via PPPoE
• Confirm that no access is available via DHCP client

153
Filter Chains
router<>router:
Output chain to Input chain

Laptop<>router: Laptop<>Laptop:
Input chain Forward chain on
both routers

Laptop 1 Laptop 2

154
Firewall Filter Structure Diagram

155
Stateful Firewall
• RouterOS implements a stateful firewall. A stateful-firewall is a
firewall capable of tracking ICMP, UDP, and TCP connections.
• This means that the firewall can identify if a packet is related to
previous packet.
• Firewall can track operating state.

156
Intrusion Detection
• Where can we detect / compare traffic flows against given sets of
conditions?
• Firewall RAW
– Able to detect traffic before connection tracking
– Not capable of using any connection state variables e.g. working with only NEW
state packets
• Firewall filter
– Detects traffic post ConnTrack
– Works with Connection State based rules
• Firewall Mangle
– Detects traffic post ConnTrack
– Useful for bulk marking of connections and traffic flows

157
Connection Tracking
• Connection Tracking (or Conntrack) is the heart of the firewall
• 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,
and iptables can use this information to act as a stateful firewall
• By disabling the conntrack system you will lose total functionality of the NAT
system and some of the filter and mangle system
– Some filter and mangle rules can still operate if the matcher is not dependant on
conntrack
– Firewall RAW does not depend on conntrack
• Each conntrack table entry represents bidirectional data exchange
• Conntrack takes a lot of CPU resources
– disable it, if you don't use any firewall functions on that router
– OR you only work with RAW table rules 158
Conntrack Placement

159
160
TCP Connections
• The TCP handshaking mechanism is designed so that two computers
attempting to communicate can negotiate the parameters of the
network TCP socket connection before transmitting data such as SSH
and HTTP web browser requests.
• This 3-way handshake process is also designed so that both ends can
initiate and negotiate separate TCP socket connections at the same
time.
– Being able to negotiate multiple TCP socket connections in both directions
at the same time allows a single physical network interface, such as
ethernet, to be multiplexed to transfer multiple streams of TCP data
simultaneously.

161
TCP 3-way Handshake
• Client sends a TCP SYNchronize packet to Server – Firewall Conntrack marks as New connection state
• Server receives A's SYN
• Server sends a SYNchronize-ACKnowledgement to client - Conntrack marks as Established connection state
• Host A receives B's SYN-ACK - Host A sends ACKnowledge - Conntrack keeps as Established connection state
• Host B receives ACK - TCP socket connection is ESTABLISHED.

162
TCP Sessions
• SYNchronize and ACKnowledge messages are indicated by a either the
SYN bit, or the ACK bit inside the TCP header
– SYN-ACK message has both the SYN and the ACK bits turned on in the TCP
header.
• TCP knows whether the network TCP socket connection is opening,
synchronizing, established by using the SYNchronize and ACKnowledge
messages when establishing a network TCP socket connection.
• When the communication between two computers ends, another 3-way
communication is performed to tear down the TCP socket connection
– This setup and teardown of a TCP socket connection is part of what qualifies TCP
a reliable protocol
– TCP also acknowledges that data is successfully received and guarantees the data
is reassembled in the correct order.

163
UDP Connections
• Note that UDP is connectionless
• That means UDP doesn't establish connections as TCP does, so UDP does
not perform this 3-way handshake
– For this reason, it is referred to as an unreliable protocol.
• This does not mean UDP can't transfer data, it just doesn't negotiate how
the connection will work
– UDP just transmits and hopes for the best
• Traffic like UDP and ICMP can still have a connection state since traffic is
still travelling in both directions
– E.g. a constant ping between 2 devices will maintain the same connection state

164
Condition: Connection State
• Connection state is a status assigned to each packet by the
conntrack system:
– New – packet is opening a new connection
– Established – packet belongs to already known connection
– Invalid – packet does not belong to any of the known connections
– Related – packet is also opening a new connection, but it is in some kind
relation to already known connection
• Connection state ≠ TCP state

165
TCP Connection State
State Explanation
The NEW state tells us that the packet is the first packet that we see. This means that the first packet that
NEW 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.

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
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.

The RELATED state is one of the more tricky states. A connection is considered RELATED when it is related to
another already ESTABLISHED connection. What this means, is that for a connection to be considered as
RELATED 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, if the conntrack module is able to understand that it is RELATED.

The INVALID state means that the packet can't be identified or that it does not have any state. This may be
INVALID due to several reasons, such as the system running out of memory or ICMP error messages that do not
respond to any known connections. Generally, it is a good idea to DROP everything in this state. 166
Chain Input

Protection of the router – allowing only necessary


services from reliable source addresses with agreeable
load.

167
Chain Input
• Create 3 rules to ensure that only connection-state new packets will
proceed through the input filter
– Drop all connection-state invalid packets
– Accept all connection-state related packets
– Accept all connection-state established packets
• Create 2 rules to ensure that only you will be able to connect to the
router
– Accept all packets from your laptop IP
– Drop everything else
• Label the rules accordingly
168
Fasttrack
• A method to accelerate packet flow through the router
• An established or related connection can be marked for fasttrack connection
• Bypasses firewall, connection tracking, simple queue and other features
• Currently supports only TCP and UDP protocols
• To use, add before the accept established/related rules

169
More Firewall Rules
• Update your input chain connection state rules to fasttrack connections

170
Firewall Action Log
• The log action is used to log any firewall activity that you want to track
• If you want to track a specific rule in the firewall you would create a rule
with identical matching parameters but with action “log”
• The log rule must be placed above the rule you want to track
• You can prefix the log to make it easier to identify
• Like “passthrough”, the log action does not affect the packet in any way
• Log is often used just before action “drop” to determine what is being
dropped by the firewall
• You can combine the log action with any other rule when setting the
action

171
Action “log”

172
RouterOS Services

173
Network Services
• Create rules to allow only necessary RouterOS services to be
accessed from the public network
• Use action “log” to determine those services
• Create a rule to allow winbox, ssh and telnet connections from the
“public” network (10.1.1.0/24)
– Test the functionality, you should be able to winbox to your neighbours
router, but not ping it

174
OSPF Setup
• Add a new OSPF Instance in OSPF à Instances
• Set the Version to 2
• Set your WAN IP as your Loopback
• Set to distribute static and connected routes

175
OSPF Setup
• Add a new OSPF area called backbone in
OSPF à Areas
• Set the Area ID to 0.0.0.0
• Add a new OSPF Interface Template with
ether1 as the interface

OSPF à Areas OSPF à Interface Templates 176


Network Services
• Allow OSPF on the ether1 interface (previous slide)
– Remove your default route
• Arrange rules accordingly
• Write comment for each firewall rule
• Evaluate what else is being dropped and add accept or drop rules
accordingly
• Attempt a bandwidth test to your neighbour
– If unsuccessful create the required rules

177
Important Issue
• Firewall filters do not filter MAC level
communications
• You should turn off MAC-telnet and MAC-
Winbox features at least on the public
facing interface (Tools à MAC Server)
– Use Interface List to define allowed interfaces
• You can disable the network discovery
feature so that the router does not reveal
itself (IP à Neighbour à Discovery)

178
Firewall Filter Chains
• Firewall filtering rules are grouped together in chains
• You can match a packet against some common criteria in one chain, and
then pass it over for processing to another chain.
• For example a packet needs to be matched against an IP address:port
pair
– You could achieve it 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 a successful match
pass the IP packet to a custom chain, (mychain in this example)
– rules that perform matching against separate ports can be added to mychain
chain without specifying the IP addresses.

179
Firewall Filter Chains
• You can reroute traffic to user-defined chains using action jump (and
reroute it back to the default chain using action return)
– Note there is no point in having a return action if the final rule in the chain
is a drop all
• Users can add any number of chains
• User-defined chains are used to optimize the firewall structure and
make it re-usable, more readable and manageable
• User-defined chains help to improve performance by reducing the
average number of processed rules per packet

180
User-Defined Chains
TCP
traffic

UDP
traffic

© MikroTikSA.com 2007 181


181
Custom Chain
• Migrate the Connection State rules to a custom chain called
“conn_state”
– You need to create the chain on the first rule, subsequent rules will have
the chain in the drop down list
• Add a jump rule to the Input chain to ensure packets get processed
through these rules
– Add a return rule to ensure other rules are evaluated
• Add a jump rule to the Forward chain to ensure packets get
processed through these rules

182
Chain Forward

Protection of clients from viruses and protection of the


public network from the client

183
Virus Port Filter
• At the moment the are few hundreds active trojans and less than 50
active worms
• Some viruses and trojans use standard services ports and can not be
blocked.

184
Chain Forward
• Copy the virus2 chain script from the trainer router 10.1.1.254 /pub
directory and import it onto your router
– This will create a “virus” chain for tcp ports and “virus_udp” for udp ports
• Add forward chain jump rules to send UDP and TCP traffic to the
correct respective chains
– You will require one rule per chain
– Remember to add a “return” rule to the end of each chain
• Order and label all the chains and rules correctly

185
Bogon IPs
• There are ~4,3 billion IPv4 addresses
• There are several IP ranges that are restricted in the public network
• There are several of IP ranges reserved (not used at the moment) for
specific purposes
• There are lots of unused IP ranges!!!
• You can find information about all unused IP ranges at:
http://www.completewhois.com/bogons/

186
Address List Options
• Instead of creating one filter rule for each IP
network address, you can create a single rule
by using an IP address list.
• Use “Src./Dst. Address List” options in the
Filter rule Advanced tab
• Create an address list in the “/ip firewall
address-list” menu
– Use single address, range or subnet or any
combination
• You can use 1 address list per firewall rule

187
Address List Cont.
• Rules can also be created dynamically by using the Add
source/destination to Address List action in Firewall Filter, NAT or
Mangle
• Options for adding an address
– None Static: Add a permanent address that will be persistent through
router reboots
– None Dynamic: Add a dynamic entry with no timeout that will reset after
reboot
– 00:00:00 time value – add for specified time
• You can specify a FQDN instead of an IP – this will lookup all possible
values for domain and add with TTL value from DNS lookup 188
Good MANRS
• https://manrs.org/
• Mutually Agreed Norms for Routing Security (MANRS) is a global
initiative, supported by the Global Cyber Alliance, that provides
crucial fixes to reduce the most common routing threats
• The MANRS Network Operators Program defines the minimum steps
network operators like Internet Service Providers should take to
ensure the security and resilience of the Internet’s global routing
system

189
Network Opearator Actions
1.Filtering - Ensure the correctness of your own announcements and
those from your customers to adjacent networks
2.Anti-spoofing - Enable source address validation for at least single-
homed stub customer networks, their own end-users, and
infrastructure
3.Coordination - Maintain globally accessible, up-to-date contact
information in common routing databases.
4.Global information - Publish your data so others can validate

190
Address List
• Make an address list of the most common bogon IPs
• You can import the bogon-list file from the course resources

191
Address Filtering
• Allow packets to enter your network only from valid Internet
addresses
• Allow packets to enter your network only to valid customer
addresses
• Allow packets to leave your network only from valid customers
addresses
• Allow packets to leave your network only to valid Internet addresses
• Label all rules correctly

192
Alternatives for blacklisting
• The full bogon list is over 5000 IP ranges
• The list constantly changes as addresses are assigned from the
available IPv4 space
• You can use a BGP feed from Team Cymru with a route filter
blackhole as an alternative means of blocking bogon IP ranges

193
Blackhole Filtering
• You can use IP à Routes as a means of blackholing certain ranges
• This is far more efficient than firewall filtering as it is a route table
lookup requiring minimal resources
• Set route type=blackhole to stop packets to private networks
See https://mikrotiksa.jitbit.com/helpdesk/KB/View/40063499-tech-
day-files for related scripts

194
Blackhole Filter
/ip route
# IPv4 reserved and private ranges
add type=blackhole comment="This network" dst-address=0.0.0.0/8
add type=blackhole comment=Loopback dst-address=127.0.0.0/8
add type=blackhole comment=Private dst-address=10.0.0.0/8
add type=blackhole comment="CG Nat" dst-address=100.64.0.0/10
add type=blackhole comment=Private dst-address=172.16.0.0/12
add type=blackhole comment=Private dst-address=192.168.0.0/16
add type=blackhole comment=Private dst-address=169.254.0.0/16
add type=blackhole comment=ietf dst-address=192.0.0.0/24
add type=blackhole comment=ietf dst-address=192.0.2.0/24
add type=blackhole comment=reserved dst-address=192.88.99.0/24
add type=blackhole comment="benchmark testing" dst-address=198.18.0.0/15
add type=blackhole comment="benchmark testing" dst-address=198.51.100.0/24
add type=blackhole comment="benchmark testing" dst-address=203.0.113.0/24
add type=blackhole comment=Multicast dst-address=224.0.0.0/3

195
IPv6 Blackhole Filter
# IPv6 reserved and private ranges
add type=blackhole comment="IPv6 - IPv4-compatible IPv6 address deprecated by RFC4291" dst-address=::/96
add type=blackhole comment="IPv6 - Unspecified address" dst-address=::/128
add type=blackhole comment="IPv6 - Local host loopback address" dst-address=::1/128
add type=blackhole comment="IPv6 - IPv4-mapped addresses" dst-address=::ffff:0.0.0.0/96
add type=blackhole comment="IPv6 - Compatible address (IPv4 format)" dst-address=::224.0.0.0/100
add type=blackhole comment="IPv6 - Compatible address (IPv4 format)" dst-address=::127.0.0.0/104
add type=blackhole comment="IPv6 - Compatible address (IPv4 format)" dst-address=::/104
add type=blackhole comment="IPv6 - Compatible address (IPv4 format)" dst-address=::255.0.0.0/104
add type=blackhole comment="IPv6 - Pool used for unspecified loopback and embedded IPv4 addresses" dst-address=::/8
add type=blackhole comment="IPv6 - OSI NSAP-mapped prefix set (RFC4548) deprecated by RFC4048" dst-address=200::/7
add type=blackhole comment="IPv6 - Former 6bone now decommissioned" dst-address=3ffe::/16
add type=blackhole comment="IPv6 - Reserved by IANA for special purposes and documentation" dst-address=2001:db8::/32
add type=blackhole comment="IPv6 - Invalid 6to4 packets (IPv4 multicast)" dst-address=2002:e000::/20
add type=blackhole comment="IPv6 - Invalid 6to4 packets (IPv4 loopback)" dst-address=2002:7f00::/24
add type=blackhole comment="IPv6 - Invalid 6to4 packets (IPv4 default)" dst-address=2002::/24
add type=blackhole comment="IPv6 - Invalid 6to4 packets" dst-address=2002:ff00::/24
add type=blackhole comment="IPv6 - Invalid 6to4 packets (IPv4 private 10.0.0.0/8 network)" dst-address=2002:a00::/24
add type=blackhole comment="IPv6 - Invalid 6to4 packets (IPv4 private 172.16.0.0/12 network)" dst-address=2002:ac10::/28
add type=blackhole comment="IPv6 - Invalid 6to4 packets (IPv4 private 192.168.0.0/16 network)" dst-address=2002:c0a8::/32
add type=blackhole comment="IPv6 - Unicast Unique Local Addresses (ULA) RFC 4193" dst-address=fc00::/7
add type=blackhole comment="IPv6 - Link-local Unicast" dst-address=fe80::/10
add type=blackhole comment="IPv6 - Site-local Unicast deprecated by RFC 3879 (replaced by ULA)" dst-address=fec0::/10
add type=blackhole comment="IPv6 - Multicast" dst-address=ff00::/8

196
Address Filtering
• Remove the previous address filtering rules
• Add the blackhole filter routes
• Test traceroute to private ranges

197
Firewall Address List
• PROBLEM: You need to apply firewall rules by DNS name instead of
static address
• SOLUTION: Firewall address list can now track DNS names for
dynamic address generation
• Lists will be refreshed according to upstream TTL record
• Domains with multiple servers will generate multiple records

198
199
Firewall Address List
• Firewall action “Add src/dst to address list” has improved options
• Choose between a set timeout value, none static or none dynamic

200
Built In Addresses
• Firewall Extra tab can be used to match certain default address
types for SRC or DST
• unicast - IP address used for point to point transmission
• local - if dst-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
• E.g. for Mangle prerouting chain you can match traffic to router by
specifying DST Address Type = local

201
PPP Address List
• It is possible to add incoming PPP
connections to an Address List automatically
• Use PPP Profile à Address List to
automatically add each incoming client to
specified list
• You can also use the built in all-ppp interface
to process all ppp interfaces at once

202
TLS Host
• Usually, it is not possible to firewall by DNS name without using L7 Filter
• TLS Host Allows to match https traffic based on TLS SNI hostname
– Accepts GLOB syntax for wildcard matching
• Note this cannot be tracked on the first (SYN) packet and needs a stream of packets – so
check Accept Established/Related rules in firewall Filter

Wildcard Description Example Matches Does not match


Law* Law, Laws, or Lawyer GrokLaw, La, or aw
matches any number of any
* Law, GrokLaw,
characters including none *Law* La, or aw
or Lawyer.
? matches any single character ?at Cat, cat, Bat or bat at
matches one character given
[abc] [CB]at Cat or Bat cat or bat
in the bracket
matches one character from
Letter0, Letter1, Letter2 Letters, Letter or L
[a-z] the (locale-dependent) range Letter[0-9]
up to Letter9 etter10
given in the bracket 203
TLS and Connstate
• TLS cannot match on the first packet of a connection
• If you are accepting and fastracking established/related connections
the TLS-host rule will not count anything
• You need to allow some packets through the rule first for TLS
matching to occur
• Use the Connection-Bytes field (Advanced tab) to specify a certain
number of packets allowed through
– Format is e.g. 10000-0

204
205
206
TLS Host
• Add a rule to block *facebook.com by tls-host parameter
• Test operation (does not work with conn_state rule)
• Update conn_state rules (including fastrack) to accept connection
bytes 10000-0
• Test the operation again
• Remember this will need to be added before the rule accepting your
local network range

207
Advanced Protection

ICMP
Ping Flood, PSD, (D)DoS
ICMP Protocol
• Internet Control Message Protocol (ICMP) is a basic network
troubleshooting tool
– it should be allowed to bypass the firewall
• A typical IP router uses only five types of ICMP messages (type:code)
– For PING - messages 0:0 and 8:0
– For TRACEROUTE – messages 11:0 and 3:3
– For Path MTU discovery – message 3:4
• Every other type of ICMP messages should be blocked

209
ICMP Message Rule Example

210
ICMP Jump Rule

211
Table Filtering Recommendations

ICMPv4 Message Sourced from Through Destined to


Device Device Device
ICMPv4-unreach-net Limit rate Limit rate Limit rate

ICMPv4-unreach-host Limit rate Limit rate Limit rate

ICMPv4-unreach-proto Limit rate Deny Limit rate

ICMPv4-unreach-port Limit rate Deny Limit rate

ICMPv4-unreach-frag-needed Send Permit Limit rate

ICMPv4-unreach-src-route Limit rate Deny Limit rate

ICMPv4-unreach-net-unknown (Depr) Deny Deny Deny

ICMPv4-unreach-host-unknown Limit rate Deny Ignore

ICMPv4-unreach-host-isolated (Depr) Deny Deny Deny

ICMPv4-unreach-net-tos Limit rate Deny Limit rate

Recommendations for ICMPv4

212
Table Filtering Recommendations

ICMPv4 Message Sourced from Through Destined to


Device Device Device
ICMPv4-unreach-host-tos Limit rate Deny Limit rate
ICMPv4-unreach-admin Limit rate Limit rate Limit rate
ICMPv4-unreach-prec-violation Limit rate Deny Limit rate
ICMPv4-unreach-prec-cutoff Limit rate Deny Limit rate
ICMPv4-quench Deny Deny Deny
ICMPv4-redirect-net Limit rate Deny Limit rate
ICMPv4-redirect-host Limit rate Deny Limit rate
ICMPv4-redirect-tos-net Limit rate Deny Limit rate
ICMPv4-redirect-tos-host Limit rate Permit Limit rate
ICMPv4-timed-ttl Limit rate Permit Limit rate

Recommendations for ICMPv4

213
Table Filtering Recommendations

ICMPv4 Message Sourced from Through Destined to


Device Device Device
ICMPv4-timed-reass Limit rate Permit Limit rate
ICMPv4-parameter-pointer Limit rate Deny Limit rate
ICMPv4-option-missing Limit rate Deny Limit rate
ICMPv4-req-echo-message Limit rate Permit Limit rate
ICMPv4-req-echo-reply Limit rate Permit Limit rate
ICMPv4-req-router-sol Limit rate Deny Limit rate
ICMPv4-req-router-adv Limit rate Deny Limit rate
ICMPv4-req-timestamp-message Limit rate Deny Limit rate
ICMPv4-req-timestamp-reply Limit rate Deny Limit rate
ICMPv4-info-message (Depr) Deny Deny Deny

Recommendations for ICMPv4

214
Table Filtering Recommendations

ICMPv4 Message Sourced from Through Destined to


Device Device Device
ICMPv4-info-reply (Depr) Deny Deny Deny
ICMPv4-mask-request Limit rate Deny Limit rate
ICMPv4-mask-reply Limit rate Deny Limit rate

Recommendations for ICMPv4

215
ICMPv4 Error Messages
• Echo Reply (Type 0, Code 0)
• Destination Unreachable (Type 3)
• Net Unreachable (Code 0)
• Host Unreachable (Code 1)
• Protocol Unreachable (Code 2)
• Port Unreachable (Code 3)
• Fragmentation Needed and DF Set (Code 4)
• Source Route Failed (Code 5)
• Destination Network Unknown (Code 6) (Deprecated)
• Destination Host Unknown (Code 7)
• Source Host Isolated (Code 8) (Deprecated)
• Communication with Destination Network Administratively
Prohibited (Code 9) (Deprecated)

216
ICMPv4 Error Messages
• Destination Unreachable (Type 3)
• Communication with Destination Host Administratively
Prohibited (Code 10) (Deprecated)
• Network Unreachable for Type of Service (Code 11)
• Host Unreachable for Type of Service (Code 12)
• Communication Administratively Prohibited (Code 13)
• Host Precedence Violation (Code 14)
• Precedence Cutoff in Effect (Code 15)

217
ICMPv4 Error Messages

• Source Quench (Type 4, Code 0)


• Redirect (Type 5)
• Redirect Datagrams for the Network (Code 0)
• Redirect Datagrams for the Host (Code 1)
• Redirect datagrams for the Type of Service and Network (Code 2)
• Redirect Datagrams for the Type of Service and Host (Code 3)
• Time Exceeded (Type 11)
• Time to Live Exceeded in Transit (Code 0)
• Fragment Reassembly Time Exceeded (Code 1)

218
ICMPv4 Error Messages
• Parameter Problem (Type 12)
• Pointer Indicates the Error (Code 0)
• Required Option is Missing (Code 1)

219
ICMPv4 Informational Messages
• Echo or Echo Reply Message
• Echo Message (Type 8, Code 0)
• Echo Reply Message (Type 0, Code 0)
• Router Solicitation or Router Advertisement message
• Router Solicitation Message (Type 10, Code 0)
• Router Advertisement Message (Type 9, Code 0)
• Timestamp or Timestamp Reply Message
• Timestamp Message (Type 13, Code 0)
• Timestamp Reply Message (Type 14, Code 0)

220
ICMPv4 Informational Messages
• Information Request or Information Reply Message (Deprecated)
• Information Request Message (Type 15, Code 0)
• Information Reply Message (Type 16, Code 0)
• Address Mask Request or Address Mask Reply
• Address Mask Request (Type 17, Code 0)
• Address Mask Reply (Type 18, Code 0)

221
How the ICMP Filtering Works

222
ICMP Filter Chain

/ip firewall filter


add action=jump chain=input jump-target=icmp protocol=icmp
add action=jump chain=forward jump-target=icmp protocol=icmp
add action=accept chain=icmp comment="echo reply" icmp-options=0:0 protocol=icmp
add action=accept chain=icmp comment="net unreachable" icmp-options=3:0 protocol=icmp
add action=accept chain=icmp comment="host unreachable" icmp-options=3:1 protocol=icmp
add action=accept chain=icmp comment="host unreachable fragmentation required" icmp-options=3:4 protocol=icmp
add action=accept chain=icmp comment="allow source quench" icmp-options=4:0 protocol=icmp
add action=accept chain=icmp comment="allow echo request" icmp-options=8:0 protocol=icmp
add action=accept chain=icmp comment="allow time exceed" icmp-options=11:0 protocol=icmp
add action=accept chain=icmp comment="allow parameter bad" icmp-options=12:0 protocol=icmp
add action=drop chain=icmp comment="deny all other types"

223
ICMP Chain Lab
• Add the required ICMP filter rules for your network
• Use Kali to flood your router with ICMP packets
• Check the counters and CPU

sudo hping3 --icmp --flood 10.1.1.x -a 10.1.1.1

ps -aux | grep hping3 – to check who is running the attack

kill [process_id] – to stop hping3

224
ICMP Kernel Protection
icmp_ratelimit (integer; default: 1000)
Limit the maximum rates for sending ICMP
packets whose type matches
icmp_ratemask (see next slide) to specific
targets.
0 to disable any limiting, otherwise the
minimum space between responses in
milliseconds.

225
ICMP Kernel Protection
icmp_ratemask
Mask made of ICMP types for which rates are being limited

Significant bits: IHGFEDCBA9876543210


Default mask: 0000001100000011000 (0x1818)

Bit definitions
0 Echo Reply 3 Destination Unreachable * 4 Source Quench *
5 Redirect 8 Echo Request B Time Exceeded *
C Parameter Problem * D Timestamp Request E Timestamp Reply
F Info Request G Info Reply H Address Mask Request
I Address Mask Reply
226
ICMP Kernel Protection
• There is no need to limit ICMP to the router using firewall rules
• Kernel ICMP limits can be set to limit responses from the router
• Default is 10ms (100/second)
• Rate Mask can be used to set which responses are targeted

/ip settings
set icmp-rate-limit=100 icmp-rate-mask=0x1939

227
ICMP Chain Lab
• Remove the ICMP filter rules
• Set a kernel rate limit of 200 (5/second)
• Use Kali to flood your router with ICMP packets
• Check the counters and CPU

sudo hping3 --icmp --flood 10.1.1.x -a 10.1.1.1

ps -aux | grep hping3 – to check who is running the attack

kill [process_id] – to stop hping3


228
Network Intrusion Types
• Network intrusion is a serious security risk that could result in not
only the temporal denial, but also in total refusal of network services
• We can point out 4 major network intrusion types:
– Ping flood
– Port scan
– DoS attack
– DDoS attack
• In addition, there are the TCP half-scan attacks

229
Ping Flood
• Ping floods usually consist of volumes of random
ICMP messages sent to the router
• We can use the “limit” condition to set the rule
match rate to a given limit
– You can specify a rate/time as well as a burst to allow for
occasional higher traffic
• This condition is often used with the action “log”
• Dst. Limit can be used to set the rate on a per client
or network basis
– This is useful for forward chain limitation

230
Port Scan
• Port Scan is a sequential TCP and (UPD) port
probing
• PSD (Port scan detection) is possible only for TCP
protocol
– UDP is connectionless
• Ports are weighted according to their number
– Low ports from 0 to 1023
– High ports from 1024 to 65535
• Since low ports usually identify more critical
services they are afforded a higher cost per probe
attempt
231 231
Intrusion Protection
• Create Port Scan protection
– Create a PSD drop rule in the chain “virus”
– Place it accordingly
• This makes sense since it is only a TCP service and will be more
efficiently processed via that chain (even though it is not a virus as
such)
• Note that some types of network monitoring services look like port
scan attempts (e.g. The Dude)
– You should exclude PC’s running The Dude from the PSD rule

232
DNS / NTP Amplification Attacks
• DNS amplification is a Distributed Denial of Service (DDoS) attack in
which the attacker exploits vulnerabilities in domain name system (DNS)
servers to turn initially small queries into much larger payloads, which
are used to bring down the victim’s servers.
• DNS amplification is a type of reflection attack which manipulates
publically-accessible domain name systems, making them flood a target
with large quantities of UDP packets.
• Using various amplification techniques, perpetrators can “inflate” the size
of these UDP packets, making the attack so potent as to bring down even
the most robust Internet infrastructure
• NTP can be similarly compromised if internal service have publicly
available IP addresses

233
DNS / NTP Amplification Attacks
• For most networks incoming DNS and NTP is not required
– The only exception is if you are running authoritative DNS servers inside
your network
• Remember that UDP 53 and 123 is only required on outgoing
connections, the return reply will go to a randomly generated source
port
• Best practise is to block all incoming UDP:53 and UDP:123 traffic on
both forward and input chains at the edge firewalls

234
Common Amplification Ports
REFLECTED AMPLIFIED ATTACK TYPE ATTACK SOURCE PORT RECOMMENDED MITIGATION STRATEGY
BitTorrent UDP 6881 Block source port
CharGEN UDP 19 Block source port
CLDAP UDP 389 Block source port
DNS UDP 53 Block source port with exclusion
Kad (P2P) UDP 751 Block source port
Memcached UDP 11211 Block source port
MSSQL UDP 1434 Block source port
Multicast DNS UDP 5353 Block source port
NetBIOS UDP 137 Block source port
NTP UDP 123 Block source port with exclusion
Portmap (RPCbind) UDP 111 Block source port
QOTD UDP 17 Block source port
Quake Network Protocol UDP 27960 Block source port
RIPv1 UDP 520 Block source port
SNMP UDP 161 Block source port with exclusion
SSDP UDP 1900 Block source port
235
Steam Protocol UDP 27015 Block source port
DoS Attacks
• The main target for DoS attacks is
consumption of resources, such as CPU time
or bandwidth, so that standard services or
Normal Session
valid systems requesting resources will get
Denial of Service
• Usually the router is flooded with TCP/SYN
(connection request) packets. Causing the
server to respond with a TCP/SYN-ACK packet,
and waiting for a TCP/ACK packet
• Mostly DoS attackers are virus infected
customers

236
Denial of Service
DoS Attack Protection
• All IP's with more than 10 connections to the router (input) should
be considered as DoS attackers
• With every dropped TCP connection we will allow the attacker to
create a new connection
• We should implement DoS protection into 2 steps:
– Detection - Creating a list of DoS attackers on the basis of connection-limit
– Suppression – applying restrictions to the detected DoS attackers
• Connection Limit allows you to match a number of connections by
netmask size (/32 to match per IP)

237
DoS Attack Detection

238
DoS Attack Suppression
• To prevent the attacker from creating a new
connections, we will use action=“tarpit”
• Tarpit sends a SYN-ACK back to the attacking
system, but silently discards the connection
• We must place this rule before the
detection rule otherwise the address-list
entry will rewrite continuously

239
About SYN floods
• A Distributed Denial of Service attack is very similar to DoS attack but it
occurs from multiple compromised systems
– Usually these systems would be virus infected “drones”
• A SYN flood is simply a series of SYN packets from forged IP addresses
– The IP addresses are chosen randomly and don't provide any hint of where the
attacker is
– This means standard methods for detection by connection limit will be ineffective
• The SYN flood keeps the server's SYN queue full. Normally this would
force the server to drop connections.
• A server that uses SYN cookies, however, will continue operating
normally
– You can enable TCP SynCookie in IP à Settings

240
TCP SynCookie
DDoS Attack

241
TCP Null Scan
• A Null Scan is a series of TCP packets that contain a sequence number of
0 and no set flags
– In a production environment, there will never be a TCP packet that doesn’t
contain a flag
– Because the Null Scan does not contain any set flags, it can sometimes penetrate
firewalls and edge routers that filter incoming packets with particular flags.
• The expected result of a Null Scan on an open port is no response
– Since there are no flags set, the target will not know how to handle the request
– It will discard the packet and no reply will be sent
– If the port is closed, the target will send an RST packet in response
• This will not be detected by standard Port Scan Detection
• Other scans such as TCP Xmas scan and TCP Half scan exhibit similar
properties
242
Advanced PSD
/ip firewall filter
add chain=input protocol=tcp tcp-flags=fin,!syn,!rst,!psh,!ack,!urg action=add-src-
to-address-list address-list="port scanners" address-list-timeout=2w comment="NMAP
FIN Stealth scan“
add chain=input protocol=tcp tcp-flags=fin,syn action=add-src-to-address-list
address-list="port scanners" address-list-timeout=2w comment="SYN/FIN scan“
add chain=input protocol=tcp tcp-flags=syn,rst action=add-src-to-address-list
address-list="port scanners" address-list-timeout=2w comment="SYN/RST scan“
add chain=input protocol=tcp tcp-flags=fin,psh,urg,!syn,!rst,!ack action=add-src-
to-address-list address-list="port scanners" address-list-timeout=2w
comment="FIN/PSH/URG scan“
add chain=input protocol=tcp tcp-flags=fin,syn,rst,psh,ack,urg action=add-src-to-
address-list address-list="port scanners" address-list-timeout=2w comment="ALL/ALL
scan“
add chain=input protocol=tcp tcp-flags=!fin,!syn,!rst,!psh,!ack,!urg action=add-
src-to-address-list address-list="port scanners" address-list-timeout=2w
comment="NMAP NULL scan" 243
Firewall Raw
• Firewall RAW table allows to selectively bypass or drop packets before
connection tracking that way significantly reducing load on CPU
• Tool is very useful for DOS attack mitigation
• RAW table does not have matchers that depend on connection tracking
– connection-state, layer7 etc.
• If packet is marked to bypass connection tracking packet de-
fragmentation will not occur
• Can also be used to bypass fasttrack
– E.g. still allow some queues to operate
• Use Interface Lists to set public incoming interfaces to control and limit
unwanted traffic
244
Prerouting/Output packet flow
notrack

notrack

245
Firewall Raw 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
• Actions are the same for other firewall rules except for notrack
– Notrack allows the packet to bypass connection tracking entirely
– This allows queues to still be processed when fastrack is enabled
– This will also bypass NAT functions
246
Bypass Fastrack by Address List

247
Protection from DNS Amplication

248
DNS DoS
To perform DNS Amplification attack :

su
cd /root
./dnsdrdos -f dns-servers.list -l 50000

*where dns-servers.list is the victim's IP address and l- 50000 is how many


recursions to run

To scan for an open recursive DNS server :


perl find_open_resolvers.pl '1.0.0.0 - 1.84.255.255' -q 1000

249
TCP SYN Attack

SYN

SYN-ACK

• This type of attack takes advantage of the three-way


handshake to establish communication
• In SYN flooding, the attacker sends the target a large number
of TCP/SYN packets.
• These packets have a source address, and the target computer
replies (TCP/SYN-ACK packet) back to the source IP, trying to
establish a TCP connection

250
TCP SYN Attack

• Scanning available ports on target, commonly used target is


80/http service

251
TCP SYN Attack

• Download and install “hping3” and run command bellow

252
TCP SYN Attack

• “IP > Firewall > Connections” please observe the “syn sent”
from random source addresses

253
TCP SYN Attack

• Torch interface traffic

254
TCP SYN Attack

• The attack is exhausting the resources of the router and


impacting the performance

tool profile freeze-frame-interval=1 system resource cpu print

255
Preventing TCP SYN Attack

• Rate-limiting for each new tcp connection


• Reduce syn-received timer
• And setup tcp syn-cookies

256
Preventing TCP SYN Attack

• Creating firewall for preventing tcp SYN flood

/ip firewall filter


add action=jump chain=forward comment="SYN Flood protect FORWARD" connection-state=new jump-
target=syn-attack protocol=tcp tcp-flags=syn
add action=jump chain=input comment="SYN Flood protect INPUT" connection-state=new jump-target=syn-
attack protocol=tcp tcp-flags=syn
add action=accept chain=syn-attack connection-state=new limit=400,5:packet protocol=tcp tcp-flags=syn
add action=drop chain=syn-attack

257
Preventing TCP SYN Attack

• IP > Settings and enable “TCP


SynCookies”

/ip settings set tcp-syncookies=yes

258
TCP SYN Attack

• Run hping3 again

259
Preventing TCP SYN Attack

• These rules are stopping the tcp SYN attack, but still affecting
the CPU resources. (need more powerful router for preventing)

260
Syn DOS Protection
• Test TCP SYN denial of service on your router
• Configure necessary firewall rules to prevent SYN flood
overload

sudo hping3 -c 15000 -d 120 -S -w 64 -p 80 --flood -


-rand-source 10.1.1.x

261
Firewall Filter drop SYN incoming
/ip firewall filter
add action=drop chain=input protocol=tcp tcp-flags=syn,!ack in-
interface=ether1

262
263
RAW Table SYN Flood Drop
/ip firewall raw
add chain=prerouting action=drop tcp-flags=syn,!ack protocol=tcp in-
interface=ether1

264
RAW Protection
• Add SYN drop rules to the firewall filter on the group router and check results
with flood ping
• Add the rule to firewall raw and check results again

sudo hping3 -c 15000 -d 120 -S -w 64 -p 80 --flood --rand-source


10.1.1.x

https://linuxhint.com/hping3/

ps -aux | grep hping3 – to check who is running the attack

265
Simple Edge Firewall Protection
https://github.com/MikroTikSA/edge-firewall-
ROSv7/blob/main/Edge_Firewall_V7_3.rsc

• Provides an easy to setup firewall for edge router applications


• Trainer will take you through the setup

266
MikroTik as IDS / IPS
• You can run MikroTik as an IDS/IPS hybrid on a single router by combining
connection based and RAW table rules
• The idea is to detect the unwanted traffic in the firewall filter or mangle chain
• The detected bad traffic is then added to an address list
• Then we drop the traffic using firewall RAW chain rules
• This will still place quite a load on the router but can be a cost effective
solution on smaller networks
• ROS7 now features hardware based firewalling on certain CRS3xx series
switches which can offload firewall functions at a switch level with no CPU load

267
MikroTik as IPS with IDS Trigger
• MikroTik can be combined with a Linux based detection system
to provide cost effective IDS/IPS functions
• Idea is to mirror traffic to IDS in some way so that detection
can occur
• Then update the MT firewall to drop traffic from detected IP
addresses

Traffic Sniffer
Linux Snort Box / VM
Mirror Traffic

45.1.0.2

Switch Edge Firewall 268


Switch Port Mirror

• CRS3xx (and some other) switches can do port based mirroring


• Enable the setting in the Switch menu
• You can do a simple ingress/egress mirror, or create more
advanced rules to mirror multiples ports and VLAN’s

269
Traffic Flow
• Traffic diverted by the switch needs to be sent to the MT sniffer
and then on to the Linux Snort box
• Tool à Packet Sniffer allows you to stream a flow of traffic to
an external device

270
Linux Snort
• Snort is a free Linux package that allows processing of data streams
against pre-defined recognition patterns
• It has a built in IPS feature, but needs to be installed inline for that
to work
• However, with some additional scripting we can get the Snort box to
update our IPS firewall using the API
• https://wiki.mikrotik.com/wiki/Mikrotik_IPS_IDS provides scripts
and examples to get your Snort system working with your MikroTik
firewall
• Also check out Stamus Networks | SELKS (stamus-networks.com)
which is a Suricata-based IDS with MikroTik scripts available
271
Network Address Translation
Other NAT functions
• We are already familiar with the standard NAT functions
– Srcnat/masquerade – modify the source IP and/or port
– Dstnat/redirect – modify the destination IP and/or port
• There are 2 other NAT actions we can examine
– Netmap – create a bulk range nat
– Same – maintain the same natting per client ip/dst pair

273
NAT Action “Netmap”
• Can be used in both srcnat and dstnat chains
• used to create address range to address range NAT only with one
rule
• It is possible to masquerade 192.168.0.3-192.168.0.103 (100
addresses) to 88.188.32.3-88.188.32.103 only with one rule
• It is possible to redirect 88.188.32.3-88.188.32.103 (100 addresses)
to 192.168.0.3-192.168.0.103 with the second rule

274
NETMAP

275
NAT Action “same”
• Can be used in both srcnat and dstnat chains
• Ensures that client will be NAT'ed to the same address from the
specified range every time it tries to communicate with destination
that was used before
• If client got 88.188.32.104 from the range when it communicated
to a particular server – all future communication with this server
will use the same address

276
SAME

277
Hairpin NAT
• Hairpinning (or NAT loopback)
describes a communication
between two hosts behind the
same NAT device using their
mapped endpoint
• Hairpinning is where a machine on
the LAN is able to access another
machine on the LAN or DMZ via
the external IP address of the
LAN/router (with port forwarding
set up on the router to direct
requests to the appropriate
machine on the LAN).
278
DST NAT

279
Hairpinning
• The issue is that when the internal device replies back it will send
the response directly via the local network
• This will create a network loop issue since the sender is expecting a
response from the external (public) IP
• The solution is to ensure that requests from the internal network to
the DMZ are also natted behind the public IP so that responses are
sent back via the same path

280
Hairpin NAT

281
Firewall Mangle

IP packet marking and IP header fields adjustment

282
What is Mangle?
• The mangle facility allows to mark IP packets with special marks.
• These marks are used by other router facilities to identify the packets.
• Additionally, the mangle facility is used to modify some fields in the IP header,
like TOS (DSCP) and TTL fields.
• The firewall mangle facility is a tool for packet marking
• Firewall Mangle consists of a sequence of IF-THEN rules
0) IF <condition(s)> THEN <action>
1) IF <condition(s)> THEN <action>
• If a packet doesn't meet all the conditions of the rule, it will be sent on to the
next rule.
• If a packet meet all the conditions of the rule, then the specified action will be
taken on it. 283
Mangle Structure
• Mangle rules are organized in chains
• There are five built-in chains:
– Prerouting- make a mark before Global-In queue
– Postrouting - make a mark before Global-Out queue
– Input - make a mark before Input filter
– Output - make a mark before Output filter
– Forward - make a mark before Forward filter
• New user-defined chains can be added, as necessary
• Unlike Firewall Filter and Firewall NAT, you can choose whether to
passthrough the packet for further processing after a match has been
made and an action carried out on the packet
284
Mangle Diagram

285
Mangle actions
• There are 7 additional actions in the mangle system:
– mark-connection – mark connection (only first packet)
– mark-packet – mark a flow (all packets)
– mark-routing - mark packets for policy routing
– change MSS - change maximum segment size of the packet
– change TOS - change type of service
– change TTL - change time to live
– strip IPv4 options

286
Marking Connections
• Use mark connection to identify one or a group of connections with a
specific connection mark
• Connection marks are stored in the connection tracking table
• There can be only one connection mark per connection
– Use the passthrough checkbox to limit packet processing
• Connection tracking helps to associate each packet to a specific
connection (connection mark)
• Marking connections before dropping them in the firewall can be more
efficient because only the first packet needs to be evaluated
• The same connection mark can be applied with different packet
identifiers to group connections together
287
Mark Connection Rule

288
Marking Packets
• If you want to use Queue Trees or you want to limit traffic in a simple
queue by means of protocol identifiers then you will need to use packet
marks
– Sometimes also called a flow mark since it marks a flow of traffic
• Packets can be marked
– Indirectly: Using the connection tracking facility, based on previously created
connection marks. Since the router does not have to examine each packet header
individually (since it picked it up from the connection mark) the processing will be
much faster and consume far less CPU resources.
– Directly: Without the connection tracking - no connection marks are needed, the
router will compare each packet to a given conditions (this process imitates some
of the connection tracking features)

289
Mark Packet Rule

290
Mangle Lab
• Disable the virus chain rules in IP Firewall Filter
• Import the mangle_chain script from the trainer router
• Add 2 mangle rules to process tcp and udp traffic through the correct chains
– Remember to return out of the chains
• Add rules to the firewall filter to log and drop all traffic intercepted by the mangle
chain
• Label all the rules correctly
• How can additional virus rules be easily added?
• Add a rule to bypass the checklist for certain IP’s by Address List “firewall_bypass”
• Add a mangle to the virus chain for HTTP connections
• Has web browsing been blocked?
• Add your laptop IP to firewall_bypass list and test browsing again

291
Other uses for Mangle
• Load balancing using PCC (per connection checking)
• Load balancing protocols using Policy Routing, ECMP and Mangle
• Marking Layer7 traffic for identification using RegExp
• Marking traffic for QOS using Simple and Tree Queues
• Adding certain traffic types to address list automatically for further
processing
• Any situation where identifying and grouping similar traffic types is
required

292
Layer7 Filter
• layer7-protocol is a method of searching for patterns in ICMP/TCP/UDP streams.
– Note: The L7 matcher is very resource intensive. Use this feature only for very specific traffic. It is not
recommended to use L7 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
• L7 matcher 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 as unknown.
– You should take into account that a lot of connections will significantly increase memory and CPU usage.
To avoid this, add regular firewall matchers to reduce amount of data passed to layer-7 filters repeatedly.
• Additional requirement is that layer7 matcher must see both directions of traffic
– To satisfy this requirement l7 rules should be set in forward chain.
• Example L7 patterns compatible with RouterOS can found in l7-filter project page
• http://l7-filter.sourceforge.net/protocols
• List of common protocols here. Open the archive and find the required protocol or file pattern and
use them in your L7 filter rules.
• http://www.mikrotik.com/download/share/l7_protocols_may_2009.zip
293
L7 Implementation

• Add the pattern matcher in


firewall L7 filter
• Apply in Mangle / Filter as
required
• Add rules before the detection
rule to accept common traffic
types to avoid excessive
processing

294
TCP-MSS
• MikroTik includes an auto MSS adjustment when tunnels are created
to/from the router
– MSS adjustment happens on TCP SYN packet at the beginning of handshake
negotiation
• In some cases where there are more tunnels further up the line or where
TCP fragmentation is occurring it will be impossible for the router to
determine end-to-end MSS values
– Typical symptoms: slow download, banking sites don’t work properly, many
phone apps give issues esp messaging e.g. Whatsapp, Telegram
• In this case manual MSS adjustment may be required to allow
unfragmented packets
– Can sometimes be a trial and error adjustment
295
Mangle MSS adjustment

296
Module 3

OSI LAYER ATTACKS


UDP Flood Attack

• An UDP flood does not exploit any vulnerability.


• The aim of UDP floods is creating and sending large amount
of UDP datagrams from spoofed IP’s to the target server.
• When a server receives this type of traffic, it is unable to
process every request and it consumes its bandwidth with
sending ICMP “destination unreachable” packets.

298
UDP Flood Attack

• Scanning available port on target, commonly used target is


53/dns service

299
UDP Flood Attack

• Start attacking UDP protocol port 53(dns) with hping3

300
UDP Flood Attack

• “IP > Firewall > Connections” please observe “udp” protocol


from random source addresses

301
UDP Flood Attack

• Torch interface traffic

302
UDP Flood Attack

• The attack is exhausting the resources of the router and


impacting the performance

303
Preventing UDP Flood Attack

• Disable DNS forwarder on MikroTik if not required.


• If “IP -> DNS” – Allow remote request is enabled, make sure
appropriate filter rule is set to prevent incoming DNS attacks.
• Rate-limiting for each new udp connection.

304
Preventing UDP Flood Attack

• Uncheck Allow Remote


Requests on router

305
Preventing UDP Flood Attack

• Block dns request “udp/53” traffic from outside

/interface list add name=OUTSIDE


/interface list member add interface=ether3-internet list=OUTSIDE

/ip firewall raw add action=drop chain=prerouting dst-port=53 in-interface-list=OUTSIDE protocol=udp

306
Preventing UDP Flood Attack

• Rate-limiting every udp/53 packet requests

/ip firewall raw


add action=accept chain=prerouting dst-port=53 in-interface-list=!OUTSIDE limit=100,5:packet protocol=udp
add action=drop chain=prerouting dst-port=53 in-interface-list=!OUTSIDE protocol=udp

307
ICMP Smurf Attack

• This type of attack uses large amount of Internet Control


Message Protocol (ICMP) ping traffic targeted at an Internet
Broadcast Address e.g 192.168.1.255.
• The reply IP address is spoofed to that of the intended victim
e.g 1.2.3.4
• All the replies are sent to the victim instead of the IP used for
the pings.
• Since a single Internet Broadcast Address can support a
maximum of 255 hosts, a smurf attack amplifies a single ping
255 times.

308
ICMP Smurf Attack

• Start attacking ICMP smurf with random source

309
ICMP Smurf Attack

• All of attacker’s traffic as a destination address has the


broadcast address of the network

310
ICMP Smurf Attack

311
ICMP Smurf Attack

• The attack is exhausting the resources of the router and


impacting the performance

312
Preventing ICMP Smurf Attack

• Configure routers not to forward or accept packets directed to


broadcast addresses.
• Configure individual hosts or routers to not respond to ping
requests from outside

313
Preventing ICMP Smurf Attack

/ip firewall filter


add action=drop chain=input dst-address-type=broadcast icmp-options=0:0-255 protocol=icmp
add action=drop chain=input in-interface-list=OUTSIDE protocol=icmp

314
Password Brute Force Attack

• A brute force attack is a trial-and-error method used to obtain


information such as a users password or any other credential
information.
• In a brute force attack, automated software is used to
generate a large number of consecutive guesses as to the
value of the desired data.

315
Password Brute Force Attack

• Router under SSH Brute Force Attack

316
Password Brute Force Attack

• Router under Telnet Brute Force Attack

317
Preventing Brute Force Attack

• Limiting the number of times a user can unsuccessfully


attempt to log in
• Temporarily locking out users who exceed the specified
maximum number of failed login attempts
• Requiring users to create complex passwords
• Periodically changing a password

318
Preventing Brute Force Attack

319
Preventing Brute Force Attack

/ip firewall filter


add action=drop chain=input comment="Drop SSH Brute Forcers" dst-port=22 protocol=tcp \
src-address-list=brute-force_blacklist
add action=add-src-to-address-list address-list=brute-force_blacklist address-list-timeout=1d chain=input \
connection-state=new dst-port=22,23 protocol=tcp src-address-list=bruteforce_stage3
add action=add-src-to-address-list address-list=bruteforce_stage3 address-list-timeout=30s chain=input \
connection-state=new dst-port=22,23 protocol=tcp src-address-list=bruteforce_stage2
add action=add-src-to-address-list address-list=bruteforce_stage2 address-list-timeout=30s chain=input \
connection-state=new dst-port=22,23 protocol=tcp src-address-list=bruteforce_stage1
add action=add-src-to-address-list address-list=bruteforce_stage1 address-list-timeout=1m chain=input \
connection-state=new dst-port=22,23 protocol=tcp

320
Port Scanner Detection

• A port scan is a method for determining which ports on a


network are open or available.
• Running a port scan on a network or server reveals which
ports are open and listening (receiving information)
• Port Scan tools (like NMAP) can detect what version of an
application is running on a port
• Port scanning is the “gate” for starting an attack or
penetration to your networks

321
Port Scanner Detection

• Scanning available ports on the target

322
Preventing Port Scanner

• Create Port Scanner Detection on router and block the


address

323
Preventing Port Scanner

/ip firewall filter


add action=drop chain=input src-address-list="port scanners"
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2w chain=input
comment="Port scanners to list " protocol=tcp psd=21,3s,3,1
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2w chain=input
comment="NMAP FIN Stealth scan" protocol=tcp tcp-flags=\
fin,!syn,!rst,!psh,!ack,!urg
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2w chain=input
comment="SYN/FIN scan" protocol=tcp tcp-flags=fin,syn
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2w chain=input
comment="SYN/RST scan" protocol=tcp tcp-flags=syn,rst
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2w chain=input
comment="FIN/PSH/URG scan" protocol=tcp tcp-flags=\
fin,psh,urg,!syn,!rst,!ack
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2w chain=input
comment="ALL/ALL scan" protocol=tcp tcp-flags=\
fin,syn,rst,psh,ack,urg
add action=add-src-to-address-list address-list="port scanners" address-list-timeout=2w chain=input
comment="NMAP NULL scan" protocol=tcp tcp-flags=\
!fin,!syn,!rst,!psh,!ack,!urg

324
Module 4
CRYPTOGRAPHY

325
What is Cryptography

• Cryptography is the "ART" of creating documents that can be


shared secretly over public communication.
• Traditionally, cryptography refers to :
• The practice and the study of encryption.
• Transforming information in order to prevent unauthorized
people to read it.
• But today, cryptography goes beyond encryption/decryption
to include :
• Techniques for making sure that encrypted messages are not
modified.
• Techniques for secure identification/authentication of
communication partners.

326
Security Mechanisms
Encryption :
• Process of transforming plaintext to ciphertext using a
cryptographic key
• Used all around us
• In Application Layer – used in secure email, database sessions, and
messaging
• In session layer – using Secure Socket Layer (SSL) or Transport Layer
Security (TLS)
• In the Network Layer – using protocols such as IPsec
• Benefits of good encryption algorithm:
• Resistant to cryptographic attack
• They support variable and long key lengths and scalability
• They create an avalanche effect
• No export or import restrictions

327
Terminology
plaintext (P) : the original message
ciphertext (C) : the coded message
cipher : algorithm for transforming plaintext to cipher text
key (k) : info used in cipher known only to sender/receiver
encipher/encrypt (e) : converting plaintext to cipher text
decipher/decrypt (d) : recovering cipher text from plaintext
cryptography : study of encryption principles/methods
cryptanalysis : the study of principles/ methods of deciphering
cipher text without knowing key
cryptology : the field of both cryptography and cryptanalysis

328
Encryption Methods
There are 2 kinds of encryption methods :
• Symmetric cryptography
• Sender and receiver keys are identical
• Asymmetric (public-key) cryptography
• Encryption key (public), decryption key secret (private)

329
Symmetric Encryption
• Uses a single key to both encrypt and decrypt information
• Also known as a secret-key algorithm
• The key must be kept a “secret” to maintain security
• This key is also known as a private key
• Follows the more traditional form of cryptography with key
lengths ranging from 40 to 256 bits

330
Symmetric Key Algorithms

331
Asymmetric Encryption
• Also called public-key cryptography
• Keep private key private
• Anyone can see public key
• Separate keys for encryption and decryption (public and
private key pairs)
• Examples of asymmetric key algorithms:
• RSA, DSA, Diffie-Hellman, El Gamal, Elliptic Curve and PKCS

332
Asymmetric Encryption

• RSA : the first and still most common implementation


• DSA : specified in NIST’s Digital Signature Standard (DSS),
provides digital signature capability for authentication of
messages
• Diffie-Hellman : used for secret key exchange only, and not
for authentication or digital signature
• ElGamal : similar to Diffie-Hellman and used for key exchange
• PKCS : set of interoperable standards and guidelines

333
Public Key Infrastructure (PKI)

• Framework that builds the network of trust


• Combines public key cryptography, digital signatures, to
ensure confidentiality, integrity, authentication, non-
repudiation, and access control
• Protects applications that require high level of security
Functions of a PKI :
• Registration • Key generation
• Initialization • Key update
• Certification • Cross-certification
• Key pair recovery • Revocation

334
Components of a PKI

• Certificate authority
• The trusted third party
• Trusted by both the owner of the certificate and the party relying
upon the certificate.
• Validation authority
• Registration authority
• For big CAs, a separate RA might be necessary to take some work off
the CA
• Identity verification and registration of the entity applying for a
certificate
• Central directory

335
CERTIFICATES

336
Certificates
• Public key certificates bind public key values to subjects
• A trusted certificate authority (CA) verifies the subject’s
identity and digitally sign each certificate
• Validates
• Has a limited valid lifetime
• Can be used using untrusted communications and can be
cached in unsecured storage
• Because client can independently check the certificate’s signature
• Certificate is NOT equal to signature
• It is implemented using signature
• Certificates are static
• If there are changes, it has to be re-issued

337
Digital Certificates

• Digital certificate – basic element of PKI; secure credential


that identifies the owner
• Also called public key certificate
• Deals with the problem of
• Binding a public key to an entity
• A major legal issue related to
e-commerce
• A digital certificate contains :
• User’s public key
• User’s ID
• Other information e.g. validity period

338
Digital Certificates

• Certificate examples :
• X509 (standard)
• PGP (Pretty Good Privacy)
• Certificate Authority (CA) creates and digitally signs certificates
• To obtain a digital certificate, Alice must :
• Make a certificate signing request to the CA
• CA returns Alice’s digital certificate, cryptographically binding
her identity to public key :
• CertA = {IDA, KA_PUB, info, SigCA(IDA,KA_PUB,info)}

wiki.apnictraining.net/_media/apnic44/apnic44-crypto_pgp.pdf, slide #55

339
X.509

• An ITU-T standard for a public key infrastructure (PKI) and


Privilege Management Infrastructure (PMI)
• Assumes a strict hierarchical system of Certificate Authorities
(CAs)
• RFC 1422 – basis of X.509-based PKI
• Current version X.509v3 provides a common baseline for the
Internet
• Structure of a certificate, certificate revocation (CRLs)

340
X.509

X.509 Certificate Usage:


• Fetch certificate
• Fetch certificate revocation list
(CRL)
• Check the certificate against the
CRL
• Check signature using the
certificate

341
Every Certificate Contains
• Body of the certificate
• Version number, serial number, names of the issuer and subject
• Public key associated with the subject
• Expiration date (not before, not after)
• Extensions for additional attributes
• Signature algorithm
• Used by the CA to sign the certificate
• Signature
• Created by applying the certificate body as input to a one-way hash
function. The output value is encrypted with the CA’s private key to
form the signature value

342
Certificate Authority
• Issuer and signer of the certificate
• Trusted (Third) Party
• Based on trust model
• Who to trust?
• Types:
• Enterprise CA
• Individual CA (PGP)
• Global CA (such as VeriSign)
• Functions :
• Enrols and Validates Subscribers
• Issues and Manages Certificates
• Manages Revocation and Renewal of Certificates
• Establishes Policies & Procedures

343
Certificate Revocation List

• CA periodically publishes a data structure called a certificate


revocation list (CRL)
• Described in the X.509 standard
• Each revoked certificate is identified in a CRL by its serial
number
• CRL might be distributed by posting on a known web URL or
from CA’s own X.500 directory entry

344
SELF-SIGNED
CERTIFICATES

345
Self-Signed Certificates

• A self-signed SSL certificate does not use the chain of trust


commonly used by other SSL certificates
• Is an identity certificate that is signed by the same entity
whose identity it certifies
• Most often used when a company wants to perform internal
testing without the effort or expense of acquiring a standard
SSL certificate.

346
Self-Signed Certificates

certificate add name=CA country=ES state=Toledo locality=Illescas organization=IT unit=IT common-name=example.com \


subject-alt-name=DNS:example.com key-size=2048 days-valid=365 \
key-usage=digital-signature,key-encipherment,data-encipherment,key-cert-sign,crl-sign

347
Self-Signed Certificates

certificate sign CA name=CA

348
Self-Signed Certificates

certificate add name=www country=ES state=Toledo locality=Illescas organization=IT unit=IT \


common-name=webfix.example.com subject-alt-name=DNS:webfix.example.com key-size=2048 days-valid=365 \
key-usage=digital-signature,key-encipherment,tls-client,tls-server

349
Self-Signed Certificates

certificate sign www name=www ca=CA

350
FREE OF CHARGE
VALID
CERTIFICATES
351
Let’s Encrypt

• Let's Encrypt is a new Certificate Authority (CA) that offers


FREE SSL certificates that are just as secure as current paid
certificates.
• Let’s Encrypt is a free certificate authority developed by the
Internet Security Research Group (ISRG).
• SSL certificates are issued for a period of 90 days, and need
to renew for validity issue.
• These certificates are domain-validated, don't require a
dedicated IP and are supported on all SiteGround hosting
solutions.

352
Let’s Encrypt
Key benefits of using a Let’s Encrypt SSL certificate:
• It's free – Anyone who owns a domain can obtain a trusted
certificate for that domain at zero cost.
• It's automatic – The entire enrolment process for certificates
occurs during the server’s native installation or configuration
process. The renewal occurs automatically in the background.
• It's simple – There's no payment, no validation emails, and
certificates renew automatically.
• It's secure – Let’s Encrypt serves as a platform for implementing
modern security techniques and best practices.
• More info – https://letsencrypt.org

353
SSL For Free

https://www.sslforfree.com

354
SSL For Free

355
SSL For Free

356
SSL For Free

357
Free of Charge Valid Certificates

Upload “certificate.crt” and “private.key” to the RouterOS

358
Free of Charge Valid Certificates

“System > Certificate”: import both the “certificate.crt” and the “private.key”

359
Free of Charge Valid Certificates

360
Lets Encrypt
• MikroTik ROSv7 now offers auto certificate generation for the www-
ssl service
/certificate> enable-ssl-certificate dns-
name=daveshome.gignet.co.za
progress: [success] ssl certificate updated

361
362
363
Certificate Management
• MikroTik includes a Certificate menu
System à Certificates for adding and self
signing certificates
• Certificates can be created manually or
imported as required
• To add a self signed client/server pair:
• Create a new CA cert with at least Name
and Common Name parameters
– Key Usage is CRL Sign and Key Cert Sign

364
Certificate Sign
• Sign the Cert using the Sign option, CA CRL
Host is the IP of the server
– Cert should have the KLAT flags set at this
point
• Create new Server and Client cert with at
least Name and Common Name
parameters
– key-usage=digital-signature, key-
encipherment, data-encipherment, key-cert-
sign, crl-sign,tls-server, tls-client
• Sign the Certs and set as trusted
– Use the CA created earlier
365
Using Certificates
• Create exports of Client and Server
certs as required
– Export cert and key files will be created on
router filesystem
• Copy to target router and import both
the cert and the key from the Certificate
menu
• Cert should have the KT flags once
imported

366
SSTP Setup
• Enable SSTP server using the created
profile
– Authentication method is not
important
• Specify Certificate if available
• Force AES if RC4 is not wanted
– Possible Windows compatibility issues
• On client setup only verify
certificates if domains are properly
setup
367
Certificate Lab
• Create a signed CA as per the previous examples
• Create signed client and server certificates
• Export the client cert and import on partners router

368
TUNNELING
THROUGH SSH

369
What is an SSH Tunnel

• An SSH tunnel consists of an encrypted tunnel created using


the SSH protocol connection
• The SSH tunnel can be used to encapsulate unencrypted
traffic and transmit it via an encrypted channel.
• SSH Port Forwarding must be enabled on the router

/ip ssh set forwarding-enabled=both

370
How SSH Works

Host connects to RouterOS using ssh with


local-port forwarding parameter

RouterOS accepted ssh connections from host

Host trying to open unencrypted port (80) from


ssh tunnel via local-port forwarding ip

RouterOS sending http request from host via


ssh tunnel

371
Configuring the SSH tunnel

SSH Local-Forwarding for Windows

SSH Local-Forwarding for Linux


ssh –L 80:127.0.0.1:80 your.router.ip-or-domain

372
Configuring the SSH tunnel

373
SSH Tunnel Lab
• Configure SSH tunnel to router as per the walkthrough above
• Test by trying to connect to the routers web interface (ensure
service is enabled)

putty -L 80:127.0.0.1:80 192.168.1.254

374
Module 6
SECURE TUNNELS

375
L2TP/IPsec

376
What is L2TP/IPsec
• L2TP stands for Layer 2 Tunnelling Protocol. L2TP was first proposed in
1999 as an upgrade to both L2F (Layer 2 Forwarding Protocol) and
PPTP (Point-to-Point Tunnelling Protocol)
• Because L2TP does not provide strong encryption or authentication by
itself, another protocol called IPsec is most often used in conjunction
with L2TP
• Used together, L2TP and IPsec is much more secure than PPTP (Point-
to-Point Tunnelling Protocol), but also slightly slower

377
What is L2TP/IPsec
• L2TP/IPSec offers high speeds, and high levels of security for
transmitting data
• It generally makes use of AES ciphers for encryption
• L2TP sometimes has problems traversing firewalls due to its use of
UDP port 500 which some firewalls have been known to block by
default

378
Lab Setup

INTERNET

R1
L2TP/IPsec

379
Setup L2TP/IPsec Server

/interface l2tp-server server set authentication=mschap1,mschap2 \


enabled=yes ipsec-secret=84GsvZAtUQnE use-ipsec=yes

380
Setup L2TP/IPsec Server

/ppp secret add name=demo password=demo local-address=10.0.0.1 \


remote-address=10.0.0.11 profile=default-encryption service=l2tp

381
Setup L2TP/IPsec Client

382
Setup L2TP/IPsec Client

383
Setup L2TP/IPsec Client

384
Setup L2TP/IPsec Client

385
Setup L2TP/IPsec Client

386
L2TP with IPSEC Lab
• Setup L2TP server and client in the group as appropriate
– Modify profile as required
– Create PPP secrets for dial in users
– Enable the L2TP Server with the selected profile and an IPSEC Secret
– Test the config between routers

387
SSTP

388
What is SSTP
• Microsoft introduced Secure Socket Tunnelling Protocol (SSTP) in
Windows Vista and it still considered to be a Windows-only platform
even though it is available on a number of other operating systems.
• It has very similar advantages as OpenVPN as SSTP uses SSLv3 and it has
greater stability as it is included with Windows which also makes it
simpler to use.
• It uses the same port used by SSL connections; port 443.
• It uses 2048 bit encryption and authentication certificates.
• SSTP uses SSL transmissions instead of IPsec because SSL supports
roaming instead of just site-to-site transmissions.
• RouterOS has both the SSTP server and client implementation
389
SSTP Operation

tcp connection
ssl negotiation

SSTP over HTTPS

IP binding

SSTP tunnel

390
SSTP Operation
• TCP connection is established from client to server (by default on port
443)
• SSL validates server certificate. If certificate is valid connection is
established otherwise connection is torn down
– Note: Two RouterOS devices can establish an SSTP tunnel even without the use of
certificates (not in accordance with Microsoft standard)
• The client sends SSTP control packets within the HTTPS session which
establishes the SSTP state machine on both sides
• PPP negotiation over SSTP: Client authenticates to the server and binds IP
addresses to SSTP interface
• SSTP tunnel is now established and packet encapsulation can begin.
391
SSTP Setup

INTERNET

R1
SSTP

392
Self Signed Certificate

certificate add name=sstp country=ES state=Toledo locality=Illescas organization=IT unit=IT \


common-name=sstp.example.com subject-alt-name=DNS:sstp.example.com key-size=2048 days-valid=365 \
key-usage=digital-signature,key-encipherment,tls-client,tls-server

/ certificate sign sstp name=sstp ca=CA


/ certificate set sstp trusted=yes

393
Setup SSTP Server

/interface sstp-server server set authentication=mschap1,mschap2 certificate=sstp default-profile=default-encryption \


enabled=yes force-aes=yes

394
Setup SSTP Server

sstp

/ppp secret add name=demo password=demo local-address=10.0.0.1 remote-address=10.0.0.11 \


profile=default-encryption service=sstp

395
Setup SSTP Server

SSTP Server

396
Setup SSTP Client

397
Setup SSTP Client

398
Setup SSTP Client

399
SSTP Lab
• Setup SSTP server and clients using the created certificates from the
previous lab
• Test configuration

400
IPsec

401
IPSEC
• Internet Protocol Security (IPsec) is a set of protocols defined by the
Internet Engineering Task Force (IETF) to secure packet exchange
over unprotected IP/IPv6 networks such as the Internet
• IPsec protocol suite can be divided in following groups:
– Internet Key Exchange (IKE) protocols – dynamically generates and
distributes cryptographic keys for AH and ESP.
– Authentication Header (AH) RFC 4302
– Encapsulating Security Payload (ESP) RFC 4303
– Security Association – defines the IPSEC protocols, keys, authentication and
encryption methods between hosts
402
Benefits of IPSEC
• Confidentiality
– By encrypting data
• Integrity
– Routers at each end of a tunnel calculate the checksum or hash value of the
data
• Authentication
– Signatures and certificates
• All these while still maintaining the ability to route through existing
IP Networks

403
Benefits of IPSEC
• Data integrity and source authentication
– The data is signed by the sender and the signature is verified by the
recipient
– Modification of the data can be detected by the signature verification
– Because the signature is based on a (hash of a) shared secret, it gives
source authentication
• Anti-replay protection
– Optional; the sender must provide it but the recipient may ignore

404
Benefits of IPSEC
• Key management
– IKE – session negotiation and establishment
– Sessions are rekeyed or deleted automatically
– Secret keys are securely established and authenticated
– Remote peer is authenticated through varying options

405
IPSEC Architecture

Encapsulating Security Payload

406
ISAKMP
• The Internet Key Exchange (IKE) is a protocol that provides authenticated keying
material for Internet Security Association and Key Management Protocol
(ISAKMP) framework
– There are other key exchange schemes that work with ISAKMP, but IKE is the most
widely used one
– Together they provide means for authentication of hosts and automatic management of
security associations (SA)
• Most of the time IKE daemon is dormant
• There are two possible situations when it is activated:
– There is some traffic caught by a policy rule which needs to become encrypted or
authenticated, but the policy doesn't have any SAs
• The policy notifies IKE daemon about that, and IKE daemon initiates connection to remote host
– IKE daemon responds to remote connection

407
IKE
• Typically used for establishing IPSec sessions
• A key exchange mechanism
• Five variations of an IKE negotiation:
– Two modes (aggressive and main modes)
– Three authentication methods (pre-shared, public key encryption, and
public key signature)
• Uses UDP port 500

408
IKE Mode

409
ISAKMP
• In both cases, peers establish connection and execute 2 phases:
• Phase 1
– The peers agree upon algorithms they will use in the following IKE messages and
authenticate
– The keying material used to derive keys for all SAs and to protect following ISAKMP
exchanges between hosts is generated also.
– This phase should match following settings: authentication method, DH group,
encryption algorithm, exchange mode, hash algorithm, NAT-T, DPD and lifetime
(optional)
• Phase 2
– The peers establish one or more SAs that will be used by IPsec to encrypt data
– All SAs established by IKE daemon will have lifetime values
– This phase should match following settings: Ipsec protocol, mode (tunnel or transport),
authentication method, PFS (DH) group, lifetime

410
Diffie-Hellman (DH) key exchange protocol allows two parties without any initial shared
secret to create one securely.
The following Modular Exponential (MODP) and Elliptic Curve (EC2N) Diffie-Hellman
(also known as "Oakley") Groups are supported:
Diffie-Hellman Group Name Reference
Group 1 768 bit MODP group RFC 2409
Group 2 1024 bits MODP group RFC 2409
Group 3 EC2N group on GP(2^155) RFC 2409
Group 4 EC2N group on GP(2^185) RFC 2409
Group 5 1536 bits MODP group RFC 3526
Group 14 2048 bits MODP group RFC 3526
Group 15 3072 bits MODP group RFC 3526
Group 16 4096 bits MODP group RFC 3526
Group 17 6144 bits MODP group RFC 3526
Group 18 8192 bits MODP group RFC 3526
Group 19 256 bits random ECP group RFC 5903
Group 20 384 bits random ECP group RFC 5903
Group 21 521 bits random ECP group RFC 5903 411
IKE Phases

412
Phase 1 (Main Mode)
• Main mode negotiates an ISAKMP SA which will be used to create
IPsec SAs.
• Three steps
– SA negotiation (encryption algorithm, hash algorithm, authentication
method, which DF group to use)
– Do a Diffie-Hellman exchange
– Provide authentication information
• Authenticate the peer

413
Main Mode

414
Phase 1 (Aggressive Mode)
• Uses 3 (vs 6) messages to establish IKE SA
• No denial of service protection
• Does not have identity protection
• Optional exchange and not widely implemented

415
IKE Phase 2 (Quick Mode)
• All traffic is encrypted using the ISAKMP Security Association
• Creates/refreshes keys
• Each quick mode negotiation results in two IPsec Security
Associations (one inbound, one outbound)

416
IKE Phase 2 (Quick Mode)

417
IKEv2
• Internet Key Exchange Version 2 (IKEv2) is the second-generation
standard for a secure key exchange between connected devices.
• IKEv2 works by using an IPsec-based tunnelling protocol to establish
a secure connection.
• One of the single most important benefits of IKEv2 is its ability to
reconnect very quickly in the event that your VPN connection gets
disrupted.
• Quick reconnections and strong encryption makes IKEv2 an excellent
candidate to use

418
IPsec Methods
• Multiple approaches can be used to implement IPsec:
– Header only encryption (AH)
– Data only encryption (ESP)
– Header and data encryption (AH+ESP)
• ESP (packet data encryption) is the most widely used, the other two
are used rarely
• Can be configured to operate in two different modes:
– Transport
– Tunnel
• Both can be used to encrypt traffic
419
AH vs ESP
• AH is a protocol that provides authentication of either all or part of the
contents of a datagram through the addition of a header that is
calculated based on the values in the datagram
• Which parts of the datagram are used for the calculation, and the
placement of the header, depends whether tunnel or transport mode is
used.
• The presence of the AH header allows verification of the integrity of the
message, but doesn't encrypt it
• AH provides authentication but not privacy
• Encapsulating Security Protocol (ESP) is considered superior, it provides
data privacy and also its own authentication method.
420
AH
• Provides source authentication and data integrity
• Protection against source spoofing and replay attacks
– Authentication is applied to the entire packet, with the mutable fields in the IP
header zeroed out
• Operates on top of IP using protocol 51
• In IPv4, AH protects the payload and all header fields except mutable
fields and IP options
• MikroTik RouterOS supports the following authentication algorithms for
AH:
– SHA1
– MD5

421
ESP
• Encapsulating Security Payload (ESP) uses shared key encryption to
provide data privacy
– ESP also supports its own authentication scheme like that used in AH.
• ESP packages its fields in a very different way than AH
• Instead of having just a header, it divides its fields into three
components:
– ESP Header - Comes before the encrypted data and its placement depends on
whether ESP is used in transport mode or tunnel mode.
– ESP Trailer - This section is placed after the encrypted data. It contains padding
that is used to align the encrypted data.
– ESP Authentication Data - This field contains an Integrity Check Value (ICV),
computed in a manner similar to how the AH protocol works, for when ESP's
optional authentication feature is used.

422
ESP
• Uses IP protocol 50
• Provides all that is offered by AH, plus data confidentiality
• It uses symmetric key encryption
• Must encrypt and/or authenticate in each packet
• Encryption occurs before authentication
• Authentication is applied to data in the IPsec header as well as the
data contained as payload

423
Encryption Algorithms
• Authentication:
– MD5
– SHA1
– SHA2 (256-bit, 512-bit)
• Encryption:
– AES - 128-bit, 192-bit and 256-bit key AES-CBC, AES-CTR and AES-GCM algorithms;
– Blowfish - added since v4.5
– Twofish - added since v4.5
– Camellia - 128-bit, 192-bit and 256-bit key
– DES - 56-bit DES-CBC encryption algorithm;
– 3DES - 168-bit DES encryption algorithm
• Check https://wiki.mikrotik.com/wiki/Manual:IP/IPsec to confirm which platforms support
hardware acceleration

424
Security Association
• An IPsec security association (SA) specifies security properties that are
recognized by communicating hosts
• These hosts usually require two SAs to communicate securely
– A single SA protects data in one direction
– The protection is either to a single host or a group (multicast) address.
– Because most communication is peer-to-peer or client-to-server, two SAs must be
present to secure traffic in both directions
• The security protocol (AH or ESP), destination IP address, and security
parameter index (SPI) identify an IPsec SA
– The SPI, an arbitrary 32-bit value, is transmitted with an AH or ESP packet.
• An integrity checksum value is used to authenticate a packet
– If the authentication fails, the packet is dropped.

425
SA Key Management
• A security association contains the following information:
– Material for keys for encryption and authentication
– The algorithms that can be used
– The identities of the endpoints
– Other parameters that are used by the system
• SAs require keying material for authentication and encryption
• The Internet Key Exchange (IKE/v2) protocol handles key
management automatically

426
Tunnel Mode
The original packet is wrapped, encrypted, a new
IP header is added and the packet is sent to the
other side of the tunnel
This is used in server-server VPNs where both
endpoint IP’s are known

Original IP packet

New IP ESP ESP ESP auth


IP header IP payload
header header trailer trailer

Encrypted with ESP header

Signed by ESP auth trailer


Transport Mode
The data of the packet is encrypted, but the
header is sent in open clear text, IP header is
copied to the front
This is used in client-server VPNs where the
client location may vary e.g. L2TP with IPSEC

Original IP packet

IP header ESP ESP ESP auth


IP header IP payload
(copy) header trailer trailer

Encrypted with ESP header

Signed by ESP auth trailer


LAB Setup

INTERNET

R1 R2
IPsec

429
IPSEC Profile
• Profiles define the authentication and
encryption standards supported by the
peer
• At least one algorithm for encryption and
key exchange (DH Group) must match on
each end
• Exchange mode, hash algorithm, NAT-T,
DPD and Proposal Check must match on
both ends

430
IPSEC Peer
• Create a peering agreement in IPSEC à Peers
– Peer configuration settings are used to establish connections between IKE
daemons, used to negotiate keys and algorithms for SAs (as defined in the
Profile)
– Exchange mode is the only unique identifier between the peers, meaning
that there can be multiple peer configurations with the same remote-
address as long as different exchange-mode is used.

431
IPSEC Peer
• (remote) address and local address should
be defined
– These must be opposite matching on either
end
• Different ISAKMP phase 1 exchange
modes according to RFC 2408. main mode
relaxes rfc2409 to allow pre-shared-key
authentication. IKE2 mode enables IKEv2
• Passive – Do not attempt outgoing
connection (wait only)
432
IPSEC Identity
• Identities are configuration parameters that are
specific to the remote peer
• Main purpose of an identity is to handle
authentication and verify peer's integrity.
• Auth Method
– Pre shared key – provide a password (possible
vulnerability)
– Eap radius - IKEv2 EAP RADIUS passthrough
authentication for responder, server certificate in this
case is required
• Notrack chain - Adds raw firewall rules matching
ipsec policy to specified chain (required if Fastrack
is enabled in firewall)
433
IPSEC Peer
• Create IPSEC peers between the groups to initiate PH1 connection
– Set Address and Local Address as opposite matching pairs
• Add Identity to use Pre-Shared Key between peers with password
12345678

434
IPSEC Proposal
• Ensure both sides support the at least one set of authentication and
encryption algorithms in IPSEC à Proposals
• This defines the algorithms used in phase 2 (applied to the policies)

435
Policy
• Define policies in IPSEC à Policy to indicate which traffic will be
encrypted
– Src Address – range of local network to match (traffic coming from these
IP’s will be encrypted)
– Dst Address – range of remote network to match (traffic going to these IP’s
will be encrypted)
– Action – what to do (usually encrypt)
– IPSEC protocol – usually ESP, enabled with Tunnel mode

436
437
IPSEC Policy
• Create Policies as required to encrypt traffic between local network
ranges
• Add static routes to ensure correct routing between local networks
without NAT
• Check SA counters when pinging between laptops

438
Bandwidth Management

Simple Queues
Bursting
Estimating Bandwidth
• Throughput is a measurement of data rate over time
– 22mbps means 22 megabits can flow through the link in 1 second
• If more than the available data rate tries to flow through, the system will
queue up the waiting bits
• This will lead to lag or slower download rates.
• The latency of a link is how long the bits have to queue for before being
allowed to transit
• Since normally wireless links will not provide the same level of
bandwidth and latency as wired links, we can employ QOS mechanisms
to ensure fair use of (usually) contended wireless network
440
Quality of Service
• Quality of Service (QoS) means that the router should prioritize and
shape network traffic.
• QoS is not so much about limiting, it is more about providing quality
service to the network users.
• Some features of MikroTik RouterOS traffic control mechanism are listed
below:
– limit data rate for certain IP addresses, subnets, protocols, ports, and other
parameters
– prioritize some packet flows over others
– use queue bursts for faster web browsing
– apply queues on fixed time intervals
– share available traffic among users equally, or depending on the load of the
channel
441
Speed Limiting
• Direct control over the data rate of inbound traffic is impossible
• The router controls the data rate indirectly by dropping incoming packets
– TCP protocol adapts itself to the effective connection speed
• A queue is a collection of data packets collectively waiting to be transmitted by a
network device using a pre-defined structure methodology
• Simple Queues are the easiest way to limit data rate
• Simple queues make data rate limitation easy. One can limit:
– Client's rx rate (client's download)
– Client's tx rate (client's upload)
– Client's tx + rx rate (client's aggregate)
• While being easy to configure, Simple Queues give control over all QoS features
• To create a basic limitation, specify at least a queue name, target address and
upload/download limitation
442 442
Basic Limitation
• To create a basic limitation, specify at least a target address and
upload/download limitation
• Target address can be the following:
– 0.0.0.0/0 – default target all
– Single IP Address
– IP Subnet
– Interface name (selected from dropdown)
• Several IP’s / Subnets / Interfaces can be selected in the same rule
• Note that the setting “unlimited” implies that a limitation should be
ignored, it is not a method of providing unlimited bandwidth to a target
host
443
Simple Limitation

Who is going to be limited


Target Destination

Limitation to apply

Burst Settings

444 444
Simple Queue
• Restore backup-firewall
• Create a queue to limit your laptop's upload and download data rate to
256kbps/512Kbps
• Verify the limits are working
• Make a second queue underneath the first one to limit to
128Kbps/128Kbps
– Which queue has precedence?
– Re-order the queues and test again
• Add a queue to provide unlimited speed to your router from your laptop
– How do you specify a destination address?

445 445
More Queue Settings
• Dst address allows you to specify an ip to limit data to e.g. to limit access
to a certain web server to a certain amount)
• Time allows you to specify which times the queue is valid for
• Priority is a number from 1-8 with 1 having highest priority
• Packet mark allows protocol limits by using the firewall mangle facility
• Interface applies the limit to a specified interface
• Queue type controls how HTB manages datarate limitations
• Queue colors in Winbox:
0% - 50% available traffic used - green
51% - 75% available traffic used - yellow
76% - 100% available traffic used - red

446
Burst
• Burst is one of the means to ensure enhanced (better) QoS
• Bursts are used to allow higher data rates (exceeding the max-rate)
for a short period of time
• Bursts can give clients the impression of a higher speed service and
a better browsing experience while still limiting data rates on bigger
downloads
• To calculate burst you need to know the average datarate (calculated
over a burst-time period) and how it relates to the burst threshold

447
Average Data Rate
• Average data rate is calculated as follows:
– burst-time is being divided into 16 periods
– router calculates the average data rate of each class over these small
periods
• Note, that the actual burst period is not equal to the burst-time. It
can be several times shorter than the burst-time depending on the
max-limit, burst-limit, burst-threshold, and actual data rate history
(see the graph example on the next slide)
• To work out actual time from zero rate use the formula
actual_time=burst_time/(burst_limit/burst_threshold)
448
Limitation with Burst

If the average data rate is less than the burst-threshold, burst can be used
(actual data rate can reach burst-limit) 449
Burst Operation
Values: limit-at=1M , max-limit=2M , burst-threshold=1500k , burst-limit=4M, Burst-time=16s
Client will try to download two 4MB (32Mb) blocks of data, first download will start at zero seconds,
second download will start at 17th second. Traffic was unused for last minute.
As soon as client requested bandwidth it was able to get 4Mpbs burst for 6 seconds. As soon as burst
runs out rest of the data is downloaded at 2Mbps. The block of data was downloaded in 9 seconds -
without burst it would take 16 seconds. Burst would take 7 seconds to recharge before next download
starts.
Note that burst is still disallowed when download started and it kicks in only afterwards - in the middle of
download. Burst was ~4 seconds long and second block of was downloaded 4 seconds faster then
without burst.

450
Limitation with Burst

actual time = 30 / (30/15) = 30 / 2 = 15 seconds


Burst Exercise
• Limit your laptop's upload/download
– max-limit to 1024k/1024k (1M/1M)
– burst-limit up to 2048k/2048k (2M/2M)
– burst-threshold 512Kbps/512Kbps
– burst-time 60 seconds
• Calculate the expected burst time and check the result
• Change the burst limit to 10M/10M and compare the results
• Change burst-threshold to 4M/4M - compare the results
• Change burst-threshold to 128Kbps/128Kbps and burst time to 120
seconds - compare the results
452 452
HTB

Hierarchical Token Bucket


Rate Limitation
• Rate limiting is used to control the rate of traffic flow sent or
received on a network interface. Traffic which rate that is less than
or equal to the specified rate is sent, whereas traffic that exceeds
the rate is dropped or delayed.
• Rate limiting can be performed in two ways:
– rate-limiting (dropper or shaper or policer): discard all packets that exceed
rate limit – 100% rate limiter when queue-size=0
– rate equalizing (scheduler): delay packets that exceed specific rate limit in
the queue and transmit them when possible – 100% rate equalizing when
queue-size=unlimited

454
Limiting vs Equalizing
• Rate Limiting – all traffic exceeds a specific rate and is dropped

• Rate Equalizing – traffic exceeds a specific rate and is delayed in the queue and transmitted
later when it is possible
– the packet can be delayed only until the queue is not full
– If there is no more space in the queue buffer, packets are dropped.

455
HTB
• All implementations of Quality of Service in RouterOS are based on the
Hierarchical Token Bucket system
• HTB allows the creation of hierarchical queue structures and determines
relationships between parent and child queues and relationships between child
queues
• You cannot work with the HTB directly, it is the “master” queue that determines
how all the queue systems relate together
• HTBs help in controlling the use of the in and outbound bandwidth on a given link
• HTB allows using one single physical link to simulate multiple slower links and to
send different kinds of traffic on different simulated links.
• In other words, HTB is very useful to limit a clients download/upload rate.
• Thus, the limited client cannot saturate the total bandwidth
456
Mangle and HTBs

457
HTB in RouterOS
• RouterOS supports a Global HTB and another just before each
interface
• When a packet travels through the router, it passes Global and
interface HTB
• When a packet travels to the router, it passes only global HTB
• When a packet travels from the router, it passes Global and
interface HTB

458
Parent Queue
• It is hard for the router to detect the exact speed of your Internet
connection
• To optimize usage of your Internet resources and to ensure desired
QoS operation you should assign the maximal available connection
speed manually
• To do so, you should create one parent queue with strict speed
limitations and assign all your queues to this parent queue
• This allows the router to accurately apportion bandwidth and also
significantly improves performance (far less CPU cycles are required)

459
Parent Queue

460
HTB Structure
• As soon as a queue has at least one child it becomes a parent queue
• All child queues (irrespective of how many levels of parents they
have) are on the same bottom level of HTB
• Child queues do the actual traffic consumption, parent queues are
only responsible for traffic distribution
• Child queues will get their limit-at (Commited Information Rate) first
and then rest of the traffic will distributed by parents (up to the
max-rate)

461
Dual Limitation
• Working on the group router
• Create a parent queue with a limitation of 5M
• Create 2-3 child queues to limit each LAN router
– max-limit to 3M, target 10.x.0.a
– max-limit to 4M, target 10.x.0.b
– max limit to 5M, target 10.x.0.c
• Test by using btest between your LAN and WAN routers
• Check the effect on the child and parent queues

462
HTB Features – Dual Limitation
• HTB has two rate limits:
– CIR (Committed Information Rate) – (limit-at in RouterOS) this is the worst case
scenario: a flow will always get this amount of traffic (assuming we can satisfy the
total CIR bandwidth requirements across all child queues)
– MIR (Maximal Information Rate) – (max-limit in RouterOS) this is the best case
scenario: the rate that a flow can achieve, if the queue's parent has enough spare
bandwidth available

463
HTB Features – Dual Limitation
• First HTB will attempt to satisfy all the child queue's limit-at
• Once all the limit-at’s are satisfied it will try to reach max-limit
• The Maximal rate of the parent should be equal to or bigger than
the sum of the committed rates of the children
– MIR (parent) ≥ CIR(child1) +...+ CIR(childN)
• The Maximal rate of any child should be less than or equal to
maximal rate of the parent
– MIR (parent) ≥ MIR(child1)
– MIR (parent) ≥ MIR(child2)
– MIR (parent) ≥ MIR(childN)

464
Dual Limitation
• Give child queue A a limit-at of 2mbs
• Give other child queues a limit-at of 1mbs
• Consume all bandwidth and check the results
• Now give child queue A a limit-at of 3mbps
• Consume all bandwidth and check the results
• Reset child A back to 2mbps

465
HTB Features - Priority
• Priority works within child queues to arrange them by priority number
• 8 is the lowest priority, 1 is the highest
• Distinction between priorities is irrelevant (two queues with priorities 1
and 8, will have same relation as two queues with priorities 1 and 2)
• The queue with higher priority will satisfy its max-limit before other
queues
– But only after all limit-at’s for all queues have been satisfied
• Actual traffic prioritization will only work if limits are specified and there
is a parent queue
– Queues without limits will not consume bandwidth
466
Dual Limitation
• Adjust priorities
– give A higher priority – check the results
• Set guaranteed limits
– Give B a limit-at of 2m – check the results

467
Priority vs Limit-at
• It is a common misconception to use priority as a means of
guaranteeing traffic (e.g. giving VOIP a higher priority over other
traffic)
• Priority implies a better chance of receiving traffic, not a guarantee
• To guarantee certain traffic flows use limit-at, to give certain flows a
better chance of getting traffic use priority
– E.g. you would guarantee VOIP traffic but prioritise HTTP traffic over P2P
• In order for priority and limit-at to work a parent queue must exist, if
placed in the root it will have no effect

468
Token Bucket
• The Token Bucket algorithm is based on an analogy to a bucket where tokens,
represented in bytes, are added at a specific rate
– The bucket itself has a specified capacity.
• If the bucket fills to capacity, newly arriving tokens are dropped
• Bucket capacity = bucket-size * max-limit
• bucket size (0..10, Default:0.1) - queue option was added in RouterOS v6.35, before that
it was hard-coded to a value of "0.1".
• Before allowing any packet to pass through the queue, the queue bucket is inspected to
see if it already contains sufficient tokens at that moment.
• If yes, the appropriate number of tokens are removed ("cashed in") and packet is
permitted to pass through the queue.
• If no, the packets stays at the start of packet waiting queue until the appropriate
amount of tokens are available.
• In case of a multi-level queue structure, tokens used in a child queue are also 'charged'
to their parent queues. In other words - child queues 'borrow' tokens from their parent
queues. 469
HTB Bucket Size

470
Bucket Size
/queue simple add bucket-size=10/10 max-limit=10M/10M target=10.0.0.1

• In this case bucket-size=10, so bucket-capacity= 10 x 10M = 100M


• If the bucket is full (that is, client was not using full capacity of the queue for
some time), the next 100Mb of traffic can pass through the queue at an
unrestricted speed.
• So you can have:
• 20Mbps transfer speed for 10s
• 60Mbps transfer burst for 2s
• 1Gbps transfer burst for approximately 100ms
• You can therefore see that the bucket permits a type of 'burstiness' of the traffic
that passes through the queue
– The behaviour is similar to the normal burst feature, but lacks the upper limit of the
burst.
471
Bucket Size
• Create a simple queue for your laptop to test bucket size
• Set max limit to 5M/5M
• Try different bucket sizes (0.1, 1, 10) and check the result

472
HTB Features - Structure

• Following are some case studies for HTB which detail how bandwidth is split
between multiple connections based on the parent/child relationship 473
HTB
• The trainer will setup a simulation of the HTB structure to test out various scenarios as
depicted in the following slides

474
HTB - limit-at

6mbps 2mbps 2mbps

• Each child will receive their limit-at since with all queues
demanding full bandwidth the total requested will be 6M +
2M + 2M = 10M
• Since only limit-at can be satisfied priorities have no effect 475
HTB - max-limit

2mbps 6mbps 2mbps

• In this case the limit-at for all child queues is 6M


• If any queue does not use the limit-at the remaining
bandwidth will be divided between the other queues with
the highest priority receiving bandwidth first 476
HTB – limit-at
of the Parent

2mbps 6mbps 2mbps

• All queues demand full bandwidth


• Result: Q03 2M, Q04 6M, Q05 2M
• After satisfying all limit-ats HTB will give throughput to queue with highest priority. But
in this case the inner queue Q02 had a limit-at specified, by doing so, it reserved 8Mbps
of throughput for queues Q04 and Q05. Q04 has highest priority, it gets additional
throughput. 477
HTB – limit-at >
parent's max-
limit

• All queues request maximum bandwidth


• Result: Q03 ~3mbps, Q04 ~1mbps, Q05 ~6mbps
• By satisfying all limit-at’s HTB was forced to allocate 20Mbps - 6Mbps
to Q03, 2Mbps to Q04, 12Mbps to Q05. Our output interface only has
10Mbps. HTB will then try to maintain the same ratio 6:2:12 or 3:1:6 478
Queue Tree

Advanced queue structures


Queue Tree
• Queue tree is a direct implementation of HTB
• Each queue in the queue tree can be assigned to one HTB (Global or
Interface-queue)
• Each child queue must have a packet mark assigned to it

480
Queue Tree
• Queue Trees are superseded by Simple Queues
– Simple Queue offers all the functions of Queue Tree but does not require
mangle
– Can still use mangle if required
– Simple Queue performance (especially in HTB implementation) is far
better that Queue Tree

481
Creating a Mangle example
• For bandwidth management you need to use both Connection and
Packet marks
• First identify the traffic and apply a Connection Mark
• Then create a Packet Mark (flow mark) to track the flow of packets
– This is more efficient as it uses the ConnTrack table for packet matching
• Once the Packet Mark is established you can use the advanced tab in
your simple queue to limit by packet mark
• Passthrough specifies if the processing should stop or proceed to
further rules
• NB – queues will not work for any traffic that is Fastracked
482
483 Connection Mark Packet mark from
Connection Mark
Using the Packet Mark
• Use the Advanced tab to specify the flow mark

484
Queue Tree
• On side A
– Mark all HTTP connections and mark all packets from HTTP connections
– Mark all ICMP packets
• Set all previous queue priorities to 8
• Consume all available bandwidth with btest and check ping response time and
speedtest.net performance
• Extend Queue Tree structure as follows
– Child 1: 256kbps, http-flow, (priority 4)
– Child 2: 64k, ICMP, (priority 1)
• From your neighbour consume all bandwidth with bandwidth test
• Check ping response times and speedtest.net with and without priority
• Use torch to monitor traffic and modify mangle to improve speedtest.net results

485
Connection Rate
• Connection Rate is a firewall matcher that allow to capture traffic based on present
speed of the connection.
• Each entry in connection tracking table represents bidirectional communication.
• Every time packet gets associated to particular entry, packet size value is added to
"connection-bytes" value for this entry. This includes both upload and download
• Connection Rate calculates speed of connection based on change of "connection-
bytes".
– Connection Rate is recalculated every second and does not have any averages.
• Both options "connection-bytes" and "connection-rate" work only with TCP and UDP
traffic. (you need to specify protocol to activate these options)
• In "connection-rate" you can specify range of speed that you like to capture.

486
Capture TCP/UDP traffic going through the router when
connection speed is below 100kbps

487
These two rules will mark all heavy connections based on any
connection after the first 10mb, that exceeds 1mbps speed can be
assumed as "heavy"

488
489
Connection Rate
• Disable previous rules (do not delete)
• Create required rules to mark all connections and packets exceeding 50mb and
5mbps
• Create 2 queues
– One queue limits users to 20mbps
– 2nd queue limits all users exceeding 50mb to 2mbps
• Test out configuration using speedtest website

490
Queue Types
• RouterOS has 4 queue types:
– FIFO – First In First Out (for Bytes or for Packets)
– RED – Random Early Detect (or Drop)
– SFQ – Stochastic Fairness Queuing
– PCQ – Per Connection Queuing (MikroTik Proprietary)

491
Hardware queues
• Starting from v5.8 there is a new type “none” and new default
queue “only-hardware-queue”
• All RouterBOARDS will have this new queue type set as default
interface queue
• only-hardware-queue leaves an interface with only the hw transmit
descriptor ring buffer which acts as a queue in itself
• Usually at least 100 packets can be queued for transmit in transmit
descriptor ring buffer
• Transmit descriptor ring buffer size and the amount of packets that
can be queued in it varies for different types of ethernet MACs

492
Hardware queues
• Having no software queue is especially beneficial on SMP systems because it
removes the requirement to synchronize access to it from different cpus/cores
which is expensive
• “multi-queue-ethernet-default” can be beneficial on SMP systems with ethernet
interfaces that have support for multiple transmit queues and have a linux driver
support for multiple transmit queues
• By having one software queue for each hardware queue there might be less time
spent for synchronizing access to them
• Having possibility to set only-hardware-queue requires support in ethernet driver
so it is available only for some ethernet interfaces mostly found on RBs
• Improvement from only-hardware-queue and multi-queue-ethernet-default is
present only when there is no "/queue tree" entry with particular interface as a
parent

493
FIFO – First In First Out
• What comes in first is handled first, what comes in next waits until the first is
finished
• Number of waiting units (Packets or Bytes) is limited by “queue size”. If the
queue “is full” then incoming units are dropped
• Usually used on Ethernet because of the predictable behaviour of the link and
very low resource consumption

494
RED – Random Early Drop
• Same as FIFO but with additional drop probability even if queue is
not full
• The probability is based on a
comparison of the average queue
length over a period of time to the
minimal and maximal threshold –
the closer to the maximal threshold
bigger the chance of drop.

495
SFQ
• Based on hash value from source and destination address SFQ
divides traffic into 1024 sub-streams
• A Round Robin algorithm then distributes equal amounts of
traffic to each sub-stream
• SFQ should be used for equalizing
similar connections
• Usually used to manage information
flow to or from servers, so it can
offer services to every customer
• Ideal for p2p limitation as it is
possible to place strict limitations
without dropping connections
496
CAKE
• Common Applications Kept Enhanced (CAKE) is a queue
discipline (qdisc) for the Linux kernel
• Uses COBALT (AQM algorithm combining Codel and
BLUE) and a variant of DRR++ for flow isolation
• In other words, Cake’s fundamental design goal is user-
friendliness and low overhead (as compared to similar
disciplines like SFQ)
• All settings are optional; the default settings are chosen
to be practical in most common deployments
• In most cases, the configuration requires only a
bandwidth parameter to get useful results
• Designed for localized (CPE) deployment at a SOHO level

497
CoDeL and FQCoDel
• CoDel (Controlled-Delay Active Queue Management) algorithm uses
the local minimum queue as a measure of the persistent queue,
similarly, it uses a minimum delay parameter as a measure of the
standing queue delay
– Queue size is calculated using packet residence time in the queue.
• CoDel - Fair Queuing (FQ) with Controlled Delay (CoDel) uses
a randomly determined model to classify incoming packets into
different flows and is used to provide a fair share of the bandwidth
to all the flows using the queue
– Each flow is managed using CoDel queuing discipline which internally uses a
FIFO algorithm.
498
Queue Types
• (Optional) – enable the tree queue rules and test performance for ping and
speedtest using different queue types

499
Per Connection Queuing
• PCQ is used to optimize massive QoS systems where most of the queues are
exactly the same only for different sub-streams.
• The PCQ algorithm is simple
– first it uses selected classifiers to distinguish one sub-stream from another
– then it applies an identical individual FIFO queue size and limitation on every sub-stream
– then it groups all sub-streams together and applies a global FIFO queue size and
limitation.
• PCQ parameters:
– pcq-classifier (dst-address | dst-port | src-address | src-port; : selection of sub-stream
identifiers
– pcq-rate (number) : maximal available data rate of each sub-stream
– pcq-limit (number) : queue size of one sub-stream in packets
– pcq-total-limit (number) : queue size of global FIFO queue

500
PCQ example
• If ‘limit-at’ and ‘max-limit’ are set to ‘0’, then the subqueues can
take up all bandwidth available for the parent
• Set the PCQ Rate to ‘0’, if you do not want to limit subqueues, i.e,
they can use the bandwidth up to ‘max-limit’, if available
• Set the PCQ Rate to <number> to hard limit each subqueue to a
specified amount

501
PCQ in Action (cont.)
• pcq-rate=0
1 ‘user’ 2 ‘users’ 7 ‘users’

73k

256k 73k
73k
queue=pcq-down
512k 73k
max-limit=512k
73k
256k 73k
73k

502
• Set pcq-rate to zero to
balance all flows in the
queue without limiting
individual flows
– Each flow can get up to total
limit of queue
• Set classifier – dst-address
for download queue, src-
address for upload queue

503
PCQ in Action
pcq-rate=128000
2 ‘users’ 4 ‘users’ 7 ‘users’

73k
128k
73k

128k 73k
queue=pcq-down
73k
max-limit=512k
128k 128k 73k
73k
128k 128k
73k

504
• Set pcq-rate to a number to
balance all flows in the
queue and limit each flow to
a set rate
– Each flow can get up to set
rate if there is enough total
bandwidth
• Set classifier – dst-address
for download queue, src-
address for upload queue

505
Applying the Queue Type

506
Universal Plug and Play
UPNP
• RouterOS supports Universal Plug and Play architecture for transparent peer-to-
peer network connectivity of personal computers and network-enabled
intelligent devices or appliances.
• UPnP enables data communication between any two devices under the
command of any control device on the network.
• Universal Plug and Play is completely independent of any particular physical
medium
• It supports networking with automatic discovery without any initial configuration,
whereby a device can dynamically join a network
• DHCP and DNS servers are optional and will be used if available on the network
• UPnP implements a simple yet powerful NAT traversal solution, that enables the
client to get full two-way peer-to-peer network support from behind the NAT.

508
Interfaces
• There are two interface types for UPnP
– internal (the one local clients are connected to) and
– external (the one the Internet is connected to)
• A router may only have one active external interface with a 'public' IP
address on it, and as many internal interfaces as needed, all with source-
NATted 'internal' IP addresses.
• The protocol works by creating dynamic NAT entries.
• The UPnP protocol is used for many modern applications, like most
DirectX games, as well as for various Windows Messenger features like
remote assistance, application sharing, file transfer, voice, video from
behind a firewall.
509
Enable UPNP
• Set in IP à UPNP
• Enable and define internal and external interface/s

510
UPNP Setup
allow-disable-external- whether or not should the users are allowed to disable the router's
interface (yes | no ; external interface. This functionality (for users to be able to turn the
Default: yes) router's external interface off without any authentication procedure)
is required by the standard, but as it is sometimes not expected or
unwanted in UPnP deployments which the standard was not
designed for (it was designed mostly for home users to establish their
own local networks), you can disable this behavior
enabled (yes | no ; Enable UPnP service
Default: no)
show-dummy-rule (yes Enable a workaround for some broken implementations, which are
| no ; Default: yes) handling the absence of UPnP rules incorrectly (for example, popping
up error messages). This option will instruct the server to install a
dummy (meaningless) UPnP rule that can be observed by the clients,
which refuse to work correctly otherwise 511
Web Proxy

HTTP Caching
HTTP Firewall
Transparent Mode
Web Proxy
• A proxy server acts as an intermediary for requests from clients seeking resources
from the internet
• A client connects to the proxy server, requesting some service, such as a file,
connection, web page, or other resource
• The proxy server evaluates the request according to its filtering rules
– If the request is validated by the filter, the proxy provides the resource by connecting to
the relevant server and requesting the service on behalf of the client.
– A proxy server may optionally alter the client's request or the server's response, and
sometimes it may serve the request without contacting the specified server.
– In this case, it 'caches’ responses from the remote server, and returns subsequent
requests for the same content directly.
• Most proxies are a web proxy, allowing access to content on the World Wide Web

513
Uses for a Proxy Server
• To keep machines behind it anonymous (mainly for security)
• To speed up access to resources (using caching).
– Web proxies are commonly used to cache web pages from a web server
• To apply access policy to network services or content, e.g. to block
undesired sites.
• To log / audit usage, i.e. to provide company employee Internet usage
reporting.
• To bypass security/ parental controls.
• To scan transmitted content for malware before delivery.
• To scan outbound content, e.g., for data leak protection.
• To circumvent regional restrictions.

514
MikroTik Proxy
• The MikroTik proxy is a scaled down, “light” proxy with the following
features:
– Easy and rapid deployment
– Runs as standard proxy
– Runs as transparent proxy (with additional firewall rules)
– HTTP Filtering (HTTP “firewall”)
– HTTP Redirection
– Parent Proxy support

515
Web Proxy Settings

Enable/disable the proxy


Optional source address to use for proxy
requests
Proxy port/s
(optional) Parent Proxy settings
Contact info for proxy support
Cache settings and size
Set to use disk instead of memory
Performance settings
Cache validity
Force Caching
Set QOS pointer for Proxy cache hits 516
Transparent Mode

• To run in transparent
mode you will need a
Redirect (DST-NAT) rule
• Redirect action can
send all port 80
requests to the internal
proxy and port
• Web browsing is
transparently cached

517
Proxy
● Enable your proxy server now
– Cache from memory
● Change your browser settings to use a proxy server
– Test the functionality
● Alter your proxy settings to use the trainer router as a parent proxy server
– 10.1.1.254:8080
– Test the functionality
● Reset your browser settings and redirect all port 80 requests to your internal
proxy using a firewall rule
– Confirm functionality
– http://httpforever.com
518
Proxy Notes
• When setting up the proxy service, make sure it serves only your
clients, and is not misused as relay.
– Use the IP > Web Proxy > Access or a firewall rule to limit proxy access to
your internal network
• It may be useful to have Web proxy running even with no cache
when you want to use it only as something like HTTP and FTP
firewall; for example,
– denying access to mp3 files
– redirect requests to an external proxy (possibly, to a proxy with caching
functions) transparently.
519
HTTP Firewall
• The IP > Web Proxy > Access can be used to block access to
websites, and redirect to others
• You can limit access by IP or by DNS name

520
Proxy Access
● Block access to your proxy from all IP’s not inside your network
– Can your neighbour use your proxy server?
● Redirect all requests for httpforever.com to the trainer website
trainer.mikrotiksa.com
– Test the functionality

521
Using an External Cache
• The Stores menu is used to configure external drives on the router
• Cache can be stored to IDE, SATA, USB, CF, MicroSD drives
• The store needs to be formatted before use
• The store can serve multiple functions
– Web Proxy Cache
– User Manager database
– Dude Database

522
Before the test
• Connect your laptop to the Internet AP
– Password is Internet
• Login to your account on www.mikrotik.com
• Select “My Training Sessions” link
• You should see the exam ready for taking
• Please rate the trainer before you begin
• Licenses and certificates (if you pass) are issued
immediately after the exam is written

523
Certification Test
• You have all been enrolled on the test at http://www.mikrotik.com
• Open Book exam
– Google.com - Wiki.mikrotik.com – all documentation
– Forum.mikrotik.com - Routerboard.com – all hardware specifications
– Training Manual - Routerboard direct login

• Exam is 1 Hour Long


– 60% Pass Grade
– Everyone’s questions are different: 25 questions from a large possible pool
– Click Save Progress regularly (top right below timer) in case of disconnect
– Images can be enlarged by clicking on them
– 50-59% ask the trainer for a re-write (1 allowed per student)
• Please reset your routers after you are done

524
Contact me?
• Email: [email protected]
• Skype: savagedavid
• Twitter: savagedavid
• Web: http://mikrotiksa.com
• Blog: http://www.mikrotiksa.com/evo
• Office (Cape Town) +27-21-557-6868
• Sales/Support queries: ([email protected])

525

You might also like