From MikroTik Wiki
Jump to: navigation, search

Applies to RouterOS: v6.0 +



Sub-menu: /ip ipsec
Package required: security
Standards: RFC 4301

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

IpSec protocol suite can be divided in following groups:

  • Authentication Header (AH) RFC 4302
  • Encapsulating Security Payload (ESP) RFC 4303
  • Internet Key Exchange (IKE) protocols. Dynamically generates and distributes cryptographic keys for AH and ESP.

Authentication Header (AH)

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. What 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 to verify the integrity of the message, but doesn't encrypt it. Thus, AH provides authentication but not privacy. Another protocol (ESP) is considered superior, it provides data privacy and also its own authentication method.

RouterOS supports the following authentication algorithms for AH:

  • SHA1
  • MD5

Transport mode

In transport mode AH header is inserted after IP header. IP data and header is used to calculate authentication value. IP fields that might change during transit, like TTL and hop count, are set to zero values before authentication.

Tunnel mode

In tunnel mode original IP packet is encapsulated within a new IP packet. All of the original IP packet is authenticated.

Encapsulating Security Payload

Encapsulating Security Payload (ESP) uses shared key encryption to provide data privacy. ESP also supports its own authentication scheme like that used in AH, or can be used in conjunction with AH.


Note: Using ah and esp together provides double authentication which adds additional load to CPU and does not provide any significant security advantages. We suggest to switch only to ESP.

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.

Transport mode

In transport mode ESP header is inserted after original IP header. ESP trailer and authentication value is added to the end of the packet. In this mode only IP payload is encrypted and authenticated, IP header is not secured.

Tunnel mode

In tunnel mode original IP packet is encapsulated within a new IP packet thus securing IP payload and IP header.

Encryption algorithms

RouterOS ESP supports various encryption and authentication algorithms.


  • SHA1
  • MD5


  • DES - 56-bit DES-CBC encryption algorithm;
  • 3DES - 168-bit DES encryption algorithm;
  • AES - 128, 192 and 256-bit key AES-CBC encryption algorithm;
  • Blowfish - added since v4.5
  • Twofish - added since v4.5
  • Camellia - 128, 192 and 256-bit key Camellia encryption algorithm added since v4.5

Hardware encryption

Hardware acceleration allows to do faster encryption process by using built-in encryption engine inside CPU. AES-CBC and sha1/sha256 are the only algorithms that uses these features, any other combination will fall back to software.

List of RouterBoards with enabled hardware support:

  • hEX v3 (RB750Gr3 model only)
  • All Cloud Coure Router series devices
  • RB1100AHx2
  • RB1000
  • RB850Gx2 (only starting 2016, serial numbers that begin with number 5)

For comparison RB1000 with enabled HW support can forward up to 550Mbps encrypted traffic. When HW support is disabled it can forward only 150Mbps encrypted traffic in AES-128 mode.

RB1100AHx2 Config Optimizations

Some configuration advices on how to get maximum ipsec throughput on multicore RB1100AHx2:

  • Avoid using ether12 and ether13. Since these ports are pci-x they will be slowest ones.
  • Fastest forwarding is from switch chip ports (ether1-ether10) to ether11 (directly connected to CPU) and vice versa.
  • Set hardware queue on all interfaces
/queue interface set [find] queue=only-hardware-queue
  • Disable RPS:
/system resource irq rps disable [find]
  • Assign one CPU core to ether11 and other CPU core to everything else. Forwarding over ether11 requires more CPU that is why we are giving one core only for that interface (in IRQ setting ether11 is listed as ether12 tx,rx and error).
/system resource irq
set [find] cpu=1
set [find users="eth12 tx"] cpu=0
set [find users="eth12 rx"] cpu=0
set [find users="eth12 error"] cpu=0
  • disable connection tracking

With all above recommendations it is possible to forward 820Mbps (1470byte packets two streams).

With enabled connection tracking 700Mbps (1470 byte packets two streams).

HEXv3 (mmips) Config Optimizations

Hex v3 or RB750Gr3 uses MediaTek MT7621 CPU with has integrated hardware packet processor. This allows in RouterOS to accelerate Ipsec traffic up to 470Mbps. Hardware acceleration is used with following algorithms: 128,192,256-bit aes-cbc; sha1,sha256.

To get best performance two simple rules must be taken into account:

  • avoid packet fragmentation;
  • there must be no packet reordering.

Packet fragmentation can be avoided by sending packet over the tunnel that will fit in 1500 bytes after Ipsec and other encapsulation protocol headers are added. Ipsec header size depends on tunnel/transport mode and used encryption algorithm. With pure Ipsec in tunnel mode it is possible to safely send 1400byte packets. To avoid fragmentation for TCP traffic, change-mss rule should be added to change TCP MSS to 1400-40=1360bytes. See example in the mangle manual

To demonstrate max Ipsec throughput that Hex v3 can handle, lets set up basic site-to-site setup. For more info on such setups see the examples. Two 36 core CCR routers will be used to generate traffic from each site.


Ipsec configuration on Hexes is quite simple:

# Hex 1
/ip address add address= interface=ether3
/ip address add address= interface=ether2
/ip route add dst-address= gateway=

/ip ipsec {
  peer add remote-address= secret=xxx
  proposal set default enc-algorithms=aes-128-cbc
  policy add src-address= dst-address= \
    sa-src-address= sa-dst-address= tunnel=yes

# Hex 2
/ip address add address= interface=ether3
/ip address add address= interface=ether2
/ip route add dst-address= gateway=

/ip ipsec {
  peer add remote-address= secret=xxx
  proposal set default enc-algorithms=aes-128-cbc
  policy add src-address= dst-address= \
    sa-src-address= sa-dst-address= tunnel=yes

Now lets set up traffic generator on CCR routers:

# CCR 1
/ip address add address= interface=ether1
/ip route add dst-address= gateway=

/tool traffic-generator set measure-out-of-order=yes
/tool traffic-generator packet-template
  add ip-src= ip-dst= ip-gateway=

#CCR 2
/ip address add address= interface=ether1
/ip route add dst-address= gateway=

/tool traffic-generator set measure-out-of-order=yes
/tool traffic-generator packet-template
  add ip-src= ip-dst= ip-gateway=

Notice that measure-out-of-order was enabled, this allows to see how much reordered packets appear when processed by Ipsec hardware driver.

Setup is ready, now lets run traffic generator in both directions:



As it can be seen from screenshots above, maximum that encryption core can handle is ~450Mbps with 1400byte packets. On interface ether3 can be seen total traffic forwarded with added Ipsec headers, which is approximately 500Mbps. Total CPU load is approximately ~50%, this allows to run ipsec at its maximum and still have free resources for other tasks like firewall, queues etc.

Now lets change to maximum security settings that currently is supported by hardware encryption core.

/ip ipsec proposal set default enc-algorithms=aes-256-cbc auth-algorithms=sha256


Results above show that its a bit slower but still a decent speed at 320Mbps with 1400byte packets.

Internet Key Exchange Protocol

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 doing nothing. 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. 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 alorithm
    • 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 (either limiting time, after which SA will become invalid, or amount of data that can be encrypted by this SA, or both). This phase should match following settings:
    • Ipsec protocol
    • mode (tunnel or transport)
    • authentication method
    • PFS (DH) group
    • lifetime

Note: There are two lifetime values - soft and hard. When SA reaches it's soft lifetime treshold, the IKE daemon receives a notice and starts another phase 2 exchange to replace this SA with fresh one. If SA reaches hard lifetime, it is discarded.


Warning: Phase 1 is not re-keyed if DPD is disabled when lifetime expires, only phase 2 is re-keyed. To force phase 1 re-key, enable DPD.

IKE can optionally provide a Perfect Forward Secrecy (PFS), which is a property of key exchanges, that, in turn, means for IKE that compromising the long term phase 1 key will not allow to easily gain access to all IPsec data that is protected by SAs established through this phase 1. It means an additional keying material is generated for each phase 2.

Generation of keying material is computationally very expensive. Exempli gratia, the use of modp8192 group can take several seconds even on very fast computer. It usually takes place once per phase 1 exchange, which happens only once between any host pair and then is kept for long time. PFS adds this expensive operation also to each phase 2 exchange.

Diffie-Hellman Groups

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 GroupNameReference
Group 1768 bit MODP groupRFC 2409
Group 21024 bits MODP groupRFC 2409
Group 3EC2N group on GP(2^155)RFC 2409
Group 4EC2N group on GP(2^185)RFC 2409
Group 51536 bits MODP groupRFC 3526
Group 142048 bits MODP groupRFC 3526
Group 153072 bits MODP groupRFC 3526
Group 164096 bits MODP groupRFC 3526
Group 176144 bits MODP groupRFC 3526

IKE Traffic

To avoid problems with IKE packets hit some SPD rule and require to encrypt it with not yet established SA (that this packet perhaps is trying to establish), locally originated packets with UDP source port 500 are not processed with SPD. The same way packets with UDP destination port 500 that are to be delivered locally are not processed in incoming policy check.

Setup Procedure

To get IPsec to work with automatic keying using IKE-ISAKMP you will have to configure policy, peer and proposal (optional) entries.


Warning: Ipsec is very sensitive to time changes. If both ends of the IpSec tunnel are not synchronizing time equally(for example, different NTP servers not updating time with the same timestamp), tunnels will break and will have to be established again.

Mode Config

Sub-menu: /ip ipsec mode-config


Note: If RouterOS client is initiator, it will always send CISCO UNITY extension, and RouterOS supports only split-include from this extension.

Property Description
address-pool (none | string; Default: ) Name of the address pool from which responder will try to assign address if mode-config is enabled.
address-prefix-length (integer [1..32]; Default: ) Prefix length (netmask) of assigned address from the pool.
comment (string; Default: )
name (string; Default: )
static-dns (IP; Default: ) Manually specified DNS server's IP address to be sent to the client
system-dns (yes | no; Default: ) When this option is enabled DNS addresses will be taken from /ip dns
split-include (list of ip prefix; Default: ) List of subnets in CIDR format, which to tunnel. Subnets will be sent to the peer using CISCO UNITY extension, remote peer will create specific dynamic policies.

XAuth Users

Sub-menu: /ip ipsec user

List of allowed XAuth users

Property Description
address (IP; Default: ) IP address assigned to the client. If not set dynamic address is used allocated from the address-pool defined in Mode Config menu.
name (string; Default: ) Username
password (string; Default: )

Peer configuration

Sub-menu: /ip ipsec peer

Peer configuration settings are used to establish connections between IKE daemons ( phase 1 configuration). This connection then will be used to negotiate keys and algorithms for SAs.

Starting from v6rc12 responder side now uses initiator exchange type for peer config selection. It means that you can configure multiple ipsec peers with the same address but different exchange modes or encryption methods.


Note: exchange modes main and l2tp-main are treated the same, so these modes cannot be used select config between multiple peers.

Property Description
address (IP/IPv6 Prefix; Default: If remote peer's address matches this prefix, then the peer configuration is used in authentication and establishment of Phase 1. If several peer's addresses match several configuration entries, the most specific one (i.e. the one with largest netmask) will be used.
auth-method (eap-radius | pre-shared-key | pre-shared-key-xauth | rsa-signature | rsa-key | rsa-signature-hybrid; Default: pre-shared-key) Authentication method:
  • eap-radius - IKEv2 EAP RADIUS passthrough authentication for responder (RFC 3579). Server certificate in this case is required. If server certificate is not specified then only clients supporting EAP-only (RFC 5998) will be able to connect. Note that EAP method should be compatible with EAP-only.
  • pre-shared-key - authenticate by a password (secret) string shared between the peers
  • rsa-signature - authenticate using a pair of RSA certificates
  • rsa-key - authenticate using a RSA key imported in Ipsec key menu.
  • pre-shared-key-xauth - mutual PSK authentication + xauth username/password. passive parameter identifies server/client side
  • rsa-signature-hybrid - responder certificate authentication with initiator Xauth. passive parameter identifies server/client side
certificate (string; Default: ) Name of a certificate listed in certificate table (signing packets; the certificate must have private key). Applicable if RSA signature authentication method (auth-method=rsa-signature) is used.
comment (string; Default: ) Short description of the peer.
dh-group (ec2n155 | ec2n185 | modp1024 | modp1536 | modp2048 | modp3072 | modp4096 | modp6144 | modp768; Default: modp1024) Diffie-Hellman group (cipher strength)
disabled (yes | no; Default: no) Whether peer is used to match remote peer's prefix.
dpd-interval (time | disable-dpd; Default: 2m) Dead peer detection interval. If set to disable-dpd, dead peer detection will not be used.
dpd-maximum-failures (integer: 1..100; Default: 5) Maximum count of failures until peer is considered to be dead. Applicable if DPD is enabled.
enc-algorithm (3des | aes-128 | aes-192 | aes-256 | blowfish | camellia-128 | camellia-192 | camellia-256 | des; Default: aes-128) List of encryption algorithms that will be used by the peer.
exchange-mode (aggressive | base | main | main-l2tp | ike2; Default: main) Different ISAKMP phase 1 exchange modes according to RFC 2408. Do not use other modes then main unless you know what you are doing. main-l2tp mode relaxes rfc2409 section 5.4, to allow pre-shared-key authentication in main mode. ike2 mode enables Ikev2 RFC 7296. Parameters that are ignored by Ikev2 proposal-check, compatibility-options, lifebytes, all xauth parameters.
generate-policy (no | port-override | port-strict; Default: no) Allow this peer to establish SA for non-existing policies. Such policies are created dynamically for the lifetime of SA. Automatic policies allows, for example, to create IPsec secured L2TP tunnels, or any other setup where remote peer's IP address is not known at the configuration time.
  • no - do not generate policies
  • port-override -- generate policies and force policy to use any port (old behavior)
  • port-strict -- use ports from peer's proposal, which should match peer's policy
hash-algorithm (md5 | sha1 | sha256 | sha512; Default: sha1) Hashing algorithm. SHA (Secure Hash Algorithm) is stronger, but slower. MD5 uses 128-bit key, sha1-160bit key.
key (string; Default: ) Name of the key from key menu. Applicable if auth-method=rsa-key.
lifebytes (Integer: 0..4294967295; Default: 0) Phase 1 lifebytes is used only as administrative value which is added to proposal. Used in cases if remote peer requires specific lifebytes value to establish phase 1.
lifetime (time; Default: 1d) Phase 1 lifetime: specifies how long the SA will be valid.
mode-config (none | request-only | string; Default: none) Name of the mode config parameters from mode-config menu. When parameter is set mode-config is enabled.
  • initiator peer on phase1 will send mode-config request and will set assigned IP address and DNS.
  • responder will assign ip address if address-pool is specified, will send also DNS server addresses and split-include subnets (if defined).
my-id (auto | fqdn | user-fqdn; Default: auto) This parameter sets IKE ID to specified mode. It is possible to manually set two modes FQDN and USER_FQDN.
  • FQDN - fully qualified domain name
  • USER_FQDN - specifies a fully-qualified username string, for example, "";
  • auto IP address is used as ID.
nat-traversal (yes | no; Default: no) Use Linux NAT-T mechanism to solve IPsec incompatibility with NAT routers inbetween IPsec peers. This can only be used with ESP protocol (AH is not supported by design, as it signs the complete packet, including IP header, which is changed by NAT, rendering AH signature invalid). The method encapsulates IPsec ESP traffic into UDP streams in order to overcome some minor issues that made ESP incompatible with NAT.
passive (yes | no; Default: no) When passive mode is enabled will wait for remote peer to initiate IKE connection. Enabled passive mode also indicates that peer is xauth responder, and disabled passive mode - xauth initiator. When passive mode is disabled peer will try to establish not only phase1, but also phase2 automatically, if policies are configured or created during phase1.
policy-template-group (none | string; Default: ) If generate-policy is enabled, responder checks against templates from the same group. If none of the templates match, Phase2 SA will not be established.
port (integer:0..65535; Default: 500) Communication port used (when router is initiator) to connect to remote peer in cases if remote peer uses non-default port.
proposal-check (claim | exact | obey | strict; Default: obey) Phase 2 lifetime check logic:
  • claim - take shortest of proposed and configured lifetimes and notify initiator about it
  • exact - require lifetimes to be the same
  • obey - accept whatever is sent by an initiator
  • strict - if proposed lifetime is longer than the default then reject proposal otherwise accept proposed lifetime
remote-certificate (string; Default: ) Name of a certificate (listed in certificate table) for authenticating the remote side (validating packets; no private key required). Applicable if RSA signature authentication method is used. If remote-certificate is not specified then received certificate from remote peer is used and checked against CA in certificate store. Proper CA must be imported in certificate store.
secret (string; Default: ) Secret string (in case pre-shared key authentication is used). If it starts with '0x', it is parsed as a hexadecimal value
send-initial-contact (yes | no; Default: yes) Specifies whether to send "initial contact" IKE packet or wait for remote side, this packet should trigger removal of old peer SAs for current source address. Usually in road warrior setups clients are initiators and this parameter should be set to no. Initial contact is not sent if modecfg or xauth is enabled for ikev1.
xauth-login (string; Default: ) initiator (client) XAuth username
xauth-password (string; Default: ) initiator (client) XAuth password


Note: IPSec phases information is erased, when /ip ipsec peer configuration is modified on the fly, however packets are being encrypted/decrypted because of installed-sa (for example remote-peers information is erased, when peer configuration is modified.


Sub-menu: /ip ipsec key

This submenu list all imported public/private keys, that can be used for peer authentication. Submenu also has several commands to work with keys.

For example print below shows two imported 1024-bit keys, one public and one private.

[admin@PoETik] /ip ipsec key> print 
Flags: P - private-key, R - rsa 
 #    NAME                                                               KEY-SIZE
 0 PR priv                                                               1024-bit
 1  R pub                                                                1024-bit


Property Description
export-pub-key (file-name; key) Export public key to file from one of existing private keys.
generate-key (key-size; name) Generate private key. Takes two parameters, name of newly generated key and key size 1024,2048 and 4096.
import (file-name; name) Import key from file.


Sub-menu: /ip ipsec policy

Policy table is used to determine whether security settings should be applied to a packet.

Property Description
action (discard | encrypt | none; Default: encrypt) Specifies what to do with packet matched by the policy.
  • none - pass the packet unchanged
  • discard - drop the packet
  • encrypt - apply transformations specified in this policy and it's SA
comment (string; Default: ) Short description of the policy
disabled (yes | no; Default: no) Whether policy is used to match packets.
dst-address (IP/IPv6 prefix; Default: Destination address to be matched in packets.
dst-port (integer:0..65535 | any; Default: any) Destination port to be matched in packets. If set to any all ports will be matched
group (string; Default: default) Name of the policy group to which this template is assigned.
ipsec-protocols (ah | esp; Default: esp) Specifies what combination of Authentication Header and Encapsulating Security Payload protocols you want to apply to matched traffic
level (require | unique | use; Default: require) Specifies what to do if some of the SAs for this policy cannot be found:
  • use - skip this transform, do not drop packet and do not acquire SA from IKE daemon
  • require - drop packet and acquire SA
  • unique - drop packet and acquire a unique SA that is only used with this particular policy. It is used in setups where multiple clients can sit behind one public IP address (clients behind NAT).
manual-sa (string | none; Default: none) Name of the manual SA template
priority (integer:-2147483646..2147483647; Default: 0) Policy ordering classificator (signed integer). Larger number means higher priority.
proposal (string; Default: default) Name of the proposal template that will be sent by IKE daemon to establish SAs for this policy.
protocol (all | egp | ggp| icmp | igmp | ...; Default: all) IP packet protocol to match.
sa-dst-address (ip/ipv6 address; Default: ::) SA destination IP/IPv6 address (remote peer).
sa-src-address (ip/ipv6 address; Default: ::) SA source IP/IPv6 address (local peer).
src-address (ip/ipv6 prefix; Default: Source IP prefix
src-port (any | integer:0..65535; Default: any) Source Port of the packet
template (yes | no; Default: no) Creates a template and assigns it to specified policy group

Following parameters are used by template:

  • src-address, dst-address - Requested subnet must match in both directions(for example to allow all)
  • protocol - protocol to match, if set to all, then any protocol is accepted
  • proposal - SA parameters used for this template
  • level - useful when 'unique' is required in setups with multiple clients behind NAT.
tunnel (yes | no; Default: no) Specifies whether to use tunnel mode


Note: All packets are IPIP encapsulated in tunnel mode, and their new IP header's src-address and dst-address are set to sa-src-address and sa-dst-address values of this policy. If you do not use tunnel mode (id est you use transport mode), then only packets whose source and destination addresses are the same as sa-src-address and sa-dst-address can be processed by this policy. Transport mode can only work with packets that originate at and are destined for IPsec peers (hosts that established security associations). To encrypt traffic between networks (or a network and a host) you have to use tunnel mode.

Policy Stats

Command /ip ipsec policy print stats will show current status of the policy. Additional read-only parameters will be printed.

Property Description
in-accepted (integer) How many incoming packets were passed by the policy without an attempt to decrypt.
in-dropped (integer) How many incoming packets were dropped by the policy without an attempt to decrypt
in-transformed (integer) How many incoming packets were decrypted (ESP) and/or verified (AH) by the policy
out-accepted (integer) How many outgoing packets were passed by the policy without an attempt to encrypt.
out-dropped (integer) How many outgoing packets were dropped by the policy without an attempt to encrypt.
out-transformed (integer) How many outgoing packets were encrypted (ESP) and/or verified (AH) by the policy.
ph2-count (integer) Number of active phase2 sessions associated with the policy.
ph2-state (expired | no-phase2 | established) Indication of the progress of key establishing.

Policy Groups

Sub-menu: /ip ipsec policy group

Property Description
name (string; Default: )
comment (string; Default: )

Proposal settings

Sub-menu: /ip ipsec proposal

Proposal information that will be sent by IKE daemon to establish SAs for this policy ( Phase 2). Configured proposals are set in policy configuration.

Property Description
auth-algorithms (md5|sha1|null|sha256|sha512; Default: sha1) Allowed algorithms for authorization. sha1 is stronger, but slower algorithm.
comment (string; Default: ) Short description of an item.
disabled (yes | no; Default: no) Whether item is disabled.
enc-algorithms (null|des|3des|aes-128-cbc|aes-128-cbc|aes-128gcm|aes-192-cbc|aes-192-ctr|aes-192-gcm|aes-256-cbc|aes-256-ctr|aes-256-gcm|blowfish|camellia-128|camellia-192|camellia-256|twofish; Default: aes-128-cbc) Allowed algorithms and key lengths to use for SAs.
lifetime (time; Default: 30m) How long to use SA before throwing it out.
name (string; Default: ) Name of the proposal template, that will be identified in other parts of ipsec configuration.
pfs-group (ec2n155 | ec2n185 | modp1024 | modp1536 | modp2048 | modp3072 | modp4096 | modp6144 | modp768 | none; Default: modp1024) Diffie-Helman group used for Perfect Forward Secrecy.

Manual SA

Sub-menu: /ip ipsec manual-sa

Menu is used to configure SAs manually. Created SA template then can be used in policy configuration.

Property Description
ah-algorithm (in/out
in,out = md5|null|sha1
; Default: null)
Authentication Header encryption algorithm.
ah-key (string/string; Default: ) Incoming-authentication-key/outgoing-authentication-key
ah-spi (0x100..FFFFFFFF/0x100..FFFFFFFF; Default: 0x100) Incoming-SA-SPI/outgoing-SA-SPI
disabled (yes | no; Default: no) Defines whether item is ignored or used
esp-auth-algorithm (in/out
in,out = md5|null|sha1
; Default: null)
Encapsulating Security Payload authentication encryption algorithm
esp-auth-key (string/string; Default: ) Incoming-authentication-key/outgoing -authentication-key
esp-enc-algorithm (in/out
in,out = 3des | aes-128 | aes-192 | aes-256 | des | ...
; Default: null)
esp-enc-key (string/string; Default: ) Incoming-encryption-key/outgoing-encryption-key
esp-spi (0x100..FFFFFFFF/0x100..FFFFFFFF; Default: 0x100) Incoming-SA-SPI/outgoing-SA-SPI
lifetime (time; Default: 0s) Lifetime of this SA
name (string; Default: ) Name of the item for reference from policies

Installed SA

Sub-menu: /ip ipsec installed-sa

This facility provides information about installed security associations including the keys.

Property Description
AH (yes | no)
ESP (yes | no)
add-lifetime (time/time) Added lifetime for the SA in format soft/hard
  • soft - time period after which ike will try to establish new SA
  • hard - time period after which SA is deleted
addtime (time) Date and time when this SA was added.
auth-algorithm (sha1 | md5) Shows currently used authentication algorithm
auth-key (string) Shows used authentication key
current-bytes (64-bit integer) Shows number of bytes seen by this SA.
dst-address (IP)
enc-algorithm (des | 3des | aes ...) Shows currently used encryption algorithm
pfs (yes | no)
replay (integer)
spi (string)
src-address (IP)
state (string) Shows the current state of the SA ("mature", "dying" etc)

Flushing SAs

Sometimes after incorrect/incomplete negotiations took place, it is required to flush manually the installed SA table so that SA could be renegotiated. This option is provided by the /ip ipsec installed-sa flush command.

This command accepts only one property:

Property Description
sa-type (ah | all | esp; Default: all) Specifies SA types to flush:
  • ah - delete AH protocol SAs only
  • esp - delete ESP protocol SAs only
  • all - delete both ESP and AH protocols SAs

Remote Peers

Sub-menu: /ip ipsec remote-peers

This submenu provides you with various statistics about remote peers that currently have established phase 1 connections with this router. Note that if peer doesn't show up here, it doesn't mean that no IPsec traffic is being exchanged with it.

Read only properties:

Property Description
local-address (ip/ipv6 address) Local ISAKMP SA address on the router used by the peer
remote-address (ip/ipv6 address) Remote peer's ip/ipv6 address
side (initiator | responder) Shows which side initiated the Phase1 negotiation.
state (string) State of phase 1 negotiation with the peer. For example when phase1 and phase 2 are negotiated it will show state "established".
established (time) How long peers are in established state.

Closing all IPsec connections

Menu has a command to quickly close all established ipsec connections. This command will clear all installed SAs (Phase2) and remove all entries from remote-peers menu (Phase1).


/ip ipsec remote-peers kill-connections 


Sub-menu: /ip ipsec statistics

This menu shows various ipsec statistics

Property Description
in-errors (integer) All inbound errors that are not matched by other counters.
in-buffer-errors (integer) No free buffer.
in-header-errors (integer) Header error
in-no-states (integer) No state is found i.e. Either inbound SPI, address, or IPsec protocol at SA is wrong
in-state-protocol-errors (integer) Transformation protocol specific error, for example SA key is wrong or hardware accelerator is unable to handle amount of packets.
in-state-mode-errors (integer) Transformation mode specific error
in-state-sequence-errors (integer) Sequence number is out of window
in-state-expired (integer) State is expired
in-state-mismatches (integer) State has mismatched option, for example UDP encapsulation type is mismatched.
in-state-invalid (integer) State is invalid
in-template-mismatches (integer) No matching template for states, e.g. Inbound SAs are correct but SP rule is wrong. Possible cause is mismatched sa-source or sa-destination address.
in-no-policies (integer) No policy is found for states, e.g. Inbound SAs are correct but no SP is found
in-policy-blocked (integer) Policy discards
in-policy-errors (integer) Policy errors
out-errors (integer) All outbound errors that are not matched by other counters
out-bundle-errors (integer) Bundle generation error
out-bundle-check-errors (integer) Bundle check error
out-no-states (integer) No state is found
out-state-protocol-errors (integer) Transformation protocol specific error
out-state-mode-errors (integer) Transformation mode specific error
out-state-sequence-errors (integer) Sequence errors, for example Sequence number overflow
out-state-expired (integer) State is expired
out-policy-blocked (integer) Policy discards
out-policy-dead (integer) Policy is dead
out-policy-errors (integer) Policy error

Application Examples

Simple Mutual PSK XAuth Config

Server side config:

/ip ipsec peer
add address= auth-method=pre-shared-key-xauth secret="123" passive=yes

/ip ipsec user
add name=test password=345

Client side config:

/ip ipsec peer
add address= auth-method=pre-shared-key-xauth secret="123" \
  xauth-login=test xauth-password=345


Note: On server side it is mandatory to set passive to yes when XAuth is used.

Road Warrior setup with Mode Conf

Consider setup where worker need to access other co-workers (workstations) and local office server remotely. Office has two subnets:

  • for workstations
  • network that must not be reachable by RoadWarrior clients
  • for servers

And access to those networks should be secure.


Typically in RoadWarrior setups as this it is impossible to know from which address user will connect, so we need to set up generate-policy parameter on the server side. However this leads to other problems, client can generate any policy and access any network in the office. Even set and deny internet access to office workers.

Mode Conf, policy group and policy templates will allow us to overcome these problems.

IPsec Server Config

At first we need a pool from which RoadWarrior will will get an address. Typically in office you set up DHCP server for local workstations, the same DHCP pool can be used.

/ip pool
add name=ipsec-RW ranges=

Next we need to set up what settings to send to the client using Mode Conf.

/ip ipsec mode-config
add address-pool=ipsec-RW name=RW-cfg split-include=\,

As you can see we specified from which pool to give out address and two allowed subnets.

Now to allow only specific source/destination address in generated policies we will use policy group and create policy templates:

/ip ipsec policy group
add name=RoadWarrior

/ip ipsec policy
add dst-address= group=RoadWarrior src-address= \
add dst-address= group=RoadWarrior src-address= \

Now we just add xauth users and peer with enabled Mode Conf and policy group.

/ip ipsec user
add name=user1 password=123
add name=user2 password=234

/ip ipsec peer
add auth-method=pre-shared-key-xauth generate-policy=port-strict mode-config=RW-cfg \
    policy-template-group=RoadWarrior secret=123 passive=yes

Apple iOS (iPhone/iPad) Client

For iOS devices to be able to connect, proposal changes are needed:

  • does not work with 3des encryption algorithm, aes-128/256 works
  • auth algorithm must be sha1
  • PFS group must be none
  • lifetime must be 8 hours

Example of valid proposal configuration for iOS devices:

/ip ipsec proposal
set default enc-algorithms=aes-128-cbc,aes-256-cbc lifetime=8h \

Note: Iphone does not work with split-include If you set for older clients traffic will not be sent over the tunnel, for newer ios clients tunnel will not be established.

Android Client Notes

Android devices are trying to add policy with destination, so you have to make sure that correct policy template is added.

In our case we need to add:

/ip ipsec policy
add group=RoadWarrior dst-address= src-address= template=yes

RouterOS Client Config

/ip ipsec peer
add address= auth-method=pre-shared-key-xauth generate-policy=port-strict secret=123 \
     xauth-login=user1 xauth-password=123 mode-config=request-only

Shrew Client Config


Road Warrior setup Ikev2 RSA auth

Consider the same setup scenario as in Road Warrior setup with Mode Conf example.

Ikev2 Server Setup

Before we start to configure ipsec, we will need certificates. Some certificate requirements should be met to connect various devices to our server:

  • Common name should contain IP or DNS name of the server (required by Windows)
  • Subject Alt name should have IP or DNS of the server (required for other clients, like strongSwan client on Android)
  • EKU tls-server and tls-client is required for Windows.

Considering all requirements above, lets make server and client certificates:

add common-name=ca name=ca
sign ca ca-crl-host=
add common-name= subject-alt-name=IP: key-usage=tls-server name=server1
sign server1 ca=ca
add common-name=client1 key-usage=tls-client name=client1
sign client1 ca=ca
add common-name=client2 key-usage=tls-client name=client2

Now that we have certificates, server can be configured. Note that windows client requires modeconf, so we will use it to give out IP addresses from pool and send DNS, we also need to modify default template a little, to allow policies only from specific source addresses and generate unique level (required by multiple clients behind the same public IP):

/ip pool add name=rw-pool ranges=
/ip ipsec policy
set 0 level=unique dst-address=
/ip ipsec mode-conf
add name=cfg1 send-dns=yes address-pool=rw-pool address-prefix=32
/ip ipsec peer
add auth-method=rsa-signature certificate=server1 generate-policy=port-strict \
  mode-config=cfg1 passive=yes remote-certificate=none exchange-mode=ike2

Note: Windows uses point-to-point links so specifying any prefix other than 32 in mode-config settings will do nothing. Split include subnets are ignored as well


Note: Currently RouterOS does not support any of EAP authentication methods

RouterOS Client Config

First step is to export client certificate and key from the server:

/certificate export-certificate ca
/certificate export-certificate client1 export-passphrase=1234567890

Upload exported ca.crt, client1.crt and client1.key files to client's device and import with /certificate import command. When it is done set up the client

/ip ipsec peer add address= auth-method=rsa-signature certificate=client1 \
  mode-config=request-only exchange-mode=ike2 generate-policy=port-strict

Windows Client Config

Windows client does not allow to import certificate and key separately. So we must use external tool (for example, OpenSSL) to convert .crt and .key files to pkcs12 format.

openssl pkcs12 -export -out cl1.pfx -inkey cert_export_client1.key -in cert_export_client1.crt -certfile cert_export_ca.crt 

To import certificates, open Microsoft Management Console (mmc) Press Ctrl+M and add "Certificates" from the list and choose "Local Computer".


Now Right Click on "Personal" folder pick "All Tasks"->"Import...". Select cl1.pfx file.


CA and client certificate should appear in "Personal"-> "Certificates" folder. CA certificate need to be moved to Trusted Root list. Simply drag and drop CA to "Trusted Root Certificates" folder. Only client certificate should stay in "Personal".


Now you are ready to set up the client. After adding VPN tunnel choose VPN type IKEv2 and "Use machine certificates"


Android Client Notes

Native Android client does not support ikev2 at the moment. StrongSwan client from Play Store can be used to connect to ikev2 server. StrongSwan client the same as windows accept certificates and keys in pkcs12 format. So external tool is needed to convert exported .crt and .key files to .pfx and then import .pfx file.

After its imported you will see CA and Client cert in user certificates:


Now you can pick them in profile configuration.


Ca certificate is selected automatically as shown in screenshot below, but if for some reason you need to specify exact CA certificate, then unselect "Select automatically" and pick imported CA from the list.


IOS Client Notes


When installing certificates, IOS does not install CA certificate from pkcs12 bundle. Self-signed CA certificate must be installed separately.

RemoteID must be set equal to common-name or subjAltName of server's certificate, in configuration screenshots above server's address was "".

LocalID can be left blank.

Road Warrior setup Ikev1 RSA Auth

Creating Certificates

All certificates can be created on RouterOS server using certificate manager. See example >>

Ipsec Server Config

/ip ipsec policy group
add name=test

/ip ipsec peer
add auth-method=rsa-signature certificate=server exchange-mode=main \
    generate-policy=port-override passive=yes policy-template-group=test remote-certificate=none
/ip ipsec policy
add dst-address= group=test src-address= template=yes

Ipsec Client Config

Testing CRL

Now lets say client2 should not be able to connect anymore. We need to revoke its certificate so that it is excluded from CRL list.

issued-revoke client2

Notice R flag, which means that certificate is revoked

[admin@pe0] /certificate> print 
Flags: K - private-key, D - dsa, L - crl, C - smart-card-key, 
A - authority, I - issued, R - revoked, E - expired, T - trusted 
 #         NAME               COMMON-NAME               FINGERPRINT              
 0 K L A T myCa               myCa                      7fa636e6576495fe78f1a4...
 1 K   I T server             server                    cf0650a291bf4685f2fbd3...
 2 K   I   client1            client1                   26233de30e89b203b946ab...
 3 K   R   client2            client2                   cf172b62201befaf8d8966...

Now if you kill current connection client2 will no be able to establish phase1.

Site to Site IpSec Tunnel

Consider setup as illustrated below


Two remote office routers are connected to internet and office workstations behind routers are NATed. Each office has its own local subnet, for Office1 and for Office2. Both remote offices needs secure tunnel to local networks behind routers.

IP Connectivity

On both routers ether1 is used as wan port and ether2 is used to connect workstations. Also NAT rules are set tu masquerade local networks.

Office1 router:

/ip address
add address= interface=ether1
add address= interface=ether2

/ip route 
add gateway=

/ip firewall nat
add chain=srcnat out-interface=ether1 action=masquerade

Office2 router:

/ip address
add address= interface=ether1
add address= interface=ether2

/ip route 
add gateway=

/ip firewall nat
add chain=srcnat out-interface=ether1 action=masquerade

IpSec Peer's config

Next step is to add peer's configuration. We need to specify peers address and port and pre-shared-key. Other parameters are left to default values.

Office1 router:

/ip ipsec peer
add address= port=500 auth-method=pre-shared-key secret="test"

Office2 router:

/ip ipsec peer
add address= port=500 auth-method=pre-shared-key secret="test"

Policy and proposal

It is important that proposed authentication and encryption algorithms match on both routers. In this example we can use predefined "default" proposal

[admin@MikroTik] /ip ipsec proposal> print 
Flags: X - disabled 
 0   name="default" auth-algorithms=sha1 enc-algorithms=3des lifetime=30m 

As we already have proposal as a next step we need correct IpSec policy. We want to encrypt traffic coming form to and vice versa.

Office1 router:

/ip ipsec policy
add src-address= src-port=any dst-address= dst-port=any \
sa-src-address= sa-dst-address= \
tunnel=yes action=encrypt proposal=default

Office2 router:

/ip ipsec policy
add src-address= src-port=any dst-address= dst-port=any \
sa-src-address= sa-dst-address= \
tunnel=yes action=encrypt proposal=default

Note that we configured tunnel mode instead of transport, as this is site to site encryption.

NAT and Fasttrack Bypass

At this point if you will try to establish IpSec tunnel it will not work, packets will be rejected. This is because both routers have NAT rules that is changing source address after packet is encrypted. Remote router receives encrypted packet but is unable to decrypt it because source address do not match address specified in policy configuration. For more information see packet flow ipsec example.

To fix this we need to set up NAT bypass rule.

Office1 router:

/ip firewall nat
add chain=srcnat action=accept  place-before=0 \
 src-address= dst-address=

Office2 router:

/ip firewall nat
add chain=srcnat action=accept  place-before=0 \
 src-address= dst-address=

Note: If you previously tried to establish tunnel before NAT bypass rule was added, you have to clear connection table from existing connection or restart the routers

It is very important that bypass rule is placed at the top of all other NAT rules.

Another issue is if you have fasttrack enabled, packet bypasses ipsec policies. So we need to add accept rule before fasttrack

/ip firewall filter
add chain=forward action=accept place-before=1
 src-address= dst-address= connection-state=established,related
add chain=forward action=accept place-before=1
 src-address= dst-address= connection-state=established,related

However this can add significant load to CPU if there is a fair amount of tunnels and significant traffic on each tunnel.

Solution is to use RAW firewall tables to bypass connection tracking, that way eliminating need of filter rules listed above and reducing load on CPU by approximately 30%.

/ip firewall raw
add action=notrack chain=prerouting src-address= dst-address=
add action=notrack chain=prerouting src-address= dst-address=

Ipsec/L2TP behind NAT

Consider setup as illustrated below


Client needs secure connection to the office with public address, but server does not know what will be the source address from which client connects. It is so called road-warrior setup. Our client will also be located behind the router with enabled NAT.

For the setup RouterOS router will be used as the client device behind NAT (it can be any device: Windows PC, Smartphone, Linux PC, etc.)

IP Connectivity

On the server:

/ip address 
add address= interface=ether1

/ip route
add gateway=

On the clients router:

/ip address 
add address= interface=ether1
add address= interface=ether2

/ip route
add gateway=

/ip firewall nat
add chain=srcnat action=masquerade out-interface=ether1

On the client:

/ip address
add address= interface=ether1

L2TP Config

On the server:

/interface l2tp-server 
set enabled=yes profil=default

/ip pool 
add name=l2tp-pool ranges=

/ppp profile 
set default local-address= remote-address=l2tp-pool

/ppp secret
add name=l2tp-test password=test123456

On the client:

/interface l2tp-client
add connect-to= disabled=no name=l2tp-out1 password=password user=l2tp-test

IpSec Config

On server side:

/ip ipsec proposal
set [ find default=yes ] enc-algorithms=3des,aes-128,aes-192,aes-256
/ip ipsec peer
add generate-policy=yes hash-algorithm=sha1 nat-traversal=yes secret=test123456

RouterOS as client:

/ip ipsec proposal
set [ find default=yes ] enc-algorithms=aes-128
/ip ipsec peer
add address= hash-algorithm=sha1 nat-traversal=yes secret=test123456

/ip ipsec policy
add dst-address= protocol=udp sa-dst-address= \
      sa-src-address= src-address=

Notice that nat-traversal is enabled. This option is required because Ipsec connection will be established through the NAT router otherwise Ipsec will not be able to establish phase2.


Warning: Only one L2TP/IpSec connection can be established through the NAT. Which means that only one client can connect to the sever located behind the same router.

Apple iOS (iPhone/iPad) Client


You must choose L2TP as VPN type in iOS to connect to the IPsec/L2TP server on RouterOS (this includes the default IPsec server created by QuickSet VPN checkbox).

Allow Only Ipsec Ecapsulated Traffic

There are some scenarios where for security reasons you would like to drop access from/to specific networks if incoming/outgoing packets are not encrypted. For example, If we have L2TP/Ipsec setup we would want to drop non encrypted L2TP connection attempts.

There are several ways how to achieve this:

  • Using ipsec policy matcher in firewall;
  • Using generic ipsec policy with action=drop and lower priority (can be used in road warrior setups where dynamic policies are generated);
  • By setting DSCP or priority in mangle and matching the same values in firewall after decapsulation.

Ipsec Policy Matcher

Lets start by typical rules, accept established,related, accept ESP protocol and accept UDP 500 and 4500 required by ipsec.

/ip firewall filter
add chain=input comment=established,related connection-state=\
    established,related in-interface=WAN
add chain=input comment=ESP in-interface=WAN protocol=ipsec-esp
add chain=input comment="UDP 500,4500" protocol=udp port=500,4500 \

Now lets set up ipsec policy matcher to accept all packets that matched any of ipsec policies and drop the rest

add chain=input comment="ipsec policy matcher" in-interface=WAN \
add action=drop chain=input comment="drop all" in-interface=WAN log=yes

Ipsec policy matcher takes two parameters direction, policy. We used incoming direction and ipsec policy. Ipsec policy option allows us to inspect packets after decapsulation, so for example if we want to allow only Gre encapsulated packet from specific source address and drop the rest we could set up following rules

add chain=input comment="ipsec policy matcher" in-interface=WAN \
    ipsec-policy=in,ipsec protocol=gre src=address=
add action=drop chain=input comment="drop all" in-interface=WAN log=yes

Using generic Ipsec Policy

The trick of this method is to add default policy with action drop. Lets assume we are running L2TP/IpSec server with public address and we want to drop all non encrypted L2TP:

/ip ipsec policy
add src-address= dst-address= sa-src-address= \
  protocol=udp src-port=1701 tunnel=yes action=drop

Now router will drop any L2TP unencrypted incoming traffic, but after successful L2TP/Ipsec connection dynamic policy is created with higher priority than it is on default static rule and packets matching that dynamic rule can be forwarded.

[admin@rack2_10g1] /ip ipsec policy> print
Flags: T - template, X - disabled, D - dynamic, I - inactive, * - default
 0 T * group=default src-address=::/0 dst-address=::/0 protocol=all
       proposal=default template=yes

 1     src-address= src-port=1701 dst-address=
       dst-port=any protocol=udp action=discard level=unique
       ipsec-protocols=esp tunnel=yes sa-src-address=
       sa-dst-address= proposal=default manual-sa=none priority=0

 2  D  src-address= src-port=1701 dst-address=
       dst-port=any protocol=udp action=encrypt level=require
       ipsec-protocols=esp tunnel=no sa-src-address=
       sa-dst-address= priority=2

Connecting with Shrew Client and allowing only Encrypted traffic


Problem: Windows Error 809 when connecting to Ipsec server located behind NAT.

Solution: Windows operating systems do not support NAT-T security associations to servers that are located behind a NAT device. Workaround is possible by modifying Windows registry. Read more here

[ Top | Back to Content ]